Esempio n. 1
0
        private static void EditProto(Proto proto)
        {
            if (proto is ItemProto itemProto)
            {
                if (itemUpgradeList.ContainsKey(itemProto.ID))
                {
                    itemProto.Grade = itemUpgradeList[itemProto.ID];
                    LogSource.LogDebug("Changing grade of " + itemProto.name);
                }

                if (itemProto.Grade == 0 || items.ContainsKey(itemProto.ID))
                {
                    return;
                }

                foreach (var kv in items)
                {
                    if (kv.Value.Grade == 0 || kv.Value.Upgrades == null)
                    {
                        continue;
                    }
                    if (itemProto.Grade > kv.Value.Upgrades.Length)
                    {
                        continue;
                    }

                    if (kv.Value.Upgrades[itemProto.Grade - 1] == itemProto.ID)
                    {
                        itemProto.Upgrades = kv.Value.Upgrades;
                        LogSource.LogDebug("Updating upgrade list of " + itemProto.name);
                    }
                }
            }
        }
        public void UpdateCopiedPrefab(GameObject Prefab)
        {
            this.Prefab = Prefab;

            Piece piece = Prefab.GetComponent <Piece>();

            piece.m_name        = "$piece_seed_totem_name";
            piece.m_description = "$piece_seed_totem_description";
            piece.m_clipGround  = true;
            piece.m_groundPiece = true;
            piece.m_groundOnly  = true;
            piece.m_noInWater   = true;
            foreach (GuidePoint guidePoint in Prefab.GetComponentsInChildren <GuidePoint>())
            {
                guidePoint.m_text.m_key   = localizationName;
                guidePoint.m_text.m_topic = ravenTopic;
                guidePoint.m_text.m_text  = ravenText;
                guidePoint.m_text.m_label = ravenLabel;
            }

            prefabSeedTotem = Prefab.AddComponent <SeedTotem>();
            PrivateArea privateArea = Prefab.GetComponent <PrivateArea>();

            if (privateArea != null)
            {
                logger.LogDebug("Converting PrivateArea to SeedTotem");
                SeedTotem.CopyPrivateArea(prefabSeedTotem, privateArea);
                logger.LogDebug("Destroying redundant PrivateArea: " + privateArea);
                Object.DestroyImmediate(privateArea);
            }

            RegisterPiece();
        }
Esempio n. 3
0
        public static void ToggleLocked(bool?b = null)
        {
            cameraControl = Object.FindObjectsOfType <Studio.CameraControl>().OrderBy(m => m.transform.GetSiblingIndex()).Last();
            Logger.LogDebug($"Get CameraControl: {cameraControl.gameObject.name}");

            if (null == b)
            {
                Locked = !Locked;
            }
            else
            {
                Locked = (bool)b;
            }

            if (Locked)
            {
                LockBtn.GetComponent <Image>().sprite = ImageHelper.LoadNewSprite("StudioCharaLightLinkedToCamera.Resources.lock.png", 36, 36);

                //Set value for calc
                Vector3 ligLocal = (studioLightCalc.GetField("light") as Light).transform.localEulerAngles;
                ComputeAngle.SetAngle(
                    ligLocal,
                    new Vector2(chaLight.rot[0], chaLight.rot[1]),
                    cameraControl.cameraAngle
                    );
            }
            else
            {
                LockBtn.GetComponent <Image>().sprite = ImageHelper.LoadNewSprite("StudioCharaLightLinkedToCamera.Resources.lock_open.png", 36, 36);
            }

            Logger.LogDebug("Locked status: " + Locked);
        }
Esempio n. 4
0
        public void OnSceneUnloaded(Scene scene)
        {
            if (!isTransparent || scene.name != SceneName)
            {
                return;
            }

            if (isTransparent)
            {
                SceneName = "";
                if (null != Window)
                {
                    StartCoroutine(TransparentCoroutine());
                }
                else
                {
                    if (isOriginalFullScreen)
                    {
                        SetFullScreen(true);
                        isOriginalFullScreen = false;
                    }
                }
                Logger.LogDebug($"Scene unload: {scene.name}");
            }
        }
Esempio n. 5
0
        internal static bool EnabledForCurrentHeroine()
        {
            var result = CurrentlyEnabled && _logic.EnabledForHeroine(TargetHeroine);

            Logger.LogDebug($"EnabledForCurrentHeroine => {result}");
            return(result);
        }
Esempio n. 6
0
 public static void Debug(string str)
 {
     if (UsingDevMessage)
     {
         LogInstance?.LogDebug(str);
     }
 }
Esempio n. 7
0
        public StudioSceneNavigation()
        {
            _lastLoadedScenes = new SimpleLazy <Dictionary <string, string> >(() =>
                                                                              TrackLastLoadedSceneEnabled.Value ? LoadTrackingFile() : new Dictionary <string, string>());

            _isSceneValid = new SimpleLazy <Func <string, bool> >(() =>
            {
                var pluginInfo = Chainloader.PluginInfos.Where(pi => pi.Key.EndsWith("InvalidSceneFileProtection"))
                                 .Select(pi => pi.Value).FirstOrDefault();
                if (pluginInfo == null)
                {
                    return(_ => true);
                }

                var pluginType = pluginInfo.Instance.GetType();
                var method     = AccessTools.Method(pluginType, "IsFileValid");
                if (method == null)
                {
                    return(_ => true);
                }

                Logger.LogDebug(
                    $"Will use {pluginType.Name}.{method.Name} to pre-check images during navigation");
                return((Func <string, bool>)Delegate.CreateDelegate(typeof(Func <string, bool>), method));
            });

            _saveTrackingFileDelay = new WaitUntil(IsSaveReady);
        }
Esempio n. 8
0
        /// <summary>
        /// 載入sample chara
        /// </summary>
        /// <param name="stream">角色圖片讀取為Stream</param>
        public static void LoadSampleChara(Stream stream)
        {
            Hooks.BlockChanging = true;
            SampleChara.chaFile = new ChaFileControl();
            SampleChara.chaFile.Invoke("LoadCharaFile", new object[] { stream, true, true });
            Logger.LogDebug("Loaded sample chara: " + SampleChara.chaFile.parameter.fullname);
            Hooks.BlockChanging = false;
            ChaFileFace face = MessagePackSerializer.Deserialize <ChaFileFace>(MessagePackSerializer.Serialize <ChaFileFace>(SampleChara.chaFile.custom.face));
            ChaFileBody body = MessagePackSerializer.Deserialize <ChaFileBody>(MessagePackSerializer.Serialize <ChaFileBody>(SampleChara.chaFile.custom.body));

            //Logger.LogMessage("Length Face: " + face.shapeValueFace.Length);
            //Logger.LogMessage("Length Body: " + body.shapeValueBody.Length);
            SampleChara.shapeValueFace = face.shapeValueFace.ToList();
            SampleChara.shapeValueBody = body.shapeValueBody.ToList();

            SampleChara.ABMXData = MessagePackSerializer.Deserialize <PluginData>(MessagePackSerializer.Serialize(ExtendedSave.GetExtendedDataById(SampleChara.chaFile, "KKABMPlugin.ABMData")));
            if (FBIOpenUp._isABMXExist && null != SampleChara.ABMXData)
            {
                Logger.LogDebug("Loaded sample chara ABMX");
            }
            else
            {
                Logger.LogDebug("NO sample chara ABMX");
            }
        }
Esempio n. 9
0
        public static void Disassemble(ManualLogSource logSource, IntPtr memoryPtr, int size)
        {
            var data = new byte[size];

            Marshal.Copy(memoryPtr, data, 0, size);

            var formatter  = new NasmFormatter();
            var output     = new StringOutput();
            var codeReader = new ByteArrayCodeReader(data);
            var decoder    = Decoder.Create(64, codeReader);

            decoder.IP = (ulong)memoryPtr.ToInt64();
            while (codeReader.CanReadByte)
            {
                decoder.Decode(out var instr);
                formatter.Format(instr, output);
                logSource.LogDebug($"{instr.IP:X16} {output.ToStringAndReset()}");

                if (instr.Code == Code.Jmp_rm64 && instr.Immediate32 == 0
                    ) // && instr.IsIPRelativeMemoryOperand && instr.IPRelativeMemoryAddress = 6
                {
                    var address = new byte[8];

                    for (var i = 0; i < 8; i++)
                    {
                        address[i] = (byte)codeReader.ReadByte();
                    }

                    logSource.LogDebug($"{instr.IP + (ulong) instr.Length:X16} db 0x{BitConverter.ToUInt64(address, 0):X16}");
                    decoder.IP += 8;
                }
            }
        }
Esempio n. 10
0
        private void LoadAllUnityArchives(ZipFile arc, string archiveFilename)
        {
            foreach (ZipEntry entry in arc)
            {
                if (entry.Name.EndsWith(".unity3d", StringComparison.OrdinalIgnoreCase))
                {
                    string assetBundlePath = entry.Name;

                    if (assetBundlePath.Contains('/'))
                    {
                        assetBundlePath = assetBundlePath.Remove(0, assetBundlePath.IndexOf('/') + 1);
                    }

                    AssetBundle getBundleFunc()
                    {
                        AssetBundle bundle;

                        if (entry.CompressionMethod == CompressionMethod.Stored)
                        {
                            long index = (long)locateZipEntryMethodInfo.Invoke(arc, new object[] { entry });

                            if (DebugLogging.Value)
                            {
                                Logger.LogDebug($"Streaming \"{entry.Name}\" ({GetRelativeArchiveDir(archiveFilename)}) unity3d file from disk, offset {index}");
                            }

                            bundle = AssetBundle.LoadFromFile(archiveFilename, 0, (ulong)index);
                        }
                        else
                        {
                            Logger.LogDebug($"Cannot stream \"{entry.Name}\" ({GetRelativeArchiveDir(archiveFilename)}) unity3d file from disk, loading to RAM instead");
                            var stream = arc.GetInputStream(entry);

                            byte[] buffer = new byte[entry.Size];

                            stream.Read(buffer, 0, (int)entry.Size);

                            BundleManager.RandomizeCAB(buffer);

                            bundle = AssetBundle.LoadFromMemory(buffer);
                        }

                        if (bundle == null)
                        {
                            Logger.LogError($"Asset bundle \"{entry.Name}\" ({GetRelativeArchiveDir(archiveFilename)}) failed to load. It might have a conflicting CAB string.");
                        }

                        return(bundle);
                    }

                    BundleManager.AddBundleLoader(getBundleFunc, assetBundlePath, out string warning);

                    if (!string.IsNullOrEmpty(warning) && ModLoadingLogging.Value)
                    {
                        Logger.LogWarning($"{warning} in \"{GetRelativeArchiveDir(archiveFilename)}\"");
                    }
                }
            }
        }
Esempio n. 11
0
        public static int ApplyToolCostModifiers(Agent agent, int baseCost)
        {
            logger.LogDebug($"{MethodBase.GetCurrentMethod().Name} ( agent = '{agent.agentName}', baseCost = '{baseCost}'");
            float costFactor = TamperTantrum.GetToolCostFactor(agent)
                               * TamperTantrum2.GetToolCostFactor(agent);

            return(Mathf.FloorToInt(baseCost * costFactor));
        }
Esempio n. 12
0
        internal void ScanHammer(bool lateAdd)
        {
            try
            {
                logger.LogDebug("Scanning Hammer PieceTable for Pieces");
                foreach (GameObject hammerRecipe in PieceManager.Instance.GetPieceTable("Hammer").m_pieces)
                {
                    if (hammerRecipe == null)
                    {
                        logger.LogWarning("null recipe in Hammer PieceTable");
                        continue;
                    }
                    Piece piece = hammerRecipe.GetComponent <Piece>();

                    if (piece.name == "piece_repair")
                    {
                        if (!addedHammer)
                        {
                            PieceTable planHammerPieceTable = PieceManager.Instance.GetPieceTable(PlanHammerPrefabConfig.pieceTableName);
                            if (planHammerPieceTable != null)
                            {
                                planHammerPieceTable.m_pieces.Add(hammerRecipe);
                                addedHammer = true;
                            }
                        }
                        continue;
                    }
                    if (planPiecePrefabConfigs.ContainsKey(piece.name))
                    {
                        continue;
                    }
                    if (!piece.m_enabled ||
                        piece.GetComponent <Ship>() != null ||
                        piece.GetComponent <Plant>() != null ||
                        piece.GetComponent <TerrainModifier>() != null ||
                        piece.m_resources.Length == 0)
                    {
                        continue;
                    }
                    PlanPiecePrefabConfig prefabConfig = new PlanPiecePrefabConfig(piece);
                    PieceManager.Instance.AddPiece(prefabConfig);
                    planPiecePrefabConfigs.Add(piece.name, prefabConfig);
                    PrefabManager.Instance.RegisterToZNetScene(prefabConfig.PiecePrefab);
                    if (lateAdd)
                    {
                        PieceTable pieceTable = PieceManager.Instance.GetPieceTable(PlanHammerPrefabConfig.pieceTableName);
                        if (!pieceTable.m_pieces.Contains(prefabConfig.PiecePrefab))
                        {
                            pieceTable.m_pieces.Add(prefabConfig.PiecePrefab);
                        }
                    }
                }
            }
            finally
            {
                PieceManager.OnPiecesRegistered -= ScanHammer;
            }
        }
Esempio n. 13
0
        public static bool AddPointsLate_Prefix(string pointsType, int extraNum, ref IEnumerator __result, SkillPoints __instance,
                                                ref Agent ___agent)
        {
            logger.LogDebug("SkillPoints_AddPointsLate");

            __result = AddPointsLate_Enumerator(pointsType, extraNum, __instance, ___agent);

            return(false);
        }
Esempio n. 14
0
        public static void SpawnEmployees(Agent playerAgent, int numberToSpawn, string agentType, LoadLevel __instance, string relationship)
        {
            logger.LogDebug("SpawnEmployees");

            for (int i = 0; i < numberToSpawn; i++)
            {
                GC.spawnerMain.SpawnAgent(GC.tileInfo.FindLocationNearLocation(playerAgent.tr.position, playerAgent, 0.32f, 0.96f, true, false), playerAgent,
                                          agentType, "FriendPhone", playerAgent);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// <c>[Received 'ExampleMessage' from server]</c>
        /// <br/>
        /// <c>[Received 'ExampleMessage' from client 'usernamehere']</c>
        /// </summary>
        /// <param name="netMessage"></param>
        /// <param name="source"></param>
        public static void LogMessageReceived(object netMessage, bool fromServer, string source = "")
        {
            string typeName   = netMessage.GetType().Name;
            string fullSource = fromServer ? "server" : "client";

            if (!string.IsNullOrWhiteSpace(source))
            {
                fullSource += $" '{source}'";
            }

            Logger.LogDebug($"[Received '{typeName}' from {fullSource}]");
        }
Esempio n. 16
0
 internal void Awake()
 {
     try
     {
         var harmony = new HarmonyLib.Harmony(ID);
         harmony.PatchAll();
         MyLogger.LogDebug("Awaken");
     }
     catch (Exception ex)
     {
         MyLogger.LogError(ex.Message);
     }
 }
Esempio n. 17
0
        private void AddAction(Type action)
        {
            if (!typeof(BaseAction).IsAssignableFrom(action))
            {
                _logger.LogWarning($"Action {action} was of wrong type");
                return;
            }

            var type = action.Name.Underscore();

            _actions.Add(type, action);
            _logger.LogDebug($"Added action: {type}");
        }
Esempio n. 18
0
        private void Connect(IPEndPoint endPoint, Key32?hostKey, JoinSecret secret, OnH3ClientDisconnect onDisconnect)
        {
            _clientLog.LogInfo($"Connecting to {endPoint}...");

            float  ups = 1 / Time.fixedDeltaTime;
            double tps = 1 / secret.TickDeltaTime;

            _clientLog.LogDebug($"Fixed update rate: {ups:.00} u/s");
            _clientLog.LogDebug($"Tick rate: {tps:.00} t/s");

            var request = new ConnectionRequestMessage(secret.Key, hostKey);

            Client = new H3Client(_clientLog, _config.Client, Activity, _messages.Client, _messages.ChannelsCount, secret.TickDeltaTime, _version, endPoint, request, onDisconnect);
        }
Esempio n. 19
0
        private void LoadMods()
        {
            Logger.LogInfo("Loading mods...");
            var mods     = new List <Mod>();
            var modsPath = Path.Combine(Paths.GameRootPath, H3VR.Sideloader.Shared.Info.MODS_DIR);

            Directory.CreateDirectory(modsPath);
            var modIds = new HashSet <string>(); // TODO: Make more elaborate (check version, etc)

            void LoadMods(IEnumerable <string> paths, Func <string, Mod> loader)
            {
                foreach (var path in paths)
                {
                    try
                    {
                        var mod = loader(path);
                        if (modIds.Contains(mod.Manifest.Guid))
                        {
                            Logger.LogWarning(
                                $"Skipping [{mod.Name}] because a mod with same GUID ({mod.Manifest.Guid}) was already loaded (check logs)");
                            continue;
                        }

                        Logger.LogDebug($"Loading {mod.Name}");
                        modIds.Add(mod.Manifest.Guid);
                        mods.Add(mod);
                    }
                    catch (Exception e)
                    {
                        Logger.LogWarning($"Skipping {path} because: ({e.GetType()}) {e.Message}");
                    }
                }
            }

            LoadMods(Directory.GetDirectories(modsPath, "*", SearchOption.TopDirectoryOnly), Mod.LoadFromDir);
            LoadMods(Extensions.GetAllFiles(modsPath, H3VR.Sideloader.Shared.Info.ModExts.Select(s => $"*.{s}").ToArray()),
                     Mod.LoadFromZip);

            // TODO: Sanity checking etc

            foreach (var loader in loaders)
            {
                Logger.LogDebug($"Loading {loader}");
                loader.Initialize(mods);
            }


            Logger.LogInfo($"Loaded {mods.Count} mods!");
        }
        private static IEnumerator AutoSaveCo()
        {
#if DEBUG
            BepLogger.LogDebug("CoRoutine Engaged...");
#endif

            while (true)
            {
                yield return(new WaitForSecondsRealtime(Math.Max(AutoSaveInterval.Value, 60) - 6));

                if (AutoSaveText.Value)
                {
                    ScreenText.SetState(true);

                    int i = 6;

                    while (i-- != 0)
                    {
                        ScreenText.Text = $"Autosaving in {i + 1} seconds...";

                        if (i + 1 > 4)
                        {
                            ScreenText.Color = Color.green;
                        }
                        else if (i + 1 > 2)
                        {
                            ScreenText.Color = Color.yellow;
                        }
                        else
                        {
                            ScreenText.Color = Color.red;
                        }

                        yield return(new WaitForSecondsRealtime(1));
                    }
                }
                else
                {
                    yield return(new WaitForSecondsRealtime(6));
                }

                IsAutoSaving = true;
                this4.PresetSave(m_maid, CharacterMgr.PresetType.All);
                IsAutoSaving = false;

                ScreenText.SetState(false);
            }
        }
        public static Dictionary <int, RewiredInputs> m_playerInputManager = (Dictionary <int, RewiredInputs>) typeof(ControlsInput).GetField("m_playerInputManager", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); // null for static field

        //
        // USE THIS METHOD TO EASILY ADD ACTIONS AND KEYBINDINGS FOR YOUR MOD
        //
        // The name arg is displayed in the keybindings menu
        //
        // The categoryId arg determines where in the keybindings list this action will appear
        //
        // The showForController arg determines if this action can also be bound to a controller
        //
        // The sectionId arg is a weird number. It somehow affects where in the list of keybindings
        // the action appears but I haven't figured out yet what it means. I just try different numbers
        // from 0-5 until I'm happy with where in the list the keybind ends up
        //
        public static void AddAction(string name, KeybindingsCategory categoryId, ControlType controlType, int sectionId = 0, InputActionType type = InputActionType.Button)
        {
            // The user does not have to initialize or instantiate anything themselves to use custom keybinds
            // Just call AddAction() and we'll make sure the plumbing is there
            if (orig_Initialize == null)
            {
                InitHooks();
            }

            // Capture the info the user has specified for the action they would like to create
            InputActionDescription protoAction = new InputActionDescription(name, (int)categoryId, controlType, sectionId, type);

            myActionInfos.Add(protoAction);

            // If this method is called after InputManager_Base.Initialize() has been called, then these actions won't be added
            // So let's report that back to the mod maker to avoid headaches
            bool shouldReportTooLateAdd = false;

            if (shouldReportTooLateAdd)
            {
                bool alreadyInitialized = (bool)typeof(ReInput).GetProperty("initialized", BindingFlags.NonPublic | BindingFlags.Static).GetGetMethod(true).Invoke(null, null);
                if (alreadyInitialized)
                {
                    MyLogger.LogDebug("Tried to add action too late. Add your action earlier in the life cycle.");
                }
            }
        }
Esempio n. 22
0
        private static void LoadAssets()
        {
            var resource = ResourceUtils.GetEmbeddedResource("crests");

            Bundle = AssetBundle.LoadFromMemory(resource);
            DontDestroyOnLoad(Bundle);

            var textAsset = Bundle.LoadAsset <TextAsset>("crestinfo");
            var infoText  = textAsset.text;

            Destroy(textAsset);

            var xd = XDocument.Parse(infoText);
            // ReSharper disable PossibleNullReferenceException
            var infoElements = xd.Root.Elements("Crest");
            var crestInfos   = infoElements
                               .Select(x => new CrestInfo(
                                           x.Element("ID").Value,
                                           x.Element("Name").Value,
                                           x.Element("Description").Value,
                                           Bundle));

            // ReSharper restore PossibleNullReferenceException
            foreach (var crestInfo in crestInfos)
            {
                Logger.LogDebug("Added crest " + crestInfo.Id);
                CrestInfos.Add(crestInfo.Id, crestInfo);
            }

            //todo use custom material in the future? might allow glow effects, showing through clothes, adjusting crest location
            //var mat = new Material(Shader.Find("Standard"));
            //ChaControl.rendBody.materials = ChaControl.rendBody.materials.Where(x => x != mat).AddItem(mat).ToArray();
        }
Esempio n. 23
0
        internal static void ProcessQueue(List <QueueItem> Queue)
        {
            ChaControl chaCtrl       = MakerAPI.GetCharacterControl();
            object     MEpluginCtrl  = MaterialEditor.GetController(chaCtrl);
            object     HACpluginCtrl = HairAccessoryCustomizer.GetController(chaCtrl);
            object     ASSpluginCtrl = AccStateSync.GetController(chaCtrl);
            object     MRpluginCtrl  = MaterialRouter.GetController(chaCtrl);
            object     DBEpluginCtrl = DynamicBoneEditor.GetController(chaCtrl);
            object     APKpluginCtrl = AAAPK.GetController(chaCtrl);

            HairAccessoryCustomizer.HairAccessoryInfos = new Dictionary <int, HairAccessoryCustomizer.HairAccessoryInfo>();
            int Coordinate = chaCtrl.fileStatus.coordinateType;

            foreach (QueueItem item in Queue)
            {
                Logger.LogDebug($"{item.srcSlot} -> {item.dstSlot}");
                HairAccessoryCustomizer.StoreSetting(chaCtrl, HACpluginCtrl, item.srcSlot);                 // need to do this before move PartsInfo
                MoreAccessories.ModifyPartsInfo(chaCtrl, Coordinate, item.srcSlot, item.dstSlot);
                MaterialEditor.ModifySetting(MEpluginCtrl, Coordinate, item.srcSlot, item.dstSlot);
                AccStateSync.ModifySetting(ASSpluginCtrl, Coordinate, item.srcSlot, item.dstSlot);
                MaterialRouter.ModifySetting(MRpluginCtrl, Coordinate, item.srcSlot, item.dstSlot);
                DynamicBoneEditor.ModifySetting(DBEpluginCtrl, Coordinate, item.srcSlot, item.dstSlot);
                AAAPK.ModifySetting(APKpluginCtrl, Coordinate, item.srcSlot, item.dstSlot);
            }

            ChaCustom.CustomBase.Instance.chaCtrl.ChangeCoordinateTypeAndReload(false);
            ChaCustom.CustomBase.Instance.updateCustomUI = true;

            foreach (QueueItem item in Queue)
            {
                HairAccessoryCustomizer.ModifySetting(HACpluginCtrl, item.srcSlot, item.dstSlot);                 // need to do this after updateCustomUI
            }
        }
Esempio n. 24
0
        /// <summary>
        ///   <para>Creates a new <see cref="CustomName"/> with the specified <paramref name="id"/>, <paramref name="type"/> and <paramref name="info"/>.</para>
        /// </summary>
        public static CustomName CreateCustomName(string id, string type, CustomNameInfo info)
        {
            CustomName customName = GetCustomName(id, type);

            if (customName != null)
            {
                string message = string.Concat("A CustomName with Id \"", id, "\" and Type \"", type, "\" already exists!");
                Logger.LogError(message);
                throw new ArgumentException(message, nameof(id));
            }
            CustomNames.Add(customName = new CustomName(id, type, info));

            Logger.LogDebug(string.Concat("A CustomName with Id \"", id, "\" and Type \"", type, "\" was created."));

            return(customName);
        }
Esempio n. 25
0
 public static void LogTrace(string message)
 {
     if (ConfigurationManager.GeneralConfig?.EnableTraceLogging?.Value == true)
     {
         Logger?.LogDebug($"{message}");
     }
 }
Esempio n. 26
0
        private void PrintHealth()
        {
            uint sent     = _health.Sent;
            uint received = _health.Received;

            uint lost = sent - received;
            var  loss = (float)lost / sent;

            double      rttAvg       = _time.Rtt;
            double      offsetAvg    = _time.Offset;
            DoubleRange offsetBounds = _time.OffsetBounds;

            double rttMad     = _health.RttAbsoluteDeviation.Value;
            double rttMapd    = rttMad / rttAvg;
            double offsetMad  = _health.OffsetAbsoluteDeviation.Value;
            double offsetMapd = offsetMad / offsetAvg;

            // Yeah we could just format/concat and make it infinitely easier to read/write but the perf gaiiiinnnnsss
            var builder = new StringBuilder().AppendLine()             // newline
                          .Append("┌─CONNECTION HEALTH REPORT───").AppendLine()
                          .Append("│       Packet─────loss : ").Append(loss.ToString("P1")).Append(" (").Append(lost).Append(" / ").Append(sent).AppendLine(")")
                          .Append("│          RTT─┬──value : ").Append((rttAvg * 1000).ToString("N0")).AppendLine(" ms")
                          .Append("│              ├────MAD : ").Append((rttMad * 1000).ToString(".0")).AppendLine(" ms")
                          .Append("│              └───MAPD : ").AppendLine(rttMapd.ToString("P"))
                          .Append("│ Clock offset─┬──value : ").Append(offsetAvg.ToString(".000")).AppendLine(" s")
                          .Append("│              ├─bounds : ").Append(offsetBounds.Minimum.ToString(".000")).Append(" s <= x <= ").Append(offsetBounds.Maximum.ToString(".000")).AppendLine(" s")
                          .Append("│              ├────MAD : ").Append(offsetMad.ToString(".000")).AppendLine(" s")
                          .Append("│              └───MAPD : ").AppendLine(offsetMapd.ToString("P"))
                          .Append("└────────────────────────────");

            _log.LogDebug(builder.ToString());

            _health.Sent     = 0;
            _health.Received = 0;
        }
Esempio n. 27
0
        private void GenerateTrampolineInner(out int trampolineLength, out int jmpLength)
        {
            if (TrampolinePtr != IntPtr.Zero)
            {
                trampolineLength = TrampolineSize;
                jmpLength        = TrampolineJmpSize;
                return;
            }

            var instructionBuffer = new byte[32];

            Marshal.Copy(OriginalFunctionPtr, instructionBuffer, 0, 32);

            var trampolineAlloc = PageAllocator.Instance.Allocate(OriginalFunctionPtr);

            logger.LogDebug($"Original: {OriginalFunctionPtr.ToInt64():X}, Trampoline: {(long) trampolineAlloc:X}, diff: {Math.Abs(OriginalFunctionPtr.ToInt64() - trampolineAlloc):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalFunctionPtr, trampolineAlloc)}");

            DetourHelper.Native.MakeWritable(trampolineAlloc, PageAllocator.PAGE_SIZE);

            var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;

            DetourGenerator.CreateTrampolineFromFunction(instructionBuffer, OriginalFunctionPtr, trampolineAlloc,
                                                         DetourGenerator.GetDetourLength(arch), arch,
                                                         out trampolineLength, out jmpLength);

            DetourHelper.Native.MakeExecutable(trampolineAlloc, PageAllocator.PAGE_SIZE);

            TrampolinePtr     = trampolineAlloc;
            TrampolineSize    = trampolineLength;
            TrampolineJmpSize = jmpLength;
        }
Esempio n. 28
0
 public override void LogVerbose(string text)
 {
     if (_hookGenDebug)
     {
         _logger.LogDebug(text);
     }
 }
Esempio n. 29
0
        internal void UpdateCurrentCardTranslationMode()
        {
            var origMode = CurrentCardLoadTranslationMode;

            if (StudioAPI.InsideStudio)
            {
                CurrentCardLoadTranslationMode =
                    StudioTranslateCardNameOnLoad?.Value ?? CardLoadTranslationMode.Disabled;
                CurrentGameMode = GameMode.Studio;
            }

            else if (MakerAPI.InsideMaker)
            {
                CurrentCardLoadTranslationMode =
                    MakerTranslateCardNameOnLoad?.Value ?? CardLoadTranslationMode.Disabled;
                CurrentGameMode = GameMode.Maker;
            }
            else
            {
                CurrentGameMode = KoikatuAPI.GetCurrentGameMode();

                if (CurrentGameMode == GameMode.MainGame)
                {
                    CurrentCardLoadTranslationMode =
                        GameTranslateCardNameOnLoad?.Value ?? CardLoadTranslationMode.Disabled;
                }
                else
                {
                    CurrentCardLoadTranslationMode = CardLoadTranslationMode.Disabled;
                }
            }


            Logger.LogDebug($"UpdateCurrentCardTranslationMode: {origMode} => {CurrentCardLoadTranslationMode}");
        }
Esempio n. 30
0
        private void OnJoin(string rawSecret)
        {
            const string errorPrefix = "Failed to handle join event: ";

            _discordLog.LogDebug($"Received Discord join secret \"{rawSecret}\"");

            byte[] data;
            try
            {
                data = Convert.FromBase64String(rawSecret);
            }
            catch
            {
                _discordLog.LogError(errorPrefix + "could not parse base 64 secret.");
                return;
            }

            bool success = JoinSecret.TryParse(data, out var secret, out var version);

            if (!_version.CompatibleWith(version))
            {
                _discordLog.LogError(errorPrefix + $"version incompatibility detected (you: {_version}; host: {version})");
                return;
            }

            if (!success)
            {
                _discordLog.LogError(errorPrefix + "join secret was malformed.");
                return;
            }

            ConnectRemote(secret);
        }