Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ValheimPerformanceOverhaul v7.3.1612
BepInEx/plugins/ValheimPerformanceOverhaul.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using Steamworks; using Unity.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.UI; using VPO_WATER.Modules.ENGINE; using ValheimEngineOptimizer.Modules; using ValheimEngineOptimizer.Modules.AutoProfile; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("ValheimEngineOptimizer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+ceaa69de68ba9c83c65c9033c5613f6587077d41")] [assembly: AssemblyProduct("ValheimEngineOptimizer")] [assembly: AssemblyTitle("ValheimEngineOptimizer")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace VPO_WATER.Modules.ENGINE { public static class AsyncUploadOptimizer { public static void Apply(int bufferSizeMB, int timeSliceMs) { QualitySettings.asyncUploadBufferSize = Mathf.Clamp(bufferSizeMB, 16, 512); QualitySettings.asyncUploadTimeSlice = Mathf.Clamp(timeSliceMs, 2, 33); PropertyInfo property = typeof(QualitySettings).GetProperty("asyncUploadPersistentBuffer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(null, true, null); } } } public static class EngineCoreOptimizer { public static void Apply(int bufferMB, int timeSliceMs) { QualitySettings.asyncUploadBufferSize = Mathf.Clamp(bufferMB, 16, 512); QualitySettings.asyncUploadTimeSlice = Mathf.Clamp(timeSliceMs, 2, 33); PropertyInfo property = typeof(QualitySettings).GetProperty("asyncUploadPersistentBuffer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(null, true, null); } Type type = Type.GetType("UnityEngine.Physics, UnityEngine.PhysicsModule") ?? Type.GetType("UnityEngine.Physics, UnityEngine"); if (type != null) { SetStaticProperty(type, "sleepThreshold", 0.01f); SetStaticProperty(type, "defaultSolverIterations", 2); SetStaticProperty(type, "defaultSolverVelocityIterations", 1); } } private static void SetStaticProperty(Type type, string propName, object value) { try { PropertyInfo property = type.GetProperty(propName, BindingFlags.Static | BindingFlags.Public); if (property != null && property.CanWrite) { property.SetValue(null, value, null); } } catch { } } } public static class JobSystemPatcher { public static void Apply(int requestedWorkers) { Type type = Type.GetType("Unity.Jobs.LowLevel.Unsafe.JobsUtility, UnityEngine.CoreModule") ?? Type.GetType("Unity.Jobs.LowLevel.Unsafe.JobsUtility, UnityEngine"); if (type == null) { return; } PropertyInfo property = type.GetProperty("JobWorkerCount", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo property2 = type.GetProperty("JobWorkerMaximumCount", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { int num = requestedWorkers; if (num <= 0) { int num2 = ((property2 != null) ? ((int)(property2.GetValue(null, null) ?? ((object)SystemInfo.processorCount))) : SystemInfo.processorCount); num = Mathf.Max(1, num2); } property.SetValue(null, num, null); } } } public class SceneLODOptimizer : MonoBehaviour { private float _lastCheckTime; private const float Interval = 1.5f; private Camera _mainCam; public static float FarDistance = 110f; private void Update() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) if (Time.time - _lastCheckTime < 1.5f) { return; } _lastCheckTime = Time.time; if ((Object)(object)_mainCam == (Object)null || !((Behaviour)_mainCam).isActiveAndEnabled) { _mainCam = Camera.main; if ((Object)(object)_mainCam == (Object)null) { return; } } ((MonoBehaviour)this).StartCoroutine(ProcessLODsRoutine(((Component)_mainCam).transform.position)); } private IEnumerator ProcessLODsRoutine(Vector3 camPos) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) LODGroup[] lods = Object.FindObjectsByType<LODGroup>((FindObjectsSortMode)0); if (lods == null || lods.Length == 0) { yield break; } float farSqr = FarDistance * FarDistance; for (int i = 0; i < lods.Length; i++) { LODGroup val = lods[i]; if ((Object)(object)val == (Object)null) { continue; } Vector3 val2 = ((Component)val).transform.position - camPos; if (((Vector3)(ref val2)).sqrMagnitude > farSqr) { if (val.enabled) { val.ForceLOD(val.lodCount - 1); val.enabled = false; } } else if (!val.enabled) { val.enabled = true; val.ForceLOD(-1); } if (i % 400 == 0) { yield return null; } } } } } namespace ValheimEngineOptimizer { [BepInPlugin("com.Skarif.ValheimPerformanceOverhaul_WATER", "Valheim Performance Overhaul by Skarif", "8.0.0")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "com.Skarif.ValheimPerformanceOverhaul_WATER"; public const string ModName = "Valheim Performance Overhaul by Skarif"; public const string ModVersion = "8.0.0"; private Harmony _harmony; public static ConfigEntry<int> AsyncUploadBufferMB; public static ConfigEntry<int> AsyncUploadTimeSliceMs; public static ConfigEntry<ProcessPriorityMode> ProcessPriority; public static ConfigEntry<KeyCode> MenuHotkey; public static ConfigEntry<KeyCode> BatchHotkey; public static ConfigEntry<bool> SkipIntro; public static ConfigEntry<bool> GcControlEnabled; public static ConfigEntry<bool> JitWarmupEnabled; public static ConfigEntry<bool> AsyncSaveEnabled; public static ConfigEntry<bool> FrameBudgetGuardEnabled; public static ConfigEntry<float> FrameBudgetThresholdMs; public static ConfigEntry<float> FrameBudgetThrottledDelta; public static ConfigEntry<float> FrameBudgetNormalDelta; public static ConfigEntry<bool> PlayerUnscaledAnimations; public static ConfigEntry<bool> VegetationSpawnOptimized; public static ConfigEntry<bool> TerrainMeshCacheEnabled; public static ConfigEntry<int> TerrainMeshCacheMaxMB; public static ConfigEntry<float> DefaultLayerCullDist; public static ConfigEntry<float> SceneLODFarDist; public static ConfigEntry<bool> GPUInstancingEnabled; public static ConfigEntry<bool> StaticBatchingEnabled; public static ConfigEntry<bool> StaticBatchingAutoRun; public static ConfigEntry<float> StaticBatchingSettleCooldown; public static ConfigEntry<int> StaticBatchingMaxPerFrame; public static ConfigEntry<string> SavedBatchPoints; public static ConfigEntry<bool> LODGenerationEnabled; public static ConfigEntry<float> LOD1Quality; public static ConfigEntry<float> LOD2Quality; public static ConfigEntry<int> LODMinVertexCount; public static ConfigEntry<bool> VanillaCameraCacheEnabled; public static ConfigEntry<bool> MipmapStreamingEnabled; public static ConfigEntry<int> MipmapStreamingBudgetMB; public static ConfigEntry<int> MipmapStreamingMaxLevelReduction; public static ConfigEntry<bool> TextureOptimizationEnabled; public static ConfigEntry<float> TextureDownscaleMultiplier; public static ConfigEntry<bool> TorchOptimizerEnabled; public static ConfigEntry<float> TorchParticleLifetime; public static ConfigEntry<bool> SmokeOptimizationEnabled; public static ConfigEntry<bool> ObjectPoolingEnabled; public static ConfigEntry<bool> LightCullingEnabled; public static ConfigEntry<bool> AiOptimizationEnabled; public static ConfigEntry<float> PathCacheDistance; public static ConfigEntry<int> MaxPathRequestsPerFrame; public static ConfigEntry<bool> CharacterPhysicsLODEnabled; public static ConfigEntry<float> CharacterPhysicsLODNearDist; public static ConfigEntry<float> CharacterPhysicsLODFarDist; public static ConfigEntry<bool> TamedIdleEnabled; public static ConfigEntry<float> TamedIdleDistanceFromCombat; public static ConfigEntry<float> TamedIdleBaseDetectionRadius; public static ConfigEntry<bool> TamedIdleDisableColliders; public static ConfigEntry<float> TamedIdleWakeUpDistance; public static ConfigEntry<bool> ZDOSmartSortingEnabled; public static ConfigEntry<bool> MinimapOptimizationEnabled; public static ConfigEntry<bool> ChunkyEnabled; public static ConfigEntry<float> ChunkyGenDelay; public static ConfigEntry<int> ChunkyMinFPS; public static Plugin Instance { get; private set; } public static string T(string english, string russian, string ukrainian, string spanish) { return LocalizationHelper.T(english, russian, ukrainian, spanish); } private void Awake() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown Instance = this; _harmony = new Harmony("com.Skarif.ValheimPerformanceOverhaul_WATER"); LegacyConfigCleaner.CleanOldConfigsOnce(); AutoOptimizationManager.Initialize(((BaseUnityPlugin)this).Config); BindConfig(); RuntimeConfigDispatcher.Initialize(((BaseUnityPlugin)this).Config); ModConflictGuard.Initialize(((BaseUnityPlugin)this).Config, _harmony); ((BaseUnityPlugin)this).Logger.LogInfo((object)"[Valheim Performance Overhaul by Skarif] v8.0.0 initializing..."); EngineCoreOptimizer.Apply(AsyncUploadBufferMB.Value, AsyncUploadTimeSliceMs.Value); ProcessPriorityManager.ApplyPriority(ProcessPriority.Value); VPOSettingsMenu.ConfigInstance = ((BaseUnityPlugin)this).Config; VPOSettingsMenu.MenuHotkey = MenuHotkey.Value; VPOSettingsMenu.BatchHotkey = BatchHotkey.Value; SyncConfigToModules(); if (FrameBudgetGuardEnabled.Value) { GameObject val = new GameObject("_VPO_FrameBudgetGuard"); val.AddComponent<FrameBudgetGuard>(); Object.DontDestroyOnLoad((Object)val); } if (ChunkyEnabled.Value) { GameObject val2 = new GameObject("_VPO_ChunkyManager"); val2.AddComponent<ChunkyManager>(); Object.DontDestroyOnLoad((Object)val2); } if (TerrainMeshCacheEnabled.Value) { TerrainMeshCache.Initialize(); } if (LODGenerationEnabled.Value) { LODGenerator.SetupManager(); } if (AiOptimizationEnabled.Value) { AIOptimizerManager.Initialize(); } if (ObjectPoolingEnabled.Value) { ObjectPoolManager.Initialize(); } int num = 0; int num2 = 0; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { if (!ModConflictGuard.IsHarmonyPatchType(type)) { continue; } if (!ModConflictGuard.CanSafelyPatch(type, "com.Skarif.ValheimPerformanceOverhaul_WATER", out var conflictReason)) { if (ModConflictGuard.LogResolutions) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("[VPO Guard] Пропущен патч " + type.Name + ": " + conflictReason)); } num2++; continue; } try { PatchClassProcessor obj = _harmony.CreateClassProcessor(type); if (obj != null) { obj.Patch(); } num++; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("[VPO] Ошибка патча " + type.Name + ": " + ex.Message)); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("[{0}] Модули успешно применены: {1} (Изолировано: {2})", "Valheim Performance Overhaul by Skarif", num, num2)); } private void Update() { if (GcControlEnabled.Value) { GCPatches.TickGCMode(); } } private void BindConfig() { //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Expected O, but got Unknown //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d6: Expected O, but got Unknown //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Expected O, but got Unknown //IL_0571: Unknown result type (might be due to invalid IL or missing references) //IL_057b: Expected O, but got Unknown //IL_06bd: Unknown result type (might be due to invalid IL or missing references) //IL_06c7: Expected O, but got Unknown //IL_0713: Unknown result type (might be due to invalid IL or missing references) //IL_071d: Expected O, but got Unknown //IL_0803: Unknown result type (might be due to invalid IL or missing references) //IL_080d: Expected O, but got Unknown //IL_0865: Unknown result type (might be due to invalid IL or missing references) //IL_086f: Expected O, but got Unknown //IL_08c7: Unknown result type (might be due to invalid IL or missing references) //IL_08d1: Expected O, but got Unknown //IL_096e: Unknown result type (might be due to invalid IL or missing references) //IL_0978: Expected O, but got Unknown //IL_09d0: Unknown result type (might be due to invalid IL or missing references) //IL_09da: Expected O, but got Unknown //IL_0a8e: Unknown result type (might be due to invalid IL or missing references) //IL_0a98: Expected O, but got Unknown //IL_0ae4: Unknown result type (might be due to invalid IL or missing references) //IL_0aee: Expected O, but got Unknown //IL_0b8b: Unknown result type (might be due to invalid IL or missing references) //IL_0b95: Expected O, but got Unknown //IL_0c32: Unknown result type (might be due to invalid IL or missing references) //IL_0c3c: Expected O, but got Unknown //IL_0dde: Unknown result type (might be due to invalid IL or missing references) //IL_0de8: Expected O, but got Unknown //IL_0e35: Unknown result type (might be due to invalid IL or missing references) //IL_0e3f: Expected O, but got Unknown //IL_0edc: Unknown result type (might be due to invalid IL or missing references) //IL_0ee6: Expected O, but got Unknown //IL_0f3e: Unknown result type (might be due to invalid IL or missing references) //IL_0f48: Expected O, but got Unknown //IL_0fe5: Unknown result type (might be due to invalid IL or missing references) //IL_0fef: Expected O, but got Unknown //IL_1047: Unknown result type (might be due to invalid IL or missing references) //IL_1051: Expected O, but got Unknown //IL_10ee: Unknown result type (might be due to invalid IL or missing references) //IL_10f8: Expected O, but got Unknown //IL_123a: Unknown result type (might be due to invalid IL or missing references) //IL_1244: Expected O, but got Unknown //IL_1293: Unknown result type (might be due to invalid IL or missing references) //IL_129d: Expected O, but got Unknown string text = T("1. Engine Core", "1. Ядро движка", "1. Ядро рушія", "1. Núcleo del Motor"); AsyncUploadBufferMB = ((BaseUnityPlugin)this).Config.Bind<int>(text, T("Async Upload Buffer (MB)", "Размер буфера асинхронной загрузки (МБ)", "Розмір буфера асинхронного завантаження (МБ)", "Búfer de Carga Asíncrona (MB)"), 64, T("GPU I/O buffer size (MB).", "Размер буфера видеопамяти для текстур и мешей (МБ).", "Розмір буфера відеопам'яті для текстур і мешів (МБ).", "Tamaño del búfer de VRAM para GPU (MB).")); AsyncUploadTimeSliceMs = ((BaseUnityPlugin)this).Config.Bind<int>(text, T("Async Upload Time Slice (ms)", "Тайм-срез асинхронной загрузки (мс)", "Тайм-зріз асинхронного завантаження (мс)", "Franja de Tiempo de Carga Asíncrona (ms)"), 8, T("Max time slice per frame for uploading data to GPU (ms).", "Максимальное время на кадр для заливки ресурсов в видеопамять (мс).", "Максимальний час на кадр для завантаження ресурсів у відеопам'ять (мс).", "Tiempo máximo por fotograma para enviar datos a la GPU (ms).")); ProcessPriority = ((BaseUnityPlugin)this).Config.Bind<ProcessPriorityMode>(text, T("Process Priority", "Приоритет процесса Valheim.exe", "Пріоритет процесу Valheim.exe", "Prioridad del proceso Valheim.exe"), ProcessPriorityMode.High, T("Sets CPU scheduling priority for Valheim.exe.", "Устанавливает приоритет планировщика процессора для Valheim.exe.", "Встановлює пріоритет планувальника процесора для Valheim.exe.", "Establece la prioridad del proceso en la CPU para Valheim.exe.")); string text2 = T("2. UI & General", "2. Интерфейс и Общие", "2. Інтерфейс та Загальні", "2. Interfaz y General"); MenuHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>(text2, T("Settings Menu Hotkey", "Горячая клавиша меню настроек", "Гаряча клавіша меню налаштувань", "Tecla de Menú de Ajustes"), (KeyCode)287, T("Hotkey to open/close the optimizer settings menu.", "Горячая клавиша для открытия и закрытия меню настроек.", "Гаряча клавіша для відкриття та закриття меню налаштувань.", "Tecla rápida para abrir/cerrar el menú de ajustes.")); BatchHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>(text2, T("Batch Hotkey", "Горячая клавиша батчинга базы", "Гаряча клавіша батчингу бази", "Tecla de Agrupación de Base"), (KeyCode)288, T("Hotkey to toggle base batching anchor at current position.", "Горячая клавиша для сохранения точки авто-батчинга базы.", "Гаряча клавіша для збереження точки авто-батчингу бази.", "Tecla rápida para alternar el anclaje de agrupación de base.")); SkipIntro = ((BaseUnityPlugin)this).Config.Bind<bool>(text2, T("Skip Intro Logos", "Пропуск заставок", "Пропуск заставок", "Omitir Logotipos"), true, T("Skips game launch logos and intros.", "Пропускает вступительные логотипы при запуске игры.", "Пропускає початкові логотипи під час запуску гри.", "Omite los logotipos al iniciar el juego.")); string text3 = T("3. Memory & GC", "3. Память и Сборщик мусора", "3. Пам'ять та Збирач сміття", "3. Memoria y GC"); GcControlEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text3, T("GC Control Enabled", "Контроль сборщика мусора", "Контроль збирача сміття", "Control de GC"), true, T("Suspends GC during combat and movement.", "Приостанавливает вызовы сборщика мусора во время боя и активного бега.", "Призупиняє виклики збирача сміття під час бою та бігу.", "Suspende la recolección de basura durante el combate y movimiento.")); JitWarmupEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text3, T("JIT Warm-up Enabled", "Прогрев JIT компилятора", "Прогрів JIT компілятора", "Precalentamiento JIT"), true, T("Pre-compiles critical combat and GUI methods at startup.", "Компилирует критические методы боя и интерфейса заранее при старте.", "Компілює критичні методи бою та інтерфейсу заздалегідь під час старту.", "Precompila métodos críticos al iniciar para evitar micro-congelaciones.")); AsyncSaveEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text3, T("Async World Saving", "Асинхронные сохранения", "Асинхронні збереження", "Guardado Asíncrono de Mundo"), true, T("Eliminates main-thread freezes during world saves.", "Устраняет фризы при автосохранениях мира благодаря асинхронной записи.", "Усуває фризи під час автозбережень світу завдяки асинхронному запису.", "Elimina congelaciones durante el guardado del mundo en segundo plano.")); string text4 = T("4. Frame Budget & Physics", "4. Защита фреймрейта и Физика", "4. Захист фреймрейту та Фізика", "4. Presupuesto de Fotogramas"); FrameBudgetGuardEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text4, T("Frame Budget Guard Enabled", "Защита фреймрейта включена", "Захист фреймрейту увімкнено", "Protector de Fotogramas Habilitado"), true, T("Limits maximum physics delta time during frame spikes.", "Смягчает провисание физики при резких скачках времени кадра.", "Пом'якшує провисання фізики під час різких стрибків часу кадру.", "Suaviza tirones físicos durante picos de tiempo de fotograma.")); FrameBudgetThresholdMs = ((BaseUnityPlugin)this).Config.Bind<float>(text4, T("Freeze Threshold (ms)", "Порог фриза (мс)", "Поріг фризу (мс)", "Umbral de Congelación (ms)"), 28f, new ConfigDescription(T("Frame time threshold to activate budget protection.", "Порог времени кадра для включения защиты.", "Поріг часу кадру для увімкнення захисту.", "Umbral de tiempo para activar protección."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(16f, 100f), Array.Empty<object>())); FrameBudgetThrottledDelta = ((BaseUnityPlugin)this).Config.Bind<float>(text4, T("Throttled MaxDeltaTime", "Защищенный лимит кадра", "Захищений ліміт кадру", "Límite de Fotograma Protegido"), 0.045f, new ConfigDescription(T("Max physics delta during a spike.", "Максимальный шаг физики во время фриза.", "Максимальний крок фізики під час фризу.", "Paso máximo de física durante congelación."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.02f, 0.1f), Array.Empty<object>())); FrameBudgetNormalDelta = ((BaseUnityPlugin)this).Config.Bind<float>(text4, T("Normal MaxDeltaTime", "Обычный лимит кадра", "Звичайний ліміт кадру", "Límite de Fotograma Normal"), 0.07f, new ConfigDescription(T("Max physics delta during normal frames.", "Максимальный шаг физики в обычном режиме.", "Максимальний крок фізики у звичайному режимі.", "Paso máximo de física en modo normal."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.03f, 0.2f), Array.Empty<object>())); PlayerUnscaledAnimations = ((BaseUnityPlugin)this).Config.Bind<bool>(text4, T("Player Realtime Animations", "Анимации игрока в реальном времени", "Анімації гравця в реальному часі", "Animaciones del jugador en tiempo real"), true, T("Forces player animator to use unscaled real-time.", "Переводит анимации игрока на реальное время.", "Переводить анімації гравця на реальний час.", "Evita la ralentización de animaciones del jugador en caídas de FPS.")); string text5 = T("5. Vegetation & Terrain", "5. Растительность и Ландшафт", "5. Рослинність та Ландшафт", "5. Vegetación y Terreno"); VegetationSpawnOptimized = ((BaseUnityPlugin)this).Config.Bind<bool>(text5, T("Vegetation Spawn Slicing", "Тайм-слайсинг спавна растительности", "Тайм-слайсинг спавну рослинності", "Distribución de Generación de Flora"), true, T("Distributes heavy vegetation generation across multiple frames.", "Распределяет спавн деревьев и кустов по кадрам без зависания игры.", "Розподіляє спавн дерев та кущів по кадрах без зависання гри.", "Distribuye la generación de árboles y plantas en varios fotogramas.")); TerrainMeshCacheEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text5, T("Terrain Mesh Cache", "Кэш мешей ландшафта", "Кеш мешів ландшафту", "Caché de Mallas de Terreno"), true, T("Caches heightmap geometry in RAM.", "Кэширует меши карт высот в оперативной памяти.", "Кешує меші карт висот в оперативній пам'яті.", "Almacena en caché mallas de terreno.")); TerrainMeshCacheMaxMB = ((BaseUnityPlugin)this).Config.Bind<int>(text5, T("Terrain Cache Max Memory (MB)", "Макс. память кэша ландшафта (МБ)", "Макс. пам'ять кешу ландшафту (МБ)", "Memoria Máxima de Caché de Terreno (MB)"), 32, new ConfigDescription(T("Max RAM budget for terrain mesh cache.", "Лимит памяти RAM под кэш мешей карт высот.", "Ліміт пам'яті RAM під кеш мешів карт висот.", "Límite de RAM para el caché de terreno."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 256), Array.Empty<object>())); string text6 = T("6. Graphics & LOD", "6. Графика, Меши и LOD", "6. Графіка, Меші та LOD", "6. Gráficos y LOD"); GPUInstancingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text6, T("GPU Instancing Enabled", "GPU Instancing включен", "GPU Instancing увімкнено", "GPU Instancing Habilitado"), true, T("Enables native GPU Instancing on static props and decor.", "Включает нативный GPU Instancing на объектах и декоре мира.", "Вмикає нативний GPU Instancing на об'єктах та декорі світу.", "Habilita GPU Instancing nativo en objetos del mundo.")); StaticBatchingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text6, T("Static Batching Enabled", "Статическое объединение (Batching)", "Статичне об'єднання (Batching)", "Agrupamiento Estático"), true, T("Combines static geometry per sector.", "Объединяет статическую геометрию построек по секторам.", "Об'єднує статичну геометрію споруд по секторах.", "Combina geometría estática por sectores.")); StaticBatchingAutoRun = ((BaseUnityPlugin)this).Config.Bind<bool>(text6, T("Static Batching Auto-Run", "Автоматический запуск батчинга", "Автоматичний запуск батчингу", "Ejecución Automática de Agrupamiento"), false, T("Automatically batches sectors in background.", "Автоматически сжимает геометрию в фоне.", "Автоматично стискає геометрію у фоні.", "Agrupa sectores automáticamente en segundo plano.")); StaticBatchingSettleCooldown = ((BaseUnityPlugin)this).Config.Bind<float>(text6, T("Batch Settle Cooldown (s)", "Задержка стабилизации (сек)", "Затримка стабілізації (сек)", "Espera de Estabilización (s)"), 2f, new ConfigDescription(T("Cooldown after object placement before combining.", "Время ожидания после постройки перед объединением.", "Час очікування після будівництва перед об'єднанням.", "Espera tras construir antes de combinar."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>())); StaticBatchingMaxPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>(text6, T("Max Batches Per Frame", "Макс. секторов за кадр", "Макс. секторів за кадр", "Máximo de Sectores por Fotograma"), 1, new ConfigDescription(T("Max sectors combined per frame.", "Лимит секторов для объединения за один кадр.", "Ліміт секторів для об'єднання за один кадр.", "Límite de sectores combinados por fotograma."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>())); SavedBatchPoints = ((BaseUnityPlugin)this).Config.Bind<string>(text6, T("Saved Base Anchors", "Сохраненные точки баз", "Збережені точки баз", "Anclajes de Base Guardados"), "", T("Stored coordinates for base auto-batching.", "Сохраненные координаты баз для авто-батчинга.", "Збережені координати баз для авто-батчингу.", "Coordenadas guardadas para agrupación automática.")); LODGenerationEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text6, T("Runtime LOD Generation", "Генерация LOD моделей", "Генерація LOD моделей", "Generación de LODs"), true, T("Generates lightweight LOD levels in background.", "Генерирует упрощенные уровни детализации (LOD) для тяжелых объектов.", "Генерує спрощені рівні деталізації (LOD) для важких об'єктів.", "Genera niveles LOD simplificados en segundo plano.")); LOD1Quality = ((BaseUnityPlugin)this).Config.Bind<float>(text6, T("LOD1 Quality", "Качество LOD1", "Якість LOD1", "Calidad de LOD1"), 0.5f, new ConfigDescription(T("Mesh reduction ratio for LOD1.", "Коэффициент качества полигонов для LOD1.", "Коефіцієнт якості полигонов для LOD1.", "Ratio de calidad para LOD1."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 0.9f), Array.Empty<object>())); LOD2Quality = ((BaseUnityPlugin)this).Config.Bind<float>(text6, T("LOD2 Quality", "Качество LOD2", "Якість LOD2", "Calidad de LOD2"), 0.15f, new ConfigDescription(T("Mesh reduction ratio for LOD2.", "Коэффициент качества полигонов для LOD2.", "Коефіцієнт якості полигонов для LOD2.", "Ratio de calidad para LOD2."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 0.5f), Array.Empty<object>())); LODMinVertexCount = ((BaseUnityPlugin)this).Config.Bind<int>(text6, T("LOD Min Vertex Count", "Мин. вершин для генерации LOD", "Мін. вершин для генерації LOD", "Vértices Mínimos para LOD"), 300, new ConfigDescription(T("Minimum vertex count to trigger LOD creation.", "Минимальное количество вершин для создания LOD.", "Мінімальна кількість вершин для створення LOD.", "Mínimo de vértices para generar LOD."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(150, 5000), Array.Empty<object>())); VanillaCameraCacheEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text6, T("Vanilla Camera Caching", "Кэш камеры и плоскостей", "Кеш камери та площин", "Caché de Cámara"), true, T("Caches Camera.main and frustum planes once per frame.", "Кэширует камеру и плоскости усечения раз за кадр.", "Кешує камеру та площини раз за кадр.", "Almacena en caché Camera.main y planos frustum por fotograma.")); DefaultLayerCullDist = ((BaseUnityPlugin)this).Config.Bind<float>(text6, T("Default Layer Cull Distance (m)", "Дальность отрисовки слоя Default (м)", "Дальність промальовування шару Default (м)", "Distancia de Renderizado de Capa Default (m)"), 180f, new ConfigDescription(T("Max render distance for default environment objects and rocks.", "Максимальная дистанция прорисовки базовых объектов и скал.", "Максимальна дистанція промальовування базових об'єктів та скель.", "Distancia máxima de dibujado de objetos base y rocas."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(50f, 2000f), Array.Empty<object>())); SceneLODFarDist = ((BaseUnityPlugin)this).Config.Bind<float>(text6, T("Scene LOD Far Distance (m)", "Дистанция отключения LOD (м)", "Дистанція вимкнення LOD (м)", "Distancia de Desactivación de LOD (m)"), 110f, new ConfigDescription(T("Distance after which distant LODGroups are forcefully disabled.", "Дистанция, дальше которой LODGroup принудительно выключаются для экономии кадров.", "Дистанція, далі якої LODGroup примусово вимикаються для економії кадрів.", "Distancia a partir de la cual los LODGroups se desactivan."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(50f, 1000f), Array.Empty<object>())); string text7 = T("7. Textures & Particles", "7. Текстуры и Частицы", "7. Текстури та Частинки", "7. Texturas y Partículas"); MipmapStreamingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text7, T("Texture Mipmap Streaming", "Mipmap Streaming текстур", "Mipmap Streaming текстур", "Mipmap Streaming de Texturas"), true, T("Dynamically streams texture mipmaps into VRAM based on distance.", "Динамически загружает мипмапы текстур в видеопамять по дистанции.", "Динамічно завантажує міпмапи текстур у відеопам'ять за відстанню.", "Carga dinámicamente mipmaps de texturas según la distancia a la cámara.")); MipmapStreamingBudgetMB = ((BaseUnityPlugin)this).Config.Bind<int>(text7, T("Mipmap VRAM Budget (MB)", "Лимит видеопамяти под текстуры (МБ)", "Ліміт відеопам'яті під текстури (МБ)", "Presupuesto de VRAM para Texturas (MB)"), 512, new ConfigDescription(T("Dedicated VRAM budget for textures.", "Выделенный лимит видеопамяти под текстуры.", "Виділений ліміт відеопам'яті під текстури.", "Presupuesto de VRAM para streaming."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 4096), Array.Empty<object>())); MipmapStreamingMaxLevelReduction = ((BaseUnityPlugin)this).Config.Bind<int>(text7, T("Mipmap Max Reduction", "Макс. уровень сжатия мипов", "Макс. рівень стиснення міпів", "Nivel Máximo de Reducción"), 2, new ConfigDescription(T("Maximum mip levels to drop under memory pressure.", "Максимальное число мип-уровней для сжатия при нехватке памяти.", "Максимальна кількість міп-рівнів для стиснення.", "Nivel máximo de reducción de mipmaps."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 4), Array.Empty<object>())); TextureOptimizationEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text7, T("Static Texture Downscale (Fallback)", "Статичное сжатие текстур (Fallback)", "Статичне стиснення текстур (Fallback)", "Reducción Estática de Texturas"), false, T("Downscales all textures globally if Mipmap Streaming is disabled.", "Уменьшает разрешение всех текстур глобально, если Mipmap Streaming выключен.", "Зменшує роздільну здатність текстур глобально, якщо стрімінг вимкнено.", "Reduce la resolución de texturas globalmente si Mipmap Streaming está deshabilitado.")); TextureDownscaleMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>(text7, T("Downscale Multiplier", "Множитель масштаба текстур", "Множник масштабу текстур", "Multiplicador de Reducción"), 0.5f, new ConfigDescription(T("Resolution multiplier for static downscale.", "Множитель разрешения для статического режима.", "Множник роздільної здатності для статичного режиму.", "Multiplicador de resolución."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>())); TorchOptimizerEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text7, T("Torch Particle Optimizer", "Оптимизация огня факелов", "Оптимізація вогню смолоскипів", "Optimización de Antorchas"), true, T("Reduces particle lifetimes on torches and braziers.", "Укорачивает время жизни частиц факелов для снижения нагрузки на видеокарту.", "Скорочує час життя частинок смолоскипів для зниження навантаження на відеокарту.", "Reduce la duración de partículas en antorchas para ahorrar GPU.")); TorchParticleLifetime = ((BaseUnityPlugin)this).Config.Bind<float>(text7, T("Torch Particle Lifetime (s)", "Время жизни частиц огня (сек)", "Час життя частинок вогню (сек)", "Duración de Partículas de Antorcha (s)"), 0.8f, new ConfigDescription(T("Lifetime of flame particles.", "Длительность жизни частиц огня факелов.", "Тривалість життя частинок вогню смолоскипів.", "Tiempo de vida de partículas de antorchas."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 2f), Array.Empty<object>())); SmokeOptimizationEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text7, T("Smoke Aerodynamics Optimization", "Оптимизация физики дыма", "Оптимізація фізики диму", "Optimización de Humo"), true, T("Replaces heavy smoke calculations with lightweight aerodynamics.", "Упрощает расчет аэродинамики дыма, убирая просадки FPS у костров.", "Спрощує розрахунок аеродинаміки диму, усуваючи просідання FPS біля багать.", "Optimiza los cálculos de aerodinámica del humo.")); ObjectPoolingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text7, T("Object Pooling (VFX / Arrows)", "Пул объектов (Стрелы / VFX)", "Пул об'єктів (Стріли / VFX)", "Pooling de Objetos"), true, T("Recycles hits, sparks, and arrows using fast in-memory pooling.", "Повторно использует частицы ударов, искр и стрел через пул объектов.", "Повторно використовує частинки ударів, іскор та стріл через пул об'єктів.", "Reutiliza proyectiles y efectos VFX mediante un pool en memoria.")); string text8 = T("8. Lights & Occlusion", "8. Источники света", "8. Джерела світла", "8. Luces y Oclusión"); LightCullingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text8, T("Light Culling (CullingGroup)", "Куллинг источников света", "Кулінг джерел світла", "Culling de Luces"), true, T("Dynamically culls off-screen and distant lights via Unity CullingGroup.", "Отключает источники света вне экрана и на расстоянии через Unity CullingGroup.", "Вимкне джерела світла поза екраном та на відстані через Unity CullingGroup.", "Desactiva luces fuera de pantalla y lejanas mediante CullingGroup.")); string text9 = T("9. AI & Creatures", "9. Искусственный интеллект и Мобы", "9. Штучний інтелект та Моби", "9. IA y Criaturas"); AiOptimizationEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text9, T("AI Throttling Enabled", "Замедление далекого ИИ", "Уповільнення далекого ШІ", "Ralentización de IA Lejana"), true, T("Throttles update frequencies of distant non-combat AI.", "Снижает частоту обновления логики далеких мобов вне боя для разгрузки процессора.", "Знижує частоту оновлення логіки далеких мобів поза боєм для розвантаження процесора.", "Reduce la frecuencia de actualización de la IA distante fuera de combate.")); PathCacheDistance = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Path Cache Distance", "Дистанция кэша путей ИИ", "Дистанція кешу шляхів ШІ", "Distancia de Caché de Rutas"), 2f, new ConfigDescription(T("Distance threshold to reuse calculated AI paths.", "Порог дистанции для повторного использования рассчитанного пути ИИ.", "Поріг дистанції для повторного використання розрахованого шляху ШІ.", "Umbral de distancia para reutilizar rutas de IA calculadas."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 8f), Array.Empty<object>())); MaxPathRequestsPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>(text9, T("Max Pathfinding Per Frame", "Макс. поисков путей за кадр", "Макс. пошуків шляхів за кадр", "Máximo de Búsquedas de Ruta"), 5, new ConfigDescription(T("Limits concurrent pathfinding searches per frame.", "Лимит одновременных расчетов поиска путей за кадр.", "Ліміт одночасних розрахунків пошуку шляхів за кадр.", "Límite de cálculos de búsqueda de ruta por fotograma."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 20), Array.Empty<object>())); CharacterPhysicsLODEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text9, T("Character Physics LOD", "LOD физики персонажей", "LOD фізики персонажів", "LOD de Física de Personajes"), true, T("Throttles FixedUpdate simulation ticks on distant creatures.", "Снижает частоту физических тиков для далеких существ.", "Знижує частоту фізичних тіків для далеких істот.", "Reduce los ticks de física en criaturas lejanas.")); CharacterPhysicsLODNearDist = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Physics LOD Near Distance", "Дистанция полной физики (LOD)", "Дистанція повної фізики (LOD)", "Distancia Cercana de Física LOD"), 20f, new ConfigDescription(T("Distance under which creatures receive 100% full physics updates.", "Дистанция, ближе которой существа симулируются с полной частотой.", "Дистанція, ближче якої істоти симулюються з повною частотою.", "Distancia en la que las criaturas reciben el 100% de actualizaciones físicas."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 40f), Array.Empty<object>())); CharacterPhysicsLODFarDist = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Physics LOD Far Distance", "Дистанция дальней физики (LOD)", "Дистанція дальньої фізики (LOD)", "Distancia Lejana de Física LOD"), 50f, new ConfigDescription(T("Distance beyond which creatures step physics at 12.5 Hz.", "Дистанция, дальше которой физика мобов рассчитывается в 4 раза реже.", "Дистанція, далі якої фізика мобів розраховується в 4 рази рідше.", "Distancia a partir de la cual la física se calcula a 12.5 Hz."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(30f, 100f), Array.Empty<object>())); TamedIdleEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text9, T("Tamed Animal Idle Sleep", "Сон прирученных питомцев", "Сон приручених тварин", "Modo Inactivo de Mascotas"), true, T("Puts tamed base animals into idle sleep mode.", "Переводит прирученных животных на базе в режим энергосбережения.", "Переводить приручених тварин на базі в режим енергозбереження.", "Pone a las mascotas en reposo, desactivando animaciones y física.")); TamedIdleDistanceFromCombat = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Tamed Idle Distance From Combat", "Дистанция сна от боя", "Дистанція сну від бою", "Distancia de Combate para Reposo"), 5f, new ConfigDescription(T("Min distance from combat to allow idle sleep.", "Минимальное расстояние от боя для засыпания питомца.", "Мінімальна відстань від бою для засинання.", "Distancia mínima del combate para suspender."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 30f), Array.Empty<object>())); TamedIdleBaseDetectionRadius = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Tamed Base Radius", "Радиус базы для засыпания", "Радіус бази для засинання", "Radio de Base para Reposo"), 30f, new ConfigDescription(T("Radius of base pieces detection.", "Радиус обнаружения построек базы для активации сна.", "Радіус виявлення споруд бази для активації сну.", "Radio de detección de base."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(15f, 60f), Array.Empty<object>())); TamedIdleDisableColliders = ((BaseUnityPlugin)this).Config.Bind<bool>(text9, T("Tamed Disable Colliders", "Отключать коллизии спящих питомцев", "Вимикати колізії сплячих тварин", "Desactivar Colisiones de Mascotas"), false, T("Disables colliders for sleeping base animals.", "Отключает физические коллизии спящих питомцев.", "Вимикає фізичні колізії сплячих тварин.", "Desactiva colisiones de mascotas suspendidas.")); TamedIdleWakeUpDistance = ((BaseUnityPlugin)this).Config.Bind<float>(text9, T("Tamed Wake Up Distance", "Дистанция пробуждения питомцев", "Дистанція пробудження тварин", "Distancia de Despertar de Mascotas"), 7f, new ConfigDescription(T("Distance at which player wakes up tamed mobs.", "Дистанция, на которой приближение игрока пробуждает питомцев.", "Дистанція, на якій наближення гравця пробуджує тварин.", "Distancia a la que el jugador despierta a la criatura."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 20f), Array.Empty<object>())); string text10 = T("10. Network & World", "10. Сеть и Мир", "10. Мережа та Світ", "10. Red y Mundo"); ZDOSmartSortingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text10, T("Smart ZDO Sorting", "Умная сортировка сетевых пакетов (ZDO)", "Розумне сортування мережевих пакетів (ZDO)", "Ordenación Inteligente de ZDO"), true, T("Prioritizes players, ships, and portals over far-away objects.", "Приоритезирует отправку данных игроков и кораблей перед далекими объектами.", "Пріоритезує відправку даних гравців та кораблів перед далекими об'єктами.", "Prioriza el envío de paquetes de jugadores y barcos.")); MinimapOptimizationEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text10, T("Minimap Pin Optimizer", "Оптимизация меток миникарты", "Оптимізація міток мінікарти", "Optimización de Marcadores de Mapa"), true, T("Reduces dynamic map pins update frequency.", "Снижает частоту обновления динамических меток миникарты.", "Знижує частоту оновлення динамічних міток мінікарти.", "Reduce la frecuencia de actualización de marcadores del mapa.")); ChunkyEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text10, T("Chunky Pregenerator Enabled", "Предгенерация зон (Chunky)", "Передгенерація зон (Chunky)", "Pregenerador Chunky Habilitado"), true, T("Enables background zone pregeneration around the player.", "Включает фоновую предгенерацию зон вокруг игрока.", "Вмикає фонову передгенерацію зон навколо гравця.", "Habilita la pregeneración de zonas en segundo plano.")); ChunkyGenDelay = ((BaseUnityPlugin)this).Config.Bind<float>(text10, T("Chunky Gen Delay (s)", "Задержка генерации зоны (сек)", "Затримка генерації зони (сек)", "Espera de Generación Chunky (s)"), 0.4f, new ConfigDescription(T("Time to wait between generating zones.", "Время ожидания между генерацией зон.", "Час очікування між генерацією зон.", "Segundos a esperar entre zonas."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>())); ChunkyMinFPS = ((BaseUnityPlugin)this).Config.Bind<int>(text10, T("Chunky Min FPS", "Минимальный FPS для генерации", "Мінімальний FPS для генерації", "FPS Mínimos para Chunky"), 35, new ConfigDescription(T("Pauses pregeneration if FPS falls below this threshold.", "Приостанавливает предгенерацию, если FPS падает ниже порога.", "Призупиняє передгенерацію, якщо FPS падає нижче порогу.", "Pausa la pregeneración si caen los FPS por debajo del umbral."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(15, 60), Array.Empty<object>())); } private void SyncConfigToModules() { SceneLoaderPatch.SkipIntro = SkipIntro.Value; GCPatches.Enabled = GcControlEnabled.Value; JitPatches.Enabled = JitWarmupEnabled.Value; AsyncSavePatches.Enabled = AsyncSaveEnabled.Value; FrameBudgetGuard.Enabled = FrameBudgetGuardEnabled.Value; FrameBudgetGuard.ThresholdMs = FrameBudgetThresholdMs.Value; FrameBudgetGuard.ThrottledDelta = FrameBudgetThrottledDelta.Value; FrameBudgetGuard.NormalDelta = FrameBudgetNormalDelta.Value; FrameBudgetGuard.PlayerUnscaledAnimations = PlayerUnscaledAnimations.Value; ZoneSystemPlaceVegetationPatch.Enabled = VegetationSpawnOptimized.Value; TerrainMeshCache.Enabled = TerrainMeshCacheEnabled.Value; TerrainMeshCache.MaxMemoryMB = TerrainMeshCacheMaxMB.Value; GPUInstancingManager.Enabled = GPUInstancingEnabled.Value; OptimizationTierResolver.Initialize(); StaticBatchingManager.Enabled = StaticBatchingEnabled.Value; StaticBatchingManager.AutoRun = StaticBatchingAutoRun.Value; StaticBatchingManager.SettleCooldown = StaticBatchingSettleCooldown.Value; StaticBatchingManager.MaxPerFrame = StaticBatchingMaxPerFrame.Value; StaticBatchingManager.SavedBatchPoints = SavedBatchPoints.Value; LODGenerator.Enabled = LODGenerationEnabled.Value; LODGenerator.LOD1Quality = LOD1Quality.Value; LODGenerator.LOD2Quality = LOD2Quality.Value; LODGenerator.MinVertexCount = LODMinVertexCount.Value; RenderOptimizer.DefaultLayerCullDistance = DefaultLayerCullDist.Value; SceneLODOptimizer.FarDistance = SceneLODFarDist.Value; RenderOptimizer.ApplySettings(); VanillaCameraCachePatches.Enabled = VanillaCameraCacheEnabled.Value; TextureOptimizer.MipmapStreamingEnabled = MipmapStreamingEnabled.Value; TextureOptimizer.MipmapStreamingBudgetMB = MipmapStreamingBudgetMB.Value; TextureOptimizer.MipmapStreamingMaxLevelReduction = MipmapStreamingMaxLevelReduction.Value; TextureOptimizer.TextureOptimizationEnabled = TextureOptimizationEnabled.Value; TextureOptimizer.TextureDownscaleMultiplier = TextureDownscaleMultiplier.Value; TextureOptimizer.ApplyTextureQuality(); TorchOptimizer.Enabled = TorchOptimizerEnabled.Value; TorchOptimizer.TorchParticleLifetime = TorchParticleLifetime.Value; SmokePatch.Enabled = SmokeOptimizationEnabled.Value; ObjectPoolManager.Enabled = ObjectPoolingEnabled.Value; VPOLightCullingManager.Enabled = LightCullingEnabled.Value; AIPatches.Enabled = AiOptimizationEnabled.Value; PathfindingScheduler.MaxRequestsPerFrame = MaxPathRequestsPerFrame.Value; CharacterPhysicsLODPatches.Enabled = CharacterPhysicsLODEnabled.Value; CharacterPhysicsLODPatches.NearDistance = CharacterPhysicsLODNearDist.Value; CharacterPhysicsLODPatches.FarDistance = CharacterPhysicsLODFarDist.Value; TamedIdleOptimizer.Enabled = TamedIdleEnabled.Value; TamedIdleOptimizer.DistanceFromCombat = TamedIdleDistanceFromCombat.Value; TamedIdleOptimizer.BaseDetectionRadius = TamedIdleBaseDetectionRadius.Value; TamedIdleOptimizer.DisableColliders = TamedIdleDisableColliders.Value; TamedIdleOptimizer.WakeUpDistance = TamedIdleWakeUpDistance.Value; ZDOOptimizer.Enabled = ZDOSmartSortingEnabled.Value; MinimapOptimizer.Enabled = MinimapOptimizationEnabled.Value; ChunkyManager.Enabled = ChunkyEnabled.Value; ChunkyManager.GenDelay = ChunkyGenDelay.Value; ChunkyManager.MinFPS = ChunkyMinFPS.Value; } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } } public static class LegacyConfigCleaner { private const string PREFS_CLEANED_KEY = "VPO_Legacy_Configs_Purged_v1"; public static void CleanOldConfigsOnce() { if (PlayerPrefs.GetInt("VPO_Legacy_Configs_Purged_v1", 0) == 1) { return; } try { string configPath = Paths.ConfigPath; if (!Directory.Exists(configPath)) { return; } string b = "com.Skarif.ValheimPerformanceOverhaul_WATER.cfg"; string[] files = Directory.GetFiles(configPath, "com.Skarif.ValheimPerformance*.cfg", SearchOption.TopDirectoryOnly); int num = 0; string[] array = files; foreach (string path in array) { string fileName = Path.GetFileName(path); if (!string.Equals(fileName, b, StringComparison.OrdinalIgnoreCase)) { try { File.Delete(path); num++; Debug.Log((object)("[VPO Cleaner] Удален устаревший файл конфигурации: " + fileName)); } catch (Exception ex) { Debug.LogWarning((object)("[VPO Cleaner] Не удалось удалить " + fileName + ": " + ex.Message)); } } } if (num > 0) { Debug.Log((object)$"[VPO Cleaner] Очистка завершена. Удалено старых конфигов: {num}"); } PlayerPrefs.SetInt("VPO_Legacy_Configs_Purged_v1", 1); PlayerPrefs.Save(); } catch (Exception ex2) { Debug.LogWarning((object)("[VPO Cleaner] Ошибка при проверке старых конфигов: " + ex2.Message)); } } } } namespace ValheimEngineOptimizer.Modules { public enum ConflictSensitivity { Conservative, Aggressive, KnownOnly } public static class ModConflictGuard { private struct KnownModRule { public string ModGuidPart; public string ModFriendlyName; public Action DisableAction; public string ModuleName; public string Reason; } public static bool Enabled = true; public static ConflictSensitivity Sensitivity = ConflictSensitivity.Conservative; public static bool LogResolutions = true; private static ConfigFile _configFile; private static Harmony _guardHarmonyInstance; private static readonly HashSet<Type> _disabledPatchTypes = new HashSet<Type>(); private static readonly HashSet<Type> _disabledTargetTypes = new HashSet<Type>(); private static readonly HashSet<string> _suppressedConfigKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static readonly List<string> _conflictReport = new List<string>(); private static readonly HashSet<string> _processedRules = new HashSet<string>(); private static readonly Dictionary<Type, Action> _moduleDisableActions = new Dictionary<Type, Action>(); private static readonly List<Type> _registeredPatchClasses = new List<Type>(); private static readonly Assembly _currentAssembly = typeof(ModConflictGuard).Assembly; private static readonly string[] IgnoredFrameworkIdentifiers = new string[15] { "jotunn", "com.jotunn.jotunn", "bepinex", "org.bepinex", "0harmony", "harmony", "hookgen", "monomod", "serversync", "piecemanager", "itemmanager", "locationmanager", "creaturemanager", "skillmanager", "localizationcache" }; private static readonly List<KnownModRule> KnownModRules = new List<KnownModRule> { new KnownModRule { ModGuidPart = "expand_world", ModFriendlyName = "Expand World", ModuleName = "Vegetation & Terrain", DisableAction = delegate { DisableModuleInMemory(typeof(ZoneSystemPlaceVegetationPatch), "Vegetation Spawn Slicing"); DisableModuleInMemory(typeof(TerrainMeshCacheZNetScenePatch), "Terrain Mesh Cache"); DisableModuleInMemory(typeof(VegetationOptimizerPatches), "Vegetation Spawn Slicing"); ZoneSystemPlaceVegetationPatch.Enabled = false; TerrainMeshCache.Enabled = false; TerrainMeshCache.Clear(); }, Reason = "Мод кардинально меняет спавн растительности и генерацию высот." }, new KnownModRule { ModGuidPart = "creaturelevelcontrol", ModFriendlyName = "Creature Level and Loot Control (CLLC)", ModuleName = "AI & Pathfinding", DisableAction = delegate { DisableModuleInMemory(typeof(AIPatches), "AI Throttling Enabled"); DisableModuleInMemory(typeof(PathfindingScheduler), "AI Throttling Enabled"); DisableModuleInMemory(typeof(CharacterPhysicsLODPatches), "Character Physics LOD"); DisableModuleInMemory(typeof(TamedIdlePatches), "Tamed Animal Idle Sleep"); AIPatches.Enabled = false; CharacterPhysicsLODPatches.Enabled = false; }, Reason = "CLLC полностью переписывает спавн, атаки и логику ИИ." }, new KnownModRule { ModGuidPart = "valheim_raft", ModFriendlyName = "ValheimRAFT", ModuleName = "StaticBatching & PhysicsLOD", DisableAction = delegate { DisableModuleInMemory(typeof(StaticBatchingPatches), "Static Batching Enabled"); DisableModuleInMemory(typeof(CharacterPhysicsLODPatches), "Character Physics LOD"); StaticBatchingManager.Enabled = false; StaticBatchingManager.Instance?.ClearAll(); }, Reason = "Подвижные базы на воде несовместимы со статическим батчингом." }, new KnownModRule { ModGuidPart = "plan_build", ModFriendlyName = "PlanBuild", ModuleName = "StructureOptimizer & StaticBatching", DisableAction = delegate { DisableModuleInMemory(typeof(StructureOptimizerPatches), "Static Batching Enabled"); DisableModuleInMemory(typeof(StaticBatchingPatches), "Static Batching Enabled"); StaticBatchingManager.Enabled = false; StaticBatchingManager.Instance?.ClearAll(); }, Reason = "Чертежи и призрачные структуры несовместимы с объединением мешей." } }; public static void Initialize(ConfigFile config, Harmony harmonyInstance) { _configFile = config; _guardHarmonyInstance = harmonyInstance; string text = "0. Compatibility Guard"; ConfigEntry<bool> val = config.Bind<bool>(text, "Enable Smart Conflict Guard", true, "Автоматически анализирует хуки сторонних модов и отключает конфликтующие подсистемы VPO во избежание сбоев."); ConfigEntry<ConflictSensitivity> val2 = config.Bind<ConflictSensitivity>(text, "Conflict Detection Sensitivity", ConflictSensitivity.Conservative, "Чувствительность детектора конфликтов:\n- Conservative: отключает модули при сторонних Prefix/Transpiler.\n- Aggressive: отключает при любом стороннем хуке.\n- KnownOnly: только по базе модов."); ConfigEntry<bool> obj = config.Bind<bool>(text, "Log Conflict Resolutions", true, "Выводить в консоль подробные отчеты об обнаруженных и предотвращенных конфликтах."); Enabled = val.Value; Sensitivity = val2.Value; LogResolutions = obj.Value; RegisterModuleDisableMappings(); if (Enabled) { RunKnownPluginScan(); if (Sensitivity != ConflictSensitivity.KnownOnly) { ScanActiveHarmonyPatches(); } } } private static bool IsOurOwnPatch(Patch patch) { if (patch == null) { return false; } if (patch.PatchMethod != null && patch.PatchMethod.DeclaringType != null && patch.PatchMethod.DeclaringType.Assembly == _currentAssembly) { return true; } if (string.Equals(patch.owner, "com.Skarif.ValheimPerformanceOverhaul_WATER", StringComparison.OrdinalIgnoreCase)) { return true; } if (!string.IsNullOrEmpty(patch.owner)) { string text = patch.owner.ToLowerInvariant(); if (text.Contains("valheimengineoptimizer") || text.Contains("valheimperformanceoverhaul") || text.Contains("vpo_water") || text.Contains("skarif")) { return true; } } return false; } public static bool IsIgnoredFramework(Patch patch) { if (patch == null) { return false; } if (!string.IsNullOrEmpty(patch.owner)) { string text = patch.owner.ToLowerInvariant(); for (int i = 0; i < IgnoredFrameworkIdentifiers.Length; i++) { if (text.Contains(IgnoredFrameworkIdentifiers[i])) { return true; } } } if (patch.PatchMethod != null && patch.PatchMethod.DeclaringType != null) { string text2 = patch.PatchMethod.DeclaringType.Assembly.GetName().Name.ToLowerInvariant(); for (int j = 0; j < IgnoredFrameworkIdentifiers.Length; j++) { if (text2.Contains(IgnoredFrameworkIdentifiers[j])) { return true; } } } return false; } private static void RegisterModuleDisableMappings() { _moduleDisableActions.Clear(); _moduleDisableActions[typeof(AIPatches)] = delegate { AIPatches.Enabled = false; }; _moduleDisableActions[typeof(PathfindingScheduler)] = delegate { AIPatches.Enabled = false; }; _moduleDisableActions[typeof(CharacterPhysicsLODPatches)] = delegate { CharacterPhysicsLODPatches.Enabled = false; }; _moduleDisableActions[typeof(TamedIdlePatches)] = delegate { TamedIdleOptimizer.Enabled = false; }; _moduleDisableActions[typeof(ZoneSystemPlaceVegetationPatch)] = delegate { ZoneSystemPlaceVegetationPatch.Enabled = false; }; _moduleDisableActions[typeof(VegetationOptimizerPatches)] = delegate { VegetationOptimizerPatches.Enabled = false; }; _moduleDisableActions[typeof(TerrainMeshCacheZNetScenePatch)] = delegate { TerrainMeshCache.Enabled = false; TerrainMeshCache.Clear(); }; _moduleDisableActions[typeof(StructureOptimizerPatches)] = delegate { StructureOptimizerPatches.Enabled = false; }; _moduleDisableActions[typeof(StaticBatchingPatches)] = delegate { StaticBatchingManager.Enabled = false; StaticBatchingManager.Instance?.ClearAll(); }; _moduleDisableActions[typeof(AsyncSavePatches)] = delegate { AsyncSavePatches.Enabled = false; }; _moduleDisableActions[typeof(GCPatches)] = delegate { GCPatches.Enabled = false; }; _moduleDisableActions[typeof(GCCollectPatch)] = delegate { GCPatches.Enabled = false; }; _moduleDisableActions[typeof(JitPatches)] = delegate { JitPatches.Enabled = false; }; _moduleDisableActions[typeof(GPUInstancingPatches)] = delegate { GPUInstancingManager.Enabled = false; GPUInstancingManager.ClearCache(); }; _moduleDisableActions[typeof(LightCullingPatches)] = delegate { VPOLightCullingManager.Enabled = false; VPOLightCullingManager.Instance?.Clear(); }; _moduleDisableActions[typeof(LODGeneratorInitPatch)] = delegate { LODGenerator.Enabled = false; }; _moduleDisableActions[typeof(VanillaCameraCachePatches)] = delegate { VanillaCameraCachePatches.Enabled = false; VPOCameraCache.Invalidate(); }; _moduleDisableActions[typeof(ZDOOptimizer)] = delegate { ZDOOptimizer.Enabled = false; }; _moduleDisableActions[typeof(MinimapOptimizer)] = delegate { MinimapOptimizer.Enabled = false; }; _moduleDisableActions[typeof(ChunkyPatches)] = delegate { ChunkyManager.Enabled = false; ChunkyManager.Instance?.StopPregeneration(); }; _moduleDisableActions[typeof(SmokePatch)] = delegate { SmokePatch.Enabled = false; }; _moduleDisableActions[typeof(TorchOptimizer)] = delegate { TorchOptimizer.Enabled = false; }; } public static void ScanActiveHarmonyPatches() { try { List<MethodBase> list = Harmony.GetAllPatchedMethods().ToList(); if (list.Count == 0) { return; } foreach (MethodBase item in list) { if (item == null || item.DeclaringType == null) { continue; } Patches patchInfo = Harmony.GetPatchInfo(item); if (patchInfo == null) { continue; } List<Patch> list2 = patchInfo.Prefixes.Where((Patch p) => !IsOurOwnPatch(p) && !IsIgnoredFramework(p)).ToList(); List<Patch> list3 = patchInfo.Transpilers.Where((Patch p) => !IsOurOwnPatch(p) && !IsIgnoredFramework(p)).ToList(); List<Patch> list4 = patchInfo.Postfixes.Where((Patch p) => !IsOurOwnPatch(p) && !IsIgnoredFramework(p)).ToList(); if (list2.Count + list3.Count + list4.Count == 0) { continue; } bool flag = false; string hookType = ""; if (Sensitivity == ConflictSensitivity.Aggressive) { flag = true; hookType = "Сторонний хук (Агрессивный режим)"; } else if (list3.Count > 0) { flag = true; hookType = "Сторонний Transpiler (IL-инъекция)"; } else if (list2.Count > 0) { flag = true; hookType = "Сторонний Prefix (Перехват управления)"; } if (flag) { IEnumerable<string> values = (from o in list2.Select((Patch p) => p.owner).Concat(list3.Select((Patch p) => p.owner)).Concat(list4.Select((Patch p) => p.owner)) where !string.IsNullOrEmpty(o) select o).Distinct(); string foreignOwners = string.Join(", ", values); HandleDynamicConflict(item.DeclaringType, item.Name, foreignOwners, hookType); } } } catch (Exception ex) { Debug.LogWarning((object)("[VPO Guard] Ошибка динамического сканирования Harmony: " + ex.Message)); } } private static void HandleDynamicConflict(Type declaringType, string methodName, string foreignOwners, string hookType) { string name = declaringType.Name; bool flag = false; if (name.IndexOf("AI", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("Pathfinding", StringComparison.OrdinalIgnoreCase) >= 0) { if (methodName.Equals("UpdateAI", StringComparison.OrdinalIgnoreCase) || methodName.Equals("DoAttack", StringComparison.OrdinalIgnoreCase) || methodName.Equals("FindPath", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(AIPatches), "AI Throttling Enabled"); DisableModuleInMemory(typeof(PathfindingScheduler), "AI Throttling Enabled"); _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("Heightmap", StringComparison.OrdinalIgnoreCase) || name.Equals("TerrainComp", StringComparison.OrdinalIgnoreCase)) { if (methodName.Equals("Regenerate", StringComparison.OrdinalIgnoreCase) || methodName.Equals("Poke", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(TerrainMeshCacheZNetScenePatch), "Terrain Mesh Cache"); TerrainMeshCache.Enabled = false; _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("ZoneSystem", StringComparison.OrdinalIgnoreCase)) { if (methodName.Equals("PlaceVegetation", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(ZoneSystemPlaceVegetationPatch), "Vegetation Spawn Slicing"); DisableModuleInMemory(typeof(VegetationOptimizerPatches), "Vegetation Spawn Slicing"); _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("Character", StringComparison.OrdinalIgnoreCase) || name.Equals("CharacterAnimEvent", StringComparison.OrdinalIgnoreCase)) { if (methodName.Equals("CustomFixedUpdate", StringComparison.OrdinalIgnoreCase) || methodName.Equals("UpdateGroundTilt", StringComparison.OrdinalIgnoreCase) || methodName.Equals("CalculateLiquidDepth", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(CharacterPhysicsLODPatches), "Character Physics LOD"); _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("WearNTear", StringComparison.OrdinalIgnoreCase) || name.Equals("Piece", StringComparison.OrdinalIgnoreCase)) { if (methodName.Equals("UpdateSupport", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(StructureOptimizerPatches), "Static Batching Enabled"); DisableModuleInMemory(typeof(StaticBatchingPatches), "Static Batching Enabled"); _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("ZNet", StringComparison.OrdinalIgnoreCase)) { if (methodName.Equals("SaveWorld", StringComparison.OrdinalIgnoreCase)) { DisableModuleInMemory(typeof(AsyncSavePatches), "Async World Saving"); _disabledTargetTypes.Add(declaringType); flag = true; } } else if (name.Equals("ZDOMan", StringComparison.OrdinalIgnoreCase) && (methodName.Equals("ServerSortSendZDOS", StringComparison.OrdinalIgnoreCase) || methodName.Equals("CreateSyncList", StringComparison.OrdinalIgnoreCase))) { DisableModuleInMemory(typeof(ZDOOptimizer), "Smart ZDO Sorting"); _disabledTargetTypes.Add(declaringType); flag = true; } if (!flag) { return; } string text = "[VPO Guard - Динамический поиск] Обнаружен сторонний мод [" + foreignOwners + "] на " + name + "." + methodName + " (" + hookType + "). Конфликтующий модуль VPO безопасно изолирован в памяти."; if (!_conflictReport.Contains(text)) { _conflictReport.Add(text); if (LogResolutions) { Debug.LogWarning((object)text); } } } public static void DisableModuleInMemory(Type patchClass, string configKeyName) { if (!(patchClass == null)) { DisableModuleForType(patchClass); if (!string.IsNullOrEmpty(configKeyName) && _suppressedConfigKeys.Add(configKeyName) && LogResolutions) { Debug.LogWarning((object)("[VPO Guard] Модуль '" + configKeyName + "' временно переведен в режим совместимости (конфигурация на диске не затронута).")); } } } public static void RunKnownPluginScan() { Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos; if (pluginInfos == null || pluginInfos.Count == 0) { return; } foreach (KnownModRule knownModRule in KnownModRules) { if (_processedRules.Contains(knownModRule.ModGuidPart)) { continue; } foreach (KeyValuePair<string, PluginInfo> item in pluginInfos) { if (string.Equals(item.Key, "com.Skarif.ValheimPerformanceOverhaul_WATER", StringComparison.OrdinalIgnoreCase)) { continue; } string text = item.Key.ToLowerInvariant(); PluginInfo value = item.Value; object obj; if (value == null) { obj = null; } else { BepInPlugin metadata = value.Metadata; obj = ((metadata == null) ? null : metadata.Name?.ToLowerInvariant()); } if (obj == null) { obj = ""; } string text2 = (string)obj; if (text.Contains(knownModRule.ModGuidPart) || text2.Contains(knownModRule.ModGuidPart)) { knownModRule.DisableAction?.Invoke(); _processedRules.Add(knownModRule.ModGuidPart); string text3 = "[VPO Guard] Обнаружен мод '" + knownModRule.ModFriendlyName + "' (" + item.Key + "). Модуль [" + knownModRule.ModuleName + "] изолирован в памяти. Причина: " + knownModRule.Reason; _conflictReport.Add(text3); if (LogResolutions) { Debug.LogWarning((object)text3); } break; } } } } private static void DisablePatchTypeHierarchy(Type rootType) { if (!(rootType == null)) { _disabledPatchTypes.Add(rootType); Type[] nestedTypes = rootType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); foreach (Type item in nestedTypes) { _disabledPatchTypes.Add(item); } } } public static bool IsHarmonyPatchType(Type type) { if (type == null) { return false; } if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Length != 0) { return true; } return type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Any((MethodInfo m) => m.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Length != 0 || m.GetCustomAttributes(typeof(HarmonyPrefix), inherit: false).Length != 0 || m.GetCustomAttributes(typeof(HarmonyPostfix), inherit: false).Length != 0 || m.GetCustomAttributes(typeof(HarmonyTranspiler), inherit: false).Length != 0 || m.GetCustomAttributes(typeof(HarmonyFinalizer), inherit: false).Length != 0); } private static IEnumerable<Type> GetPatchTargetTypes(Type patchClass) { HashSet<Type> hashSet = new HashSet<Type>(); if (patchClass == null) { return hashSet; } foreach (HarmonyPatch item in patchClass.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Cast<HarmonyPatch>()) { if (((HarmonyAttribute)item).info.declaringType != null) { hashSet.Add(((HarmonyAttribute)item).info.declaringType); } } MethodInfo[] methods = patchClass.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { foreach (HarmonyPatch item2 in methods[i].GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Cast<HarmonyPatch>()) { if (((HarmonyAttribute)item2).info.declaringType != null) { hashSet.Add(((HarmonyAttribute)item2).info.declaringType); } } } return hashSet; } public static bool CanSafelyPatch(Type patchClass, string modGuid, out string conflictReason) { conflictReason = string.Empty; if (!Enabled) { return true; } if (!_registeredPatchClasses.Contains(patchClass)) { _registeredPatchClasses.Add(patchClass); } if (_disabledPatchTypes.Contains(patchClass) || (patchClass.DeclaringType != null && _disabledPatchTypes.Contains(patchClass.DeclaringType))) { conflictReason = "Модуль отключен защитой совместимости."; return false; } foreach (Type patchTargetType in GetPatchTargetTypes(patchClass)) { if (patchTargetType != null && _disabledTargetTypes.Contains(patchTargetType)) { conflictReason = "Целевой класс [" + patchTargetType.Name + "] перехвачен сторонним модом."; return false; } } return true; } public static void DisableModuleForType(Type patchClass) { if (!(patchClass == null)) { Type type = patchClass; while (type.DeclaringType != null) { type = type.DeclaringType; } DisablePatchTypeHierarchy(type); DisablePatchTypeHierarchy(patchClass); UnpatchClass(_guardHarmonyInstance, type); UnpatchClass(_guardHarmonyInstance, patchClass); if (_moduleDisableActions.TryGetValue(type, out var value)) { value?.Invoke(); } } } public static void UnpatchClass(Harmony harmony, Type patchType) { if (harmony == null || patchType == null) { return; } try { MethodInfo[] methods = patchType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodBase item in harmony.GetPatchedMethods().ToList()) { Patches patchInfo = Harmony.GetPatchInfo(item); if (patchInfo == null) { continue; } foreach (Patch item2 in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers)) { if (item2.PatchMethod != null && (item2.PatchMethod.DeclaringType == patchType || methods.Contains(item2.PatchMethod))) { harmony.Unpatch(item, item2.PatchMethod); } } } } catch (Exception ex) { Debug.LogWarning((object)("[VPO Guard] Ошибка динамического снятия патча " + patchType.Name + ": " + ex.Message)); } } public static void PerformLateCompatibilityAudit() { if (Enabled && Sensitivity != ConflictSensitivity.KnownOnly) { RunKnownPluginScan(); ScanActiveHarmonyPatches(); } } public static bool IsConfigSuppressed(string configKey) { return _suppressedConfigKeys.Contains(configKey); } public static IReadOnlyList<string> GetConflictReport() { return _conflictReport.AsReadOnly(); } } [HarmonyPatch] public static class ModConflictGuardLateAuditPatch { [HarmonyPatch(typeof(FejdStartup), "Awake")] [HarmonyPostfix] [HarmonyPriority(0)] private static void OnFejdStartupAwake() { ModConflictGuard.PerformLateCompatibilityAudit(); } } public class AIOptimizer : MonoBehaviour { private static readonly Dictionary<int, AIOptimizer> _instances = new Dictionary<int, AIOptimizer>(512); private BaseAI _ai; private ZNetView _nview; private Character _character; private int _instanceId; internal int ManagerIndex = -1; private float _distCheckTimer; private const float DIST_CHECK_INTERVAL = 1f; private float _closestPlayerDistSqr = 1000000f; private Character _cachedEnemy; private float _lastAttackCheck; public BaseAI AI => _ai; public Character Character => _character; public ZNetView NView => _nview; public static bool TryGet(int instanceId, out AIOptimizer optimizer) { return _instances.TryGetValue(instanceId, out optimizer); } private void Awake() { _instanceId = ((Object)this).GetInstanceID(); _ai = ((Component)this).GetComponent<BaseAI>(); _nview = ((Component)this).GetComponent<ZNetView>(); _character = ((Component)this).GetComponent<Character>(); } private void OnEnable() { _instances[_instanceId] = this; _closestPlayerDistSqr = 0f; _distCheckTimer = 1f; _cachedEnemy = null; _lastAttackCheck = -100f; AIOptimizerManager.Instance?.Register(this); } private void OnDisable() { _instances.Remove(_instanceId); AIOptimizerManager.Instance?.Unregister(this); } public float GetDistanceToPlayer() { return Mathf.Sqrt(_closestPlayerDistSqr); } public float GetDistanceToPlayerSqr() { return _closestPlayerDistSqr; } public void DoOptimizeTick() { if (!((Object)(object)_nview == (Object)null) && _nview.IsValid() && _nview.IsOwner()) { _distCheckTimer += Time.fixedDeltaTime; if (!(_distCheckTimer < 1f)) { _distCheckTimer = 0f; UpdateClosestPlayerDistance(); } } } private void UpdateClosestPlayerDistance() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) _closestPlayerDistSqr = 1000000f; Vector3 position = ((Component)this).transform.position; Vector3 val; if ((Object)(object)Player.m_localPlayer != (Object)null) { val = ((Component)Player.m_localPlayer).transform.position - position; _closestPlayerDistSqr = ((Vector3)(ref val)).sqrMagnitude; } List<Player> allPlayers = Player.GetAllPlayers(); if (allPlayers == null || allPlayers.Count <= 1) { return; } for (int i = 0; i < allPlayers.Count; i++) { Player val2 = allPlayers[i]; if (!((Object)(object)val2 == (Object)null)) { val = ((Component)val2).transform.position - position; float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude; if (sqrMagnitude < _closestPlayerDistSqr) { _closestPlayerDistSqr = sqrMagnitude; } } } } public bool ShouldCheckAttack() { float time = Time.time; float interval = GetInterval(0.3f, 1f); if (time - _lastAttackCheck >= interval) { _lastAttackCheck = time; return true; } return false; } private float GetInterval(float min, float max) { if (_closestPlayerDistSqr < 1600f) { return min; } if (_closestPlayerDistSqr > 14400f) { return max; } float num = (_closestPlayerDistSqr - 1600f) / 12800f; return Mathf.Lerp(min, max, num); } private void OnDestroy() { _instances.Remove(_instanceId); } } public class AIOptimizerManager : MonoBehaviour { private readonly List<AIOptimizer> _optimizers = new List<AIOptimizer>(512); public static AIOptimizerManager Instance { get; private set; } public static void Initialize() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (!((Object)(object)Instance != (Object)null)) { GameObject val = new GameObject("_VPO_AIOptimizerManager"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<AIOptimizerManager>(); } } private void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } Instance = this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); } public void Register(AIOptimizer optimizer) { if (!((Object)(object)optimizer == (Object)null) && optimizer.ManagerIndex < 0) { optimizer.ManagerIndex = _optimizers.Count; _optimizers.Add(optimizer); } } public void Unregister(AIOptimizer optimizer) { if ((Object)(object)optimizer == (Object)null || optimizer.ManagerIndex < 0) { return; } int managerIndex = optimizer.ManagerIndex; int num = _optimizers.Count - 1; if (managerIndex < num) { AIOptimizer aIOptimizer = _optimizers[num]; _optimizers[managerIndex] = aIOptimizer; if ((Object)(object)aIOptimizer != (Object)null) { aIOptimizer.ManagerIndex = managerIndex; } } _optimizers.RemoveAt(num); optimizer.ManagerIndex = -1; } private void FixedUpdate() { if (!AIPatches.Enabled) { return; } for (int num = _optimizers.Count - 1; num >= 0; num--) { AIOptimizer aIOptimizer = _optimizers[num]; if ((Object)(object)aIOptimizer == (Object)null) { int num2 = _optimizers.Count - 1; if (num < num2) { AIOptimizer aIOptimizer2 = _optimizers[num2]; _optimizers[num] = aIOptimizer2; if ((Object)(object)aIOptimizer2 != (Object)null) { aIOptimizer2.ManagerIndex = num; } } _optimizers.RemoveAt(num2); } else { aIOptimizer.DoOptimizeTick(); } } } private void OnDestroy() { _optimizers.Clear(); if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } } } [HarmonyPatch] public static class AIPatches { public static bool Enabled; public static float AIFarInterval; private const float AI_ACTIVATION_RADIUS_SQR = 3600f; private static readonly FieldRef<BaseAI, ZNetView> _getNView; private static readonly FieldRef<BaseAI, float> _timeSinceHurt; private static readonly Action<BaseAI, float> _updateRegenFast; private static readonly Action<BaseAI, float> _updateTakeoffFast; private static readonly Dictionary<int, float> _lastSlowUpdate; private static readonly List<int> _cleanupBuffer; static AIPatches() { Enabled = true; AIFarInterval = 1f; _getNView = AccessTools.FieldRefAccess<BaseAI, ZNetView>("m_nview"); _timeSinceHurt = AccessTools.FieldRefAccess<BaseAI, float>("m_timeSinceHurt"); _lastSlowUpdate = new Dictionary<int, float>(256); _cleanupBuffer = new List<int>(64); try { MethodInfo methodInfo = AccessTools.Method(typeof(BaseAI), "UpdateRegeneration", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo != null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(BaseAI), "ai"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(float), "dt"); _updateRegenFast = Expression.Lambda<Action<BaseAI, float>>(Expression.Call(parameterExpression, methodInfo, parameterExpression2), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile(); } MethodInfo methodInfo2 = AccessTools.Method(typeof(BaseAI), "UpdateTakeoffLanding", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo2 != null) { ParameterExpression parameterExpression3 = Expression.Parameter(typeof(BaseAI), "ai"); ParameterExpression parameterExpression4 = Expression.Parameter(typeof(float), "dt"); _updateTakeoffFast = Expression.Lambda<Action<BaseAI, float>>(Expression.Call(parameterExpression3, methodInfo2, parameterExpression4), new ParameterExpression[2] { parameterExpression3, parameterExpression4 }).Compile(); } } catch (Exception ex) { Debug.LogWarning((object)("[AIPatches] Delegate compilation failed: " + ex.Message)); } } [HarmonyPatch(typeof(BaseAI), "Awake")] [HarmonyPostfix] private static void BaseAI_Awake_Postfix(BaseAI __instance) { int instanceID = ((Object)__instance).GetInstanceID(); if (!AIOptimizer.TryGet(instanceID, out var _)) { ((Component)__instance).gameObject.AddComponent<AIOptimizer>(); } Character component = ((Component)__instance).GetComponent<Character>(); if ((Object)(object)component != (Object)null && component.IsTamed() && (Object)(object)((Component)__instance).GetComponent<TamedIdleOptimizer>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<TamedIdleOptimizer>(); } _lastSlowUpdate[instanceID] = Time.time; } [HarmonyPatch(typeof(Character), "RPC_SetTamed")] [HarmonyPostfix] private static void Character_RPC_SetTamed_Postfix(Character __instance, bool tamed) { if (tamed && !((Object)(object)__instance == (Object)null) && (Object)(object)((Component)__instance).GetComponent<BaseAI>() != (Object)null && (Object)(object)((Component)__instance).GetComponent<TamedIdleOptimizer>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<TamedIdleOptimizer>(); } } [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] [HarmonyPrefix] private static bool MonsterAI_UpdateAI_Prefix(MonsterAI __instance, float dt, ref bool __result) { if (!Enabled) { return true; } int instanceID = ((Object)__instance).GetInstanceID(); if (!AIOptimizer.TryGet(instanceID, out var optimizer)) { return true; } ZNetView val = (((Object)(object)optimizer.NView != (Object)null) ? optimizer.NView : ((_getNView != null) ? _getNView.Invoke((BaseAI)(object)__instance) : null)); if ((Object)(object)val != (Object)null && !val.IsOwner()) { return true; } if (optimizer.GetDistanceToPlayerSqr() <= 3600f) { return true; } bool flag = ((BaseAI)__instance).IsAlerted() || (Object)(object)((BaseAI)__instance).GetTargetCreature() != (Object)null; float num = (flag ? 0.75f : AIFarInterval); if (!_lastSlowUpdate.TryGetValue(instanceID, out var value)) { _lastSlowUpdate[instanceID] = Time.time; return true; } if (Time.time - value < num) { if (!flag) { ((BaseAI)__instance).StopMoving(); } _updateTakeoffFast?.Invoke((BaseAI)(object)__instance, dt); _updateRegenFast?.Invoke((BaseAI)(object)__instance, dt); if (_timeSinceHurt != null) { _timeSinceHurt.Invoke((BaseAI)(object)__instance) += dt; } __result = true; return false; } _lastSlowUpdate[instanceID] = Time.time; return true; } [HarmonyPatch(typeof(BaseAI), "OnDestroy")] [HarmonyPostfix] private static void BaseAI_OnDestroy_Postfix(BaseAI __instance) { _lastSlowUpdate.Remove(((Object)__instance).GetInstanceID()); } [HarmonyPatch(typeof(MonsterAI), "DoAttack")] [HarmonyPrefix] private static bool DoAttack_Prefix(MonsterAI __instance) { if (!Enabled) { return true; } if (!AIOptimizer.TryGet(((Object)__instance).GetInstanceID(), out var optimizer)) { return true; } if (optimizer.GetDistanceToPlayerSqr() < 3600f) { return true; } return optimizer.ShouldCheckAttack(); } [HarmonyPatch(typeof(ZNet), "Update")] [HarmonyPostfix] private static void CleanupSlowUpdateCache() { if (!Enabled || Time.frameCount % 1800 != 0) { return; } float time = Time.time; _cleanupBuffer.Clear(); foreach (KeyValuePair<int, float> item in _lastSlowUpdate) { if (time - item.Value > 30f) { _cleanupBuffer.Add(item.Key); } } for (int i = 0; i < _cleanupBuffer.Count; i++) { _lastSlowUpdate.Remove(_cleanupBuffer[i]); } _cleanupBuffer.Clear(); } } [HarmonyPatch] public static class PathfindingScheduler { private static int _requestsThisFrame; private static int _lastFrameCount = -1; private const float NEAR_DISTANCE_SQR = 3600f; public static int MaxRequestsPerFrame = 5; private static readonly FieldRef<BaseAI, bool> _getLastFindPathResult = AccessTools.FieldRefAccess<BaseAI, bool>("m_lastFindPathResult"); [HarmonyTargetMethod] private static MethodBase TargetMethod() { MethodInfo methodInfo = AccessTools.Method(typeof(BaseAI), "FindPath", (Type[])null, (Type[])null); if (methodInfo != null) { return methodInfo; } Debug.LogWarning((object)"[PathfindingScheduler] BaseAI.FindPath not found — patch disabled."); return null; } [HarmonyPrefix] private static bool Prefix(BaseAI __instance, ref bool __result) { if (!AIPatches.Enabled) { return true; } if (!AIOptimizer.TryGet(((Object)__instance).GetInstanceID(), out var optimizer)) { return true; } if ((Object)(object)optimizer.Character != (Object)null && optimizer.Character.IsPlayer()) { return true; } if (optimizer.GetDistanceToPlayerSqr() <= 3600f) { return true; } int frameCount = Time.frameCount; if (frameCount != _lastFrameCount) { _lastFrameCount = frameCount; _requestsThisFrame = 0; } if (_requestsThisFrame < MaxRequestsPerFrame) { _requestsThisFrame++; return true; } __result = _getLastFindPathResult == null || _getLastFindPathResult.Invoke(__instance); return false; } } public static class AsyncSaveManager { public static bool IsSaving { get { ZNet instance = ZNet.instance; if ((Object)(object)instance != (Object)null) { return instance.IsSaving(); } return false; } } } [HarmonyPatch] public static class AsyncSavePatches { public static bool Enabled = true; [HarmonyPatch(typeof(ZNet), "SaveWorld")] [HarmonyPrefix] private static bool SaveWorld_Prefix(ZNet __instance, ref bool sync) { if (!Enabled) { return true; } if (sync || __instance.HaveStopped) { return true; } if (__instance.IsSaving()) { ZLog.LogWarning((object)"[AsyncSave] Background save is still in progress. Skipping non-critical routine save to prevent main thread hitch."); return false; } return true; } } public class CharacterPhysicsLODTag : MonoBehaviour { private static readonly FieldRef<BaseAI, float> _timeSinceHurtRef = AccessTools.FieldRefAccess<BaseAI, float>("m_timeSinceHurt"); private static readonly FieldRef<Character, Vector3> _currentVelRef = AccessTools.FieldRefAccess<Character, Vector3>("m_currentVel"); private BaseAI _baseAI; private MonsterAI _monsterAI; private ZNetView _nview; private int _tickCounter; private int _stationaryTicks; private float _distCheckTimer; private float _closestPlayerDistSqr; private const float DIST_CHECK_INTERVAL = 0.5f; private int _lastFixedFrame = -1; private bool _cachedSkipResult; public Character Character { get; private set; } public bool IsPlayer { get; private set; } public bool IsStationaryOnGround { get { if (IsPlayer || (Object)(object)Character == (Object)null) { return false; } return _stationaryTicks >= 3; } } public void Initialize(Character character) { Character = character; IsPlayer = character is Player || character.IsPlayer(); _baseAI = ((Component)this).GetComponent<BaseAI>(); _monsterAI = ((Component)this).GetComponent<MonsterAI>(); _nview = ((Component)this).GetComponent<ZNetView>(); _tickCounter = ((Object)this).GetInstanceID() & 7; _stationaryTicks = 0; _distCheckTimer = Random.Range(0f, 0.5f); _closestPlayerDistSqr = 0f; _lastFixedFrame = -1; _cachedSkipResult = false; } private bool IsStandingOnPlatform() { if ((Object)(object)Character == (Object)null) { return false; } if (Character.IsOnGround()) { return true; } if ((Object)(object)((Component)Character).transform.parent != (Object)null) { return true; } Collider lastGroundCollider = Character.GetLastGroundCollider(); if ((Object)(object)lastGroundCollider != (Object)null && ((Object)(object)((Component)lastGroundCollider).GetComponentInParent<Ship>() != (Object)null || (Object)(object)((Component)lastGroundCollider).GetComponentInParent<Piece>() != (Object)null || (Object)(object)((Component)lastGroundCollider).GetComponentInParent<Vagon>() != (Object)null)) { return true; } return false; } public void UpdateStationaryState() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (IsPlayer || (Object)(object)Character == (Object)null) { return; } Vector3 val = ((_currentVelRef != null) ? _currentVelRef.Invoke(Character) : Vector3.zero); if (!(((Vector3)(ref val)).sqrMagnitude > 0.0001f) && IsStandingOnPlatform() && !Character.InAttack() && !Character.IsStaggering()) { if (_stationaryTicks < 10) { _stationaryTicks++; } } else { _stationaryTicks = 0; } } public bool ShouldSkipFixedUpdate() { if (IsPlayer || (Object)(object)Character == (Object)null) { return false; } if ((Object)(object)_nview != (Object)null && (!_nview.IsValid() || !_nview.IsOwner())) { return false; } int frameCount = Time.frameCount; if (_lastFixedFrame == frameCount) { return _cachedSkipResult; } _lastFixedFrame = frameCount; UpdateStationaryState(); _distCheckTimer += Time.fixedDeltaTime; if (_distCheckTimer >= 0.5f) { _distCheckTimer = 0f; UpdatePlayerDistance(); } float nearDistance = CharacterPhysicsLODPatches.NearDistance; float num = nearDistance * nearDistance; if (_closestPlayerDistSqr <= num) { _cachedSkipResult = false; return false; } _tickCounter++; float farDistance = CharacterPhysicsLODPatches.FarDistance; float num2 = farDistance * farDistance; if (((_closestPlayerDistSqr <= num2) ? (_tickCounter & 1) : (_tickCounter & 3)) == 0) { _cachedSkipResult = false; return false; } if (!IsStandingOnPlatform()) { _cachedSkipResult = false; return false; } if (Character.InAttack() || Character.IsStaggering()) { _cachedSkipResult = false; return false; } if (Character.InLiquid() || Character.InWater()) { _cachedSkipResult = false; return false; } if ((Object)(object)_baseAI != (Object)null) { if (_baseAI.IsAlerted() || (Object)(object)_baseAI.GetTargetCreature() != (Object)null || _baseAI.HaveTarget()) { _cachedSkipResult = false; return false; } if (_timeSinceHurtRef != null && _timeSinceHurtRef.Invoke(_baseAI) < 2f) { _cachedSkipResult = false; return false; } } if ((Object)(object)_monsterAI != (Object)null && (Object)(object)((BaseAI)_monsterAI).GetTargetCreature() != (Object)null) { _cachedSkipResult = false; return false; } _cachedSkipResult = true; return true; } private void UpdatePlayerDistance() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to inval
BepInEx/plugins/UnityEngine.ImageConversionModule.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Experimental.Rendering; [assembly: InternalsVisibleTo("Unity.IntegrationTests.Timeline")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Framework")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Framework.Tests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework.Tests")] [assembly: InternalsVisibleTo("Unity.PerformanceTests.RuntimeTestRunner.Tests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.AllIn1Runner")] [assembly: InternalsVisibleTo("Unity.Timeline")] [assembly: InternalsVisibleTo("Assembly-CSharp-testable")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.UnityAnalytics")] [assembly: InternalsVisibleTo("Assembly-CSharp-firstpass-testable")] [assembly: InternalsVisibleTo("GoogleAR.UnityNative")] [assembly: InternalsVisibleTo("Unity.WindowsMRAutomation")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.2D.Runtime")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.Editor")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.EditorTests")] [assembly: InternalsVisibleTo("Unity.UI.Builder.Editor")] [assembly: InternalsVisibleTo("UnityEditor.UIBuilderModule")] [assembly: InternalsVisibleTo("Unity.UI.Builder.EditorTests")] [assembly: InternalsVisibleTo("Unity.UIElements")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsGameObjectsModule")] [assembly: InternalsVisibleTo("UnityEngine.SpatialTracking")] [assembly: InternalsVisibleTo("Unity.UIElements.Editor")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.ExternalVersionControl")] [assembly: InternalsVisibleTo("Unity.DeploymentTests.Services")] [assembly: InternalsVisibleTo("UnityEngine.VideoModule")] [assembly: InternalsVisibleTo("UnityEngine.VirtualTexturingModule")] [assembly: InternalsVisibleTo("UnityEngine.WindModule")] [assembly: InternalsVisibleTo("UnityEngine.SwitchModule")] [assembly: InternalsVisibleTo("UnityEngine.Switch2Module")] [assembly: InternalsVisibleTo("UnityEngine.PS4Module")] [assembly: InternalsVisibleTo("UnityEngine.PS4VRModule")] [assembly: InternalsVisibleTo("UnityEngine.PS5Module")] [assembly: InternalsVisibleTo("UnityEngine.PS5VRModule")] [assembly: UnityEngineModuleAssembly] [assembly: InternalsVisibleTo("Unity.IntegrationTests")] [assembly: InternalsVisibleTo("UnityEngine.Networking")] [assembly: InternalsVisibleTo("UnityEngine.Cloud.Service")] [assembly: InternalsVisibleTo("Unity.Analytics")] [assembly: InternalsVisibleTo("UnityEngine.Analytics")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommon")] [assembly: InternalsVisibleTo("UnityEngine.Advertisements")] [assembly: InternalsVisibleTo("UnityEngine.Purchasing")] [assembly: InternalsVisibleTo("UnityEngine.TestRunner")] [assembly: InternalsVisibleTo("Unity.Automation")] [assembly: InternalsVisibleTo("Unity.Burst")] [assembly: InternalsVisibleTo("Unity.Burst.Editor")] [assembly: InternalsVisibleTo("UnityEngine.Cloud")] [assembly: InternalsVisibleTo("Unity.UIElements.PlayModeTests")] [assembly: InternalsVisibleTo("Unity.UI.TestFramework.Runtime")] [assembly: InternalsVisibleTo("UnityEditor.UIElements.Tests")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.009")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.010")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.011")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.012")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.013")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.014")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.015")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.016")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.017")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.018")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.008")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.019")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.021")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.022")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.023")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.024")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.005")] [assembly: InternalsVisibleTo("Unity.Subsystem.Registration")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.020")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.007")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.006")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.005")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.Base")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.Bindings")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.Controls")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.StyleSheets")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.Utils")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests.UXML")] [assembly: InternalsVisibleTo("Unity.UIElements.EditorTests")] [assembly: InternalsVisibleTo("Unity.UIElements.RuntimeTests")] [assembly: InternalsVisibleTo("UnityEngine.UI")] [assembly: InternalsVisibleTo("Unity.Networking.Transport")] [assembly: InternalsVisibleTo("Unity.ucg.QoS")] [assembly: InternalsVisibleTo("Unity.Services.QoS")] [assembly: InternalsVisibleTo("Unity.Logging")] [assembly: InternalsVisibleTo("Unity.Entities")] [assembly: InternalsVisibleTo("Unity.Entities.Tests")] [assembly: InternalsVisibleTo("Unity.Collections")] [assembly: InternalsVisibleTo("Unity.Runtime")] [assembly: InternalsVisibleTo("Unity.Core")] [assembly: InternalsVisibleTo("UnityEngine.Core.Runtime.Tests")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.004")] [assembly: InternalsVisibleTo("UnityEngine.VehiclesModule")] [assembly: InternalsVisibleTo("UnityEngine.VRModule")] [assembly: InternalsVisibleTo("UnityEngine.XRModule")] [assembly: InternalsVisibleTo("UnityEngine.VFXModule")] [assembly: InternalsVisibleTo("Unity.ImageConversionTests")] [assembly: InternalsVisibleTo("UnityEngine.ClusterInputModule")] [assembly: InternalsVisibleTo("UnityEngine.ClusterRendererModule")] [assembly: InternalsVisibleTo("UnityEngine.ContentLoadModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityConnectModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommonModule")] [assembly: InternalsVisibleTo("UnityEngine.AudioModule")] [assembly: InternalsVisibleTo("UnityEngine.TLSModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsModule")] [assembly: InternalsVisibleTo("UnityEngine.CrashReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.DSPGraphModule")] [assembly: InternalsVisibleTo("UnityEngine.DirectorModule")] [assembly: InternalsVisibleTo("UnityEngine.GIModule")] [assembly: InternalsVisibleTo("UnityEngine.ImageConversionModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestModule")] [assembly: InternalsVisibleTo("UnityEngine.AssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.HotReloadModule")] [assembly: InternalsVisibleTo("UnityEngine.AnimationModule")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: InternalsVisibleTo("UnityEngine")] [assembly: InternalsVisibleTo("UnityEngine.SharedInternalsModule")] [assembly: InternalsVisibleTo("UnityEngine.CoreModule")] [assembly: InternalsVisibleTo("UnityEngine.AIModule")] [assembly: InternalsVisibleTo("UnityEngine.AMDModule")] [assembly: InternalsVisibleTo("UnityEngine.PhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.JSONSerializeModule")] [assembly: InternalsVisibleTo("UnityEngine.InputModule")] [assembly: InternalsVisibleTo("UnityEngine.ARModule")] [assembly: InternalsVisibleTo("UnityEngine.AccessibilityModule")] [assembly: InternalsVisibleTo("UnityEngine.AndroidJNIModule")] [assembly: InternalsVisibleTo("UnityEngine.GameCenterModule")] [assembly: InternalsVisibleTo("UnityEngine.GraphicsStateCollectionSerializerModule")] [assembly: InternalsVisibleTo("UnityEngine.ClothModule")] [assembly: InternalsVisibleTo("UnityEngine.HierarchyCoreModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteMaskModule")] [assembly: InternalsVisibleTo("UnityEngine.StreamingModule")] [assembly: InternalsVisibleTo("UnityEngine.SubstanceModule")] [assembly: InternalsVisibleTo("UnityEngine.SubsystemsModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainPhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.UIModule")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] [assembly: InternalsVisibleTo("UnityEngine.UmbraModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityCurlModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityTestProtocolModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAudioModule")] [assembly: InternalsVisibleTo("UnityEngine.GridModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestWWWModule")] [assembly: InternalsVisibleTo("UnityEngine.TilemapModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteShapeModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestTextureModule")] [assembly: InternalsVisibleTo("UnityEngine.ScreenCaptureModule")] [assembly: InternalsVisibleTo("UnityEngine.TextRenderingModule")] [assembly: InternalsVisibleTo("UnityEngine.InputLegacyModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreFontEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreTextEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.IMGUIModule")] [assembly: InternalsVisibleTo("UnityEngine.InputForUIModule")] [assembly: InternalsVisibleTo("UnityEngine.MarshallingModule")] [assembly: InternalsVisibleTo("UnityEngine.LocalizationModule")] [assembly: InternalsVisibleTo("UnityEngine.NVIDIAModule")] [assembly: InternalsVisibleTo("UnityEngine.ParticleSystemModule")] [assembly: InternalsVisibleTo("UnityEngine.PerformanceReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.Physics2DModule")] [assembly: InternalsVisibleTo("UnityEngine.PropertiesModule")] [assembly: InternalsVisibleTo("UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule")] [assembly: InternalsVisibleTo("UnityEngine.MultiplayerModule")] [assembly: InternalsVisibleTo("UnityEngine.ShaderVariantAnalyticsModule")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace UnityEngine; [NativeHeader("Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.h")] public static class ImageConversion { public static bool EnableLegacyPngGammaRuntimeLoadBehavior { get { return GetEnableLegacyPngGammaRuntimeLoadBehavior(); } set { SetEnableLegacyPngGammaRuntimeLoadBehavior(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ImageConversionBindings::GetEnableLegacyPngGammaRuntimeLoadBehavior", IsFreeFunction = true, ThrowsException = false)] private static extern bool GetEnableLegacyPngGammaRuntimeLoadBehavior(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ImageConversionBindings::SetEnableLegacyPngGammaRuntimeLoadBehavior", IsFreeFunction = true, ThrowsException = false)] private static extern void SetEnableLegacyPngGammaRuntimeLoadBehavior(bool enable); [NativeMethod(Name = "ImageConversionBindings::EncodeToTGA", IsFreeFunction = true, ThrowsException = true)] public static byte[] EncodeToTGA(this Texture2D tex) { BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeToTGA_Injected(MarshalledUnityObject.Marshal<Texture2D>(tex), out ret); } finally { byte[] array = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array); result = array; } return result; } [NativeMethod(Name = "ImageConversionBindings::EncodeToPNG", IsFreeFunction = true, ThrowsException = true)] public static byte[] EncodeToPNG(this Texture2D tex) { BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeToPNG_Injected(MarshalledUnityObject.Marshal<Texture2D>(tex), out ret); } finally { byte[] array = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array); result = array; } return result; } [NativeMethod(Name = "ImageConversionBindings::EncodeToJPG", IsFreeFunction = true, ThrowsException = true)] public static byte[] EncodeToJPG(this Texture2D tex, int quality) { BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeToJPG_Injected(MarshalledUnityObject.Marshal<Texture2D>(tex), quality, out ret); } finally { byte[] array = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array); result = array; } return result; } public static byte[] EncodeToJPG(this Texture2D tex) { return tex.EncodeToJPG(75); } [NativeMethod(Name = "ImageConversionBindings::EncodeToEXR", IsFreeFunction = true, ThrowsException = true)] public static byte[] EncodeToEXR(this Texture2D tex, EXRFlags flags) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeToEXR_Injected(MarshalledUnityObject.Marshal<Texture2D>(tex), flags, out ret); } finally { byte[] array = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array); result = array; } return result; } public static byte[] EncodeToEXR(this Texture2D tex) { return tex.EncodeToEXR((EXRFlags)0); } [NativeMethod(Name = "ImageConversionBindings::EncodeToR2D", IsFreeFunction = true, ThrowsException = true)] internal static byte[] EncodeToR2DInternal(this Texture2D tex) { BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeToR2DInternal_Injected(MarshalledUnityObject.Marshal<Texture2D>(tex), out ret); } finally { byte[] array = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array); result = array; } return result; } [NativeMethod(Name = "ImageConversionBindings::LoadImage", IsFreeFunction = true)] public unsafe static bool LoadImage([NotNull] this Texture2D tex, ReadOnlySpan<byte> data, bool markNonReadable) { if (tex == null) { ThrowHelper.ThrowArgumentNullException((object)tex, "tex"); } IntPtr intPtr = MarshalledUnityObject.MarshalNotNull<Texture2D>(tex); if (intPtr == (IntPtr)0) { ThrowHelper.ThrowArgumentNullException((object)tex, "tex"); } ReadOnlySpan<byte> readOnlySpan = data; bool result; fixed (byte* ptr = readOnlySpan) { ManagedSpanWrapper data2 = default(ManagedSpanWrapper); ((ManagedSpanWrapper)(ref data2))..ctor((void*)ptr, readOnlySpan.Length); result = LoadImage_Injected(intPtr, ref data2, markNonReadable); } return result; } public static bool LoadImage(this Texture2D tex, ReadOnlySpan<byte> data) { return tex.LoadImage(data, markNonReadable: false); } public static bool LoadImage(this Texture2D tex, byte[] data, bool markNonReadable) { return tex.LoadImage(new ReadOnlySpan<byte>(data), markNonReadable); } public static bool LoadImage(this Texture2D tex, byte[] data) { return tex.LoadImage(new ReadOnlySpan<byte>(data), markNonReadable: false); } [FreeFunction("ImageConversionBindings::EncodeArrayToTGA", true)] public static byte[] EncodeArrayToTGA(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeArrayToTGA_Injected(array, format, width, height, rowBytes, out ret); } finally { byte[] array2 = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array2); result = array2; } return result; } [FreeFunction("ImageConversionBindings::EncodeArrayToPNG", true)] public static byte[] EncodeArrayToPNG(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeArrayToPNG_Injected(array, format, width, height, rowBytes, out ret); } finally { byte[] array2 = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array2); result = array2; } return result; } [FreeFunction("ImageConversionBindings::EncodeArrayToJPG", true)] public static byte[] EncodeArrayToJPG(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, int quality = 75) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeArrayToJPG_Injected(array, format, width, height, rowBytes, quality, out ret); } finally { byte[] array2 = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array2); result = array2; } return result; } [FreeFunction("ImageConversionBindings::EncodeArrayToEXR", true)] public static byte[] EncodeArrayToEXR(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, EXRFlags flags = (EXRFlags)0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeArrayToEXR_Injected(array, format, width, height, rowBytes, flags, out ret); } finally { byte[] array2 = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array2); result = array2; } return result; } [FreeFunction("ImageConversionBindings::EncodeArrayToR2D", true)] internal static byte[] EncodeArrayToR2DInternal(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) BlittableArrayWrapper ret = default(BlittableArrayWrapper); byte[] result; try { EncodeArrayToR2DInternal_Injected(array, format, width, height, rowBytes, out ret); } finally { byte[] array2 = default(byte[]); ((BlittableArrayWrapper)(ref ret)).Unmarshal<byte>(ref array2); result = array2; } return result; } public unsafe static NativeArray<byte> EncodeNativeArrayToTGA<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) where T : struct { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) int sizeInBytes = input.Length * UnsafeUtility.SizeOf<T>(); void* ptr = UnsafeEncodeNativeArrayToTGA(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref sizeInBytes, format, width, height, rowBytes); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, sizeInBytes, (Allocator)4); } public unsafe static NativeArray<byte> EncodeNativeArrayToPNG<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) where T : struct { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) int sizeInBytes = input.Length * UnsafeUtility.SizeOf<T>(); void* ptr = UnsafeEncodeNativeArrayToPNG(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref sizeInBytes, format, width, height, rowBytes); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, sizeInBytes, (Allocator)4); } public unsafe static NativeArray<byte> EncodeNativeArrayToJPG<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, int quality = 75) where T : struct { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) int sizeInBytes = input.Length * UnsafeUtility.SizeOf<T>(); void* ptr = UnsafeEncodeNativeArrayToJPG(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref sizeInBytes, format, width, height, rowBytes, quality); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, sizeInBytes, (Allocator)4); } public unsafe static NativeArray<byte> EncodeNativeArrayToEXR<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, EXRFlags flags = (EXRFlags)0) where T : struct { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) int sizeInBytes = input.Length * UnsafeUtility.SizeOf<T>(); void* ptr = UnsafeEncodeNativeArrayToEXR(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref sizeInBytes, format, width, height, rowBytes, flags); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, sizeInBytes, (Allocator)4); } internal unsafe static NativeArray<byte> EncodeNativeArrayToR2DInternal<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u) where T : struct { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) int sizeInBytes = input.Length * UnsafeUtility.SizeOf<T>(); void* ptr = UnsafeEncodeNativeArrayToR2D(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref sizeInBytes, format, width, height, rowBytes); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, sizeInBytes, (Allocator)4); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ImageConversionBindings::UnsafeEncodeNativeArrayToTGA", true)] private unsafe static extern void* UnsafeEncodeNativeArrayToTGA(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ImageConversionBindings::UnsafeEncodeNativeArrayToPNG", true)] private unsafe static extern void* UnsafeEncodeNativeArrayToPNG(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ImageConversionBindings::UnsafeEncodeNativeArrayToJPG", true)] private unsafe static extern void* UnsafeEncodeNativeArrayToJPG(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, int quality = 75); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ImageConversionBindings::UnsafeEncodeNativeArrayToEXR", true)] private unsafe static extern void* UnsafeEncodeNativeArrayToEXR(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u, EXRFlags flags = (EXRFlags)0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ImageConversionBindings::UnsafeEncodeNativeArrayToR2D", true)] private unsafe static extern void* UnsafeEncodeNativeArrayToR2D(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0u); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeToTGA_Injected(IntPtr tex, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeToPNG_Injected(IntPtr tex, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeToJPG_Injected(IntPtr tex, int quality, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeToEXR_Injected(IntPtr tex, EXRFlags flags, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeToR2DInternal_Injected(IntPtr tex, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool LoadImage_Injected(IntPtr tex, ref ManagedSpanWrapper data, bool markNonReadable); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeArrayToTGA_Injected(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeArrayToPNG_Injected(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeArrayToJPG_Injected(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes, int quality, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeArrayToEXR_Injected(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes, EXRFlags flags, out BlittableArrayWrapper ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EncodeArrayToR2DInternal_Injected(Array array, GraphicsFormat format, uint width, uint height, uint rowBytes, out BlittableArrayWrapper ret); }