diff --git a/AGENTS.md b/AGENTS.md index cd943f8..733f139 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,7 +142,7 @@ The sync is implemented as an inline PowerShell `Exec` step inside the `ZipMod` ## Key Architectural Patterns - - Auto-construct motion recovery treats only actual movement keys as manual override, yields to active auto-navigation, clears stale move orders before flight ascent, returns before issuing a same-frame route after switching from walking to flying, and performs one stop-equivalent recovery when a route circles without radial progress. Planner candidates use fixed angular fan sectors with near and far representatives instead of retaining only globally nearest ghosts. Arrival follows the game's surface-direction order semantics. Site selection follows a nearest-cluster route: it prefers the best local candidate within a build-area-scaled horizon and falls back to the nearest candidate, rather than selecting a distant high-density cluster and forcing return flights. A site is held only while its first construction-drone wave remains below capacity and its current throughput is not meaningfully beaten by a nearby candidate; it must not wait merely to exhaust every ghost in range, because waiting extends drone round trips and mecha power use. Normal route changes still brake and wait for tangential flight speed to settle, but recovery detours, their continuation points, and the resumed final route bypass flight settling so they can take over before the mecha stops. Refinement destinations are selected from the scanned ghost positions. After a destination is chosen, eligible ghosts in its approach corridor are reduced to the closest route-prefix ghost so travel cannot bypass nearer construction work. Obstacle probing is only allowed to initiate a detour after stuck or orbit evidence; it detects overlapping colliders, derives a horizontal footprint radius from the collider bounds, tests tangent candidates at several radii and sides, chooses the least-blocked horizontal fallback when no fully clear tangent exists, and a completed detour resumes the final construction route instead of resetting the plan. + - Auto-construct motion recovery treats only actual movement keys as manual override (through the shared `PlayerInputUtil.HasManualMovementInput`), yields to active auto-navigation, clears stale move orders before flight ascent, returns before issuing a same-frame route after switching from walking to flying, and performs one stop-equivalent recovery when a route circles without radial progress. Planner candidates use fixed angular fan sectors with near and far representatives instead of retaining only globally nearest ghosts; a sector's near/far separation is measured as a real distance between the two representatives, and a displaced near representative is demoted to the far slot so the pair does not depend on prebuild iteration order. Arrival follows the game's surface-direction order semantics. Site selection follows a nearest-cluster route: it prefers the best local candidate within a build-area-scaled horizon and falls back to the nearest candidate, rather than selecting a distant high-density cluster and forcing return flights. A site is held only while its first construction-drone wave remains below capacity and its current throughput is not meaningfully beaten by a nearby candidate; it must not wait merely to exhaust every ghost in range, because waiting extends drone round trips and mecha power use. Normal route changes still brake and wait for tangential flight speed to settle, but recovery detours, their continuation points, and the resumed final route bypass flight settling so they can take over before the mecha stops. Refinement destinations are selected from the scanned ghost positions. After a destination is chosen, eligible ghosts in its approach corridor are reduced to the closest route-prefix ghost so travel cannot bypass nearer construction work; the corridor half-width is compared as a sine against the candidate's out-of-plane component, never as an angle against a sine. Obstacle probing is only allowed to initiate a detour after stuck or orbit evidence; it detects overlapping colliders, derives a horizontal footprint radius from the collider bounds, tests tangent candidates at several radii and sides, chooses the least-blocked horizontal fallback when no fully clear tangent exists, and a completed detour resumes the final construction route instead of resetting the plan. Distances between surface positions are great-circle distances, not chord lengths. - **Shared library:** `UXAssist` acts as a common library. `CheatEnabler` and `UniverseGenTweaks` reference `UXAssist.csproj` directly to reuse `Common/`, `UI/`, and config panel infrastructure. - **Centralized mod-feature lifecycle:** `UXAssist.Common.ModFeatures.ModFeatureRegistry` holds shared static lists of mod features discovered across all mods. **Only UXAssist drives the shared deferred lifecycle** (`StartAll`/`UninitAll`/`OnInputUpdateAll`/`OnUpdateAll`); these dispatchers are `internal` so dependent mods (separate assemblies, no `InternalsVisibleTo`) cannot call them and re-trigger other mods' features. A feature's `Init` runs **eagerly** when it is registered (via `Discover`/`Register`), preserving the original `Awake`-phase timing that keybind registration and other early setup rely on — the game's `UIOptionWindow._OnCreate` copies registered keybinds only after all plugins have finished loading. Dependent mods only call `ModFeatureRegistry.Discover(Assembly.GetExecutingAssembly())` (and optionally `Register()`) in their `Awake`. UXAssist begins the deferred lifecycle from its own `Start`; if a dependent feature is discovered after that transition, the registry starts it immediately after initialization so it cannot miss `Start`. The registry also guards start idempotency per feature (start at most once; uninit resets) and per-frame re-entrancy (`Time.frameCount`) for the update dispatchers, as defense-in-depth. @@ -156,12 +156,15 @@ The sync is implemented as an inline PowerShell `Exec` step inside the `ZipMod` - **Immediate-build beacon timing:** Signal Towers do not share the Planetary Shield initialization race. `DataPool.Add()` resets the value-type component, `NewBeaconComponent` synchronously assigns its entity and already-created power-node IDs, and no UI opens from `beacons.count` or reads tick-created resources. Holo Beacons use `MarkerComponent`; `NewMarkerComponent` also initializes and registers their UI-visible state synchronously. - **Illegal Dyson shell generation:** Estimated triangle vertex counts mirror the original `DysonShell.GenerateGeometry` rasterization as closely as possible, but can still differ from the final frame-generated shell polygon at numerical boundaries. Max-output generation must treat `QuickAddDysonShell` failure as a candidate rejection and try the next candidate rather than assuming the estimate is exact. - **Fail-soft patch application:** `PatchImpl.Enable(true)` applies Harmony patches inside a try/catch. Runtime patching can fail through no fault of ours (Harmony re-runs other mods' transpilers on shared target methods), and an escaping exception would abort the calling `ConfigEntry.SettingChanged` delegate chain, desyncing config UI from config values. On failure it logs a `LogError` with the feature type name, rolls back via `UnpatchSelf()`, and leaves `_patch` null so a later `Enable(true)` can retry. -- **Convergent in-game UI state:** In-game overlay widgets whose visibility depends on game state (e.g. `AutoConstructUI`) must not rely solely on one-shot event-driven refreshes (`SettingChanged` handlers, patch `OnEnable`/`OnDisable`), because a thrown exception earlier in a delegate chain or a failed patch application silently drops the refresh. `AutoConstructUI.OnUpdate()` reconciles button visibility and the pending-construction count with actual game state every 30 frames (also effective while paused); the `AutoConstructPatch` postfix on `PlayerAction_Rts.GameTick` only implements the fly-to-target behavior, and `AutoConstructPatch.OnEnable` logs its visibility predicate inputs once per enable as a remote-diagnosis aid. -- **Auto-construct planner:** `AutoConstructPatch` keeps a construction-site plan while drones work, chooses among a fixed candidate set using the native 120-target construction capacity, total drone travel cost, and player travel cost, then refines the strongest candidates to an actual ghost nearest the target-group center. Candidate scoring uses the planned flight altitude when evaluating build-range coverage. It replans before the current site is empty when the remaining local workload no longer covers the next flight. Candidate evaluation has fixed limits and uses allocation-free arrays; local construction checks scan actual hash entries instead of trusting stale module counters and include ghosts whose materials can be delivered from the mecha package. +- **Convergent in-game UI state:** In-game overlay widgets whose visibility depends on game state (e.g. `AutoConstructUI`) must not rely solely on one-shot event-driven refreshes (`SettingChanged` handlers, patch `OnEnable`/`OnDisable`), because a thrown exception earlier in a delegate chain or a failed patch application silently drops the refresh. `AutoConstructUI.OnUpdate()` reconciles button visibility and the pending-construction count with actual game state every 30 frames (also effective while paused); the `AutoConstructPatch` postfix on `PlayerAction_Rts.GameTick` only implements the fly-to-target behavior, and `AutoConstructPatch.OnEnable` logs its visibility predicate inputs as a remote-diagnosis aid, throttled to once per game session unless the button object itself is missing. `MyCheckButton.Checked` only refreshes the button colours: its label lives on `OnChecked` handlers, so any path that sets `Checked` directly (periodic reconcile, shortcut key, `ConfigEntry.SettingChanged`) must refresh the label too. +- **Auto-construct planner:** `AutoConstructPatch` keeps a construction-site plan while drones work, chooses among a fixed candidate set using the native 120-target construction capacity, total drone travel cost, and player travel cost, then refines the strongest candidates to an actual ghost nearest the target-group center. Candidate scoring uses the planned flight altitude when evaluating build-range coverage, so arrival must release any detour altitude (`AvoidanceAltitude`) and restore `ConstructionFlightAltitude`; otherwise the drones cannot reach part of the ghosts the score was based on. The angular fan axes are derived in the planet-local frame (`player.uRotation` is universal and must be inverse-rotated by `planet.runtimeRotation`), because prebuild and player positions are planet-local. It replans before the current site is empty when the remaining local workload no longer covers the next flight. Candidate evaluation has fixed limits and uses allocation-free arrays; local construction checks scan actual hash entries instead of trusting stale module counters and include ghosts whose materials can be delivered from the mecha package. Ghost eligibility mirrors the material-delivery filter in `ConstructionModuleComponent.GameTick` (`ItemProto.constructableIdHash` plus `PlanetFactory.HasEnemyBuildingNear`), because a ghost the game will never deliver items to can never launch a drone and would park the mecha on a site that makes no progress; the enemy-proximity probe is skipped entirely when the planet has no Dark Fog ground bases. +- **Auto-construct flight settling:** `BeginFlightSettling`/`UpdateFlightSettling`/`EndFlightSettling` implement a two-stage wait: a fixed tick countdown that covers the latency between `Player.ClearOrders()` and `PlayerMove_Fly` decaying `rtsVelocity`, followed by a residual-speed check bounded by a timeout. The residual check must be gated on the separate `_flightSettlePending` flag, not on the countdown, or it becomes unreachable the moment the countdown reaches zero. A route deferred by this wait is re-issued with `bypassBrake` so it cannot be deferred again after a timeout and stall the mecha. `Player.Order(OrderNode.Stop, false)` followed by `Player.ClearOrders()` is a no-op that only adds a stray order gizmo at the planet centre: the actual braking comes from `PlayerMove_Fly` decaying `rtsVelocity` whenever there is no unreached order. +- **Auto-construct configuration split:** `FactoryConfigProvider.AutoConstructEnabled` gates the `AutoConstructPatch` Harmony patch; `AutoConstructButtonEnabled` only controls button visibility. Do not tie patch activation to the button config — hiding the button would then silently disable the feature, and the button is the only in-game way to toggle it. - **Auto-construct final pass:** When at most eight eligible construction ghosts remain, the planner bypasses site-hold hysteresis and routes directly to the nearest remaining ghost. The final-pass count is capped at nine during the existing prebuild scan, so large construction queues do not incur an additional unbounded performance cost. - **Auto-construct maintenance:** Planner scan reset, final-pass nearest-ghost routing, and route-arrival/recovery transitions use shared state helpers; no-op UI lifecycle forwarding is removed. -- **Auto-navigation:** UXAssist now exposes one auto-cruise implementation through `PlayerPatch.AutoNavigation`; the former legacy cruise path and algorithm-selection branch are removed. The shared `ToggleAutoCruise` key and in-game button control the session state. The configuration entry is presented as `Enable auto-cruise`, and its navigation options are grouped beneath it as indented 13-point sub-options. Steering follows the original `PlayerMove_Sail.GameTick` interpolation cap of 1.6 degrees per tick for the ordinary sail velocity and explicitly chooses a stable turn plane for antiparallel velocity and target directions. During warp, the added displacement uses `currentWarpVelocity` along mecha heading; after the game's heading update, a postfix tops up the warp heading toward the requested direction so the actual heading reaches the same 1.6-degree-per-tick minimum instead of lagging behind the ordinary velocity vector. Auto-navigation also reduces `warpSpeedControl` toward the game's 0.2 floor as heading error grows; manual warp speed controls take precedence. Target resolution is validated once and applied atomically for both the UI and tick path; moving-target velocity is converted to universal coordinates; direct sail steering only runs while the player is sailing. Target state and reusable obstacle data are reset through one navigation lifecycle path. Satellite targets use a target corridor: an orbiting parent is ignored when the direct player-to-target segment is clear, shrinks its avoidance radius so it cannot contain the target, and otherwise follows a current-heading-selected tangent around the parent before returning to the satellite. -- **Auto-cruise flight input:** In the original `PlayerMove_Fly.GameTick`, `PlayerController.input0.y = 1` matches manual forward movement and `input1.y = 1` matches manual upward thrust. The auto-cruise `Fly` handler must preserve these signs so the mecha leaves a planet with the same orientation and motion as manual control. +- **Auto-cruise:** UXAssist exposes one auto-cruise implementation through `PlayerPatch.AutoNavigation`; the former legacy cruise path and algorithm-selection branch are removed. Its Harmony patches follow `AutoCruiseEnabled`, so a user who disables the feature does not keep a transpiler on the hot `PlayerController.GameTick` installed. The shared `ToggleAutoCruise` key and in-game button control the session state, and starting requires a resolvable target so the feature cannot emit a "started" and a "stopped" popup in the same frame. All user-facing strings say auto-cruise / `自动巡航`; do not reintroduce `自动导航`, which collides with the game's own `PlayerNavigation` autopilot and its `太空导航` indicators. Auto-cruise yields to that autopilot (`player.navigation.navigating`) instead of fighting it over `uVelocity`. The configuration entry is presented as `Enable auto-cruise`, and its navigation options are grouped beneath it as indented 13-point sub-options. Steering follows the original `PlayerMove_Sail.GameTick` interpolation cap of 1.6 degrees per tick for the ordinary sail velocity and explicitly chooses a stable turn plane for antiparallel velocity and target directions. During warp, the added displacement uses `currentWarpVelocity` along mecha heading; after the game's heading update, a postfix tops up the warp heading toward the requested direction so the actual heading reaches the same 1.6-degree-per-tick minimum instead of lagging behind the ordinary velocity vector. Auto-cruise also reduces `warpSpeedControl` toward the game's 0.2 floor as heading error grows; manual warp speed controls take precedence. Target resolution is validated once and applied atomically for both the UI and tick path; moving-target velocity is converted to universal coordinates; direct sail steering only runs while the player is sailing. Target state and reusable obstacle data are reset through one navigation lifecycle path. Satellite targets use a target corridor: an orbiting parent is ignored when the direct player-to-target segment is clear, shrinks its avoidance radius so it cannot contain the target, and otherwise follows a current-heading-selected tangent around the parent before returning to the satellite. `SpaceSector.dfHives` is only allocated by `SetForNewGame` and by `Import` when the save carries hive data, so obstacle collection must null-check it exactly like the game does. +- **Auto-cruise sail reference frame and braking:** `PlayerMove_Sail.GameTick` and `PlayerNavigation.DetermineSailVelocity` blend the planet frame velocity by altitude (`Clamp01((600 - altitude) / 450)`) and it is fully gone above 600 m. `visual_uvel` must use that same blend, because `PlayerController.UpdateRotation` runs after the whole action loop and turns `visual_uvel` into the mecha heading and the speed readout; subtracting the unblended planet velocity visibly misaims the mecha near a planet. For the same reason the mod does not write `uRotation` from the sail postfix — the game recomputes it immediately afterwards. Braking must be applied directly (the original's 0.008-per-tick decay branch), not folded into the turn interpolation, which would weaken it by up to `1/t`. Fixed targets are speed-capped on approach (`GetApproachSpeedLimit`) so the mecha reaches the arrival radius below the 75 m/s planet-relative speed that `PlayerMove_Sail` requires before handing over to `PlayerMove_Fly`, and warp is released early enough for that brake to settle — the game's own warp guard only covers planets, never stars. +- **Auto-cruise flight input:** In the original `PlayerMove_Fly.GameTick`, `PlayerController.input0.y = 1` matches manual forward movement and `input1.y = 1` matches manual upward thrust. In `PlayerMove_Walk`, `input0.z` is the jump axis: the first press jumps and sets `flyUpChance`, the next one calls `SwitchToFly`, so holding it lifts off within two ticks. The auto-cruise handlers must preserve these axes and signs so the mecha leaves a planet with the same orientation and motion as manual control. - **Shortcut input timing:** UXAssist dispatches mod shortcuts from a postfix of the original `VFInput.OnUpdate`, after DSP has refreshed its current modifier and UI input state. Do not move shortcut polling back to an independent plugin `Update()` or a logic-tick callback: CommonAPI `PressKeyBind.keyValue` combines Unity's current-frame `Input.GetKeyDown()` with `CombineKey` modifier caches refreshed by `VFInput.OnUpdate`. Polling before that refresh can miss a shortcut when a modifier changes in the same frame, which is easier to encounter at low frame rates. Keep the typing/menu guards and per-frame registry guards. - **UI clone initialization and text measurement:** UXAssist UI factories and dependent mods' direct UI clones treat runtime DSP objects as style sources only; after `Instantiate`, they explicitly reset stateful `UIButton`, `Text`, `Image`, `InputField`, `Slider`, and `UIComboBox` fields that can otherwise carry source state. Use `UXAssist.UI.Util.GetPreferredWidth` for dynamic text width because it invalidates DSP's custom text-generator cache before reading `preferredWidth`; do not replace it with a generic `TextGenerator` or canvas-wide rebuild without validating the rendered result. - **Transpiler patches:** Performance-critical mods (LabOpt, MechaDronesTweaks) use `[HarmonyTranspiler]` to rewrite IL instructions directly for maximum efficiency. All transpilers in UXAssist, CheatEnabler, and UniverseGenTweaks carry a standard header comment (`// Harmony transpiler:`, `// Target:`, `// Fallback:`) documenting the target method and fallback behavior. `UXAssist.Common.Patching.TranspilerGuard` provides a reusable `CodeMatcher.Finish` helper that returns original instructions when a matcher becomes invalid. diff --git a/UXAssist/Common/I18NKeys.cs b/UXAssist/Common/I18NKeys.cs index cb7dc32..587057c 100644 --- a/UXAssist/Common/I18NKeys.cs +++ b/UXAssist/Common/I18NKeys.cs @@ -154,16 +154,17 @@ public static class I18NKeys public const string ShortcutKeysForShowingStarsName = "Shortcut keys for showing stars' name"; public const string AutoBoost = "Auto boost"; public const string DistanceToUseWarp = "Distance to use warp"; - public const string StopAutoNavigationOnManualInput = "Stop auto-navigation on manual input"; + public const string StopAutoCruiseOnManualInput = "Stop auto-cruise on manual input"; public const string UseWarp = "Use warp"; public const string UseWarpMinimalEnergy = "Use warp minimal energy"; public const string AutoBoostMinimalEnergy = "Auto boost minimal energy"; public const string DarkFogHiveFollowDistance = "Dark Fog Hive follow distance"; public const string DarkFogCarrierFollowDistance = "Dark Fog Carrier follow distance"; - public const string AutoNavigationActive = "Auto-navigation active"; - public const string AutoNavigationEnableHint = "Press {0} to enable auto-navigation"; - public const string AutoNavigationStarted = "Auto-navigation started"; - public const string AutoNavigationStopped = "Auto-navigation stopped"; + public const string AutoCruiseActive = "Auto-cruise active"; + public const string AutoCruiseEnableHint = "Press {0} to enable auto-cruise"; + public const string AutoCruiseStarted = "Auto-cruise started"; + public const string AutoCruiseStopped = "Auto-cruise stopped"; + public const string AutoCruiseNoTarget = "Auto-cruise needs a navigation target"; public const string TreatStackItemsAsSingleInMonitorComponents = "Treat stack items as single in monitor components"; public const string InitializeThisPlanet = "Initialize This Planet"; public const string InitializeThisPlanetConfirm = "Initialize This Planet Confirm"; @@ -418,16 +419,17 @@ You can set 2 shortcut keys in Settings panel: I18N.Add(ShortcutKeysForShowingStarsName, "Shortcut keys for showing stars' name", "启用显示所有星系名称的快捷键"); I18N.Add(AutoBoost, "Auto boost", "自动加速"); I18N.Add(DistanceToUseWarp, "Distance to use warp (AU)", "使用曲速的距离(AU)"); - I18N.Add(StopAutoNavigationOnManualInput, "Stop auto-navigation on manual input", "手动输入时停止自动导航"); + I18N.Add(StopAutoCruiseOnManualInput, "Stop auto-cruise on manual input", "手动输入时停止自动巡航"); I18N.Add(UseWarp, "Use warp", "启用曲速"); I18N.Add(UseWarpMinimalEnergy, "Minimum energy to use warp (MJ)", "使用曲速最低能量(MJ)"); I18N.Add(AutoBoostMinimalEnergy, "Minimum energy for auto boost (MJ)", "自动加速最低能量(MJ)"); I18N.Add(DarkFogHiveFollowDistance, "Dark Fog Hive follow distance (AU)", "黑雾巢穴跟踪距离(AU)"); I18N.Add(DarkFogCarrierFollowDistance, "Dark Fog Carrier follow distance (m)", "黑雾火种跟踪距离(m)"); - I18N.Add(AutoNavigationActive, "Auto-navigation active", "自动导航中"); - I18N.Add(AutoNavigationEnableHint, "Press {0} to enable auto-navigation", "按 {0} 启用自动导航"); - I18N.Add(AutoNavigationStarted, "Auto-navigation started", "自动导航启动"); - I18N.Add(AutoNavigationStopped, "Auto-navigation stopped", "自动导航关闭"); + I18N.Add(AutoCruiseActive, "Auto-cruise active", "自动巡航中"); + I18N.Add(AutoCruiseEnableHint, "Press {0} to enable auto-cruise", "按 {0} 启用自动巡航"); + I18N.Add(AutoCruiseStarted, "Auto-cruise started", "自动巡航启动"); + I18N.Add(AutoCruiseStopped, "Auto-cruise stopped", "自动巡航关闭"); + I18N.Add(AutoCruiseNoTarget, "Auto-cruise needs a navigation target", "自动巡航需要先设置导航目标"); I18N.Add(TreatStackItemsAsSingleInMonitorComponents, "Treat stack items as single in monitor components", "在流速计中将堆叠物品视为单个物品"); I18N.Add(InitializeThisPlanet, "Initialize this planet", "初始化本行星"); I18N.Add(InitializeThisPlanetConfirm, "This operation will destroy all buildings and revert terrains on this planet, are you sure?", "此操作将会摧毁本行星上的所有建筑并恢复地形,确定吗?"); diff --git a/UXAssist/Functions/UI/AutoCruiseUI.cs b/UXAssist/Functions/UI/AutoCruiseUI.cs index 07821d6..e2899a3 100644 --- a/UXAssist/Functions/UI/AutoCruiseUI.cs +++ b/UXAssist/Functions/UI/AutoCruiseUI.cs @@ -29,19 +29,7 @@ internal static class AutoCruiseUI rectTrans.localScale = new Vector3(1f, 1f, 1f); UpdateToggleAutoCruiseCheckButtonVisiblility(); - ToggleAutoCruiseChecked(); - ToggleAutoCruise.OnChecked += ToggleAutoCruiseChecked; - static void ToggleAutoCruiseChecked() - { - if (ToggleAutoCruise.Checked) - { - ToggleAutoCruise.SetLabelText(I18NKeys.DisableAutoCruise); - } - else - { - ToggleAutoCruise.SetLabelText(I18NKeys.EnableAutoCruise); - } - } + ToggleAutoCruise.OnChecked += UpdateToggleAutoCruiseLabel; ToggleAutoCruise.OnChecked += Patches.PlayerPatch.AutoNavigation.Toggle; } @@ -50,7 +38,19 @@ internal static class AutoCruiseUI if (ToggleAutoCruise == null) return; var active = Patches.PlayerPatch.AutoCruiseEnabled.Value && Patches.PlayerPatch.AutoNavigation.HasNavigationTarget(); + // MyCheckButton.Checked only refreshes the colours; the label lives on the OnChecked + // handlers. Auto-cruise can also be toggled by its shortcut or stopped automatically on + // arrival, so the label has to be refreshed here as well or it goes stale. ToggleAutoCruise.Checked = Patches.PlayerPatch.AutoNavigation.IsActive; + UpdateToggleAutoCruiseLabel(); ToggleAutoCruise.gameObject.SetActive(active); } + + private static void UpdateToggleAutoCruiseLabel() + { + if (ToggleAutoCruise == null) return; + ToggleAutoCruise.SetLabelText(ToggleAutoCruise.Checked + ? I18NKeys.DisableAutoCruise + : I18NKeys.EnableAutoCruise); + } } diff --git a/UXAssist/Patches/PlayerPatch.cs b/UXAssist/Patches/PlayerPatch.cs index 165470f..d2cfad6 100644 --- a/UXAssist/Patches/PlayerPatch.cs +++ b/UXAssist/Patches/PlayerPatch.cs @@ -21,15 +21,15 @@ public class PlayerPatch : PatchImpl private static PressKeyBind _toggleAllStarsNameKey; private static PressKeyBind _autoDriveKey; - public static ConfigEntry AutoCruiseEnabled { get; set; } = null!; - public static ConfigEntry StopOnArrivalAndInput { get; set; } = null!; - public static ConfigEntry UseWarper { get; set; } = null!; - public static ConfigEntry UseWarperMinimalEnergy { get; set; } = null!; - public static ConfigEntry UseWarperDistance { get; set; } = null!; - public static ConfigEntry UseSpeedUp { get; set; } = null!; - public static ConfigEntry UseSpeedUpMinimalEnergy { get; set; } = null!; - public static ConfigEntry DFHiveFollowDistance { get; set; } = null!; - public static ConfigEntry DFCarrierFollowDistance { get; set; } = null!; + public static ConfigEntry AutoCruiseEnabled { get; set; } = null!; + public static ConfigEntry StopOnArrivalAndInput { get; set; } = null!; + public static ConfigEntry UseWarper { get; set; } = null!; + public static ConfigEntry UseWarperMinimalEnergy { get; set; } = null!; + public static ConfigEntry UseWarperDistance { get; set; } = null!; + public static ConfigEntry UseSpeedUp { get; set; } = null!; + public static ConfigEntry UseSpeedUpMinimalEnergy { get; set; } = null!; + public static ConfigEntry DFHiveFollowDistance { get; set; } = null!; + public static ConfigEntry DFCarrierFollowDistance { get; set; } = null!; public static void Init() { @@ -41,7 +41,7 @@ public class PlayerPatch : PatchImpl canOverride = true } ); - _toggleAllStarsNameKey = KeyBindings.RegisterKeyBinding(new BuiltinKey + _toggleAllStarsNameKey = KeyBindings.RegisterKeyBinding(new BuiltinKey { key = new CombineKey((int)KeyCode.Tab, 0, ECombineKeyAction.OnceClick, false), conflictGroup = KeyBindConflict.UI | KeyBindConflict.KEYBOARD_KEYBIND, @@ -49,14 +49,14 @@ public class PlayerPatch : PatchImpl canOverride = true } ); - _autoDriveKey = KeyBindings.RegisterKeyBinding(new BuiltinKey + _autoDriveKey = KeyBindings.RegisterKeyBinding(new BuiltinKey { key = new CombineKey((int)KeyCode.K, 0, ECombineKeyAction.OnceClick, true), conflictGroup = KeyBindConflict.MOVEMENT | KeyBindConflict.FLYING | KeyBindConflict.SAILING | KeyBindConflict.BUILD_MODE_1 | KeyBindConflict.KEYBOARD_KEYBIND, name = "ToggleAutoCruise", canOverride = true }); - EnhancedMechaForgeCountControlEnabled.SettingChanged += (_, _) => EnhancedMechaForgeCountControl.Enable(EnhancedMechaForgeCountControlEnabled.Value); + EnhancedMechaForgeCountControlEnabled.SettingChanged += (_, _) => EnhancedMechaForgeCountControl.Enable(EnhancedMechaForgeCountControlEnabled.Value); HideTipsForSandsChangesEnabled.SettingChanged += (_, _) => HideTipsForSandsChanges.Enable(HideTipsForSandsChangesEnabled.Value); ShortcutKeysForStarsNameEnabled.SettingChanged += (_, _) => ShortcutKeysForStarsName.Enable(ShortcutKeysForStarsNameEnabled.Value); AutoNavigation.Init(); @@ -67,7 +67,7 @@ public class PlayerPatch : PatchImpl EnhancedMechaForgeCountControl.Enable(EnhancedMechaForgeCountControlEnabled.Value); HideTipsForSandsChanges.Enable(HideTipsForSandsChangesEnabled.Value); ShortcutKeysForStarsName.Enable(ShortcutKeysForStarsNameEnabled.Value); - AutoNavigation.Enable(true); + AutoNavigation.Enable(AutoCruiseEnabled.Value); Enable(true); } @@ -344,887 +344,962 @@ public class PlayerPatch : PatchImpl } - #region New navigation algorithm - - public class AutoNavigation : PatchImpl - { - private const double Epsilon = 1e-18; - private const int DarkFogAstroIdStart = 1000000; - private const int StarArriveThresholdRadius = 4000; - private const int PlanetArriveThresholdRadius = 100; - private const double StarSafeRedis = 2000; - private const double PlanetSafeRedis = 2000; - private const double HiveSafeRedis = GalaxyData.AU * 0.5; - private const double FollowModeUseWarpDistance = GalaxyData.AU * 1.5; - private const double ResidualCompensationMaxDistance = GalaxyData.AU * 0.5; - private const double ResidualCompensationSpeedRatio = 0.5; - private const double ResidualCompensationMinSpeed = 100; - private const float WarpTurnDegreesPerTick = 1.6f; - - private static bool _enabled; - private static Text _uiTipText; - - private static int _targetId; - private static VectorLF3 _targetUniversePosition; - private static VectorLF3 _targetUniverseVelocity; - private static ESpaceGuideType _targetType; - private static double _targetArriveThresholdRadius; - - private static readonly List Obstacles = new(64); - private static bool _wasSailing; - private static bool _followModeLock; - private static bool _warpSteeringPending; - private static Quaternion _warpHeadingBeforeRotation; - private static VectorLF3 _warpTargetDirection; - - - public static bool IsActive => _enabled; - - protected override void OnEnable( ) - { - StartG( ); - global::UXAssist.Common.GameLogic.OnGameBegin += StartG; - global::UXAssist.Common.GameLogic.OnGameEnd += ResetState; - } - - protected override void OnDisable() - { - global::UXAssist.Common.GameLogic.OnGameBegin -= StartG; - global::UXAssist.Common.GameLogic.OnGameEnd -= ResetState; - ResetState(); - if (_uiTipText != null) - { - Object.Destroy(_uiTipText.gameObject); - _uiTipText = null; - } - } - - public static void Awake(ConfigFile config) - { - AutoCruiseEnabled = config.Bind( - "Player", - "AutoCruise", - true, - "Enable auto-cruise"); - StopOnArrivalAndInput = config.Bind("Player", nameof(StopOnArrivalAndInput), true, "Stop auto-navigation on arrival or manual input"); - UseWarper = config.Bind("Player", nameof(UseWarper), true, "Use warp during auto-navigation"); - UseWarperMinimalEnergy = config.Bind( - "Player", - nameof(UseWarperMinimalEnergy), - 800, - new ConfigDescription("Minimum energy required to use warp (MJ)", new AcceptableValueRange(50, 1000))); - UseWarperDistance = config.Bind("Player", nameof(UseWarperDistance), 2.0, - new ConfigDescription("Minimum distance to use warp (AU)", new AcceptableValueRange(0.5, 20))); - UseSpeedUp = config.Bind("Player", nameof(UseSpeedUp), true, "Use automatic acceleration"); - UseSpeedUpMinimalEnergy = config.Bind( - "Player", - nameof(UseSpeedUpMinimalEnergy), - 100, - new ConfigDescription("Minimum energy required for automatic acceleration (MJ)", new AcceptableValueRange(50, 1000))); - DFHiveFollowDistance = config.Bind( - "Player", - nameof(DFHiveFollowDistance), - 0.5, - new ConfigDescription("Dark Fog Hive follow distance (AU)", new AcceptableValueRange(0.1, 5))); - DFCarrierFollowDistance = config.Bind( - "Player", - nameof(DFCarrierFollowDistance), - 1000, - new ConfigDescription("Dark Fog Carrier follow distance (m)", new AcceptableValueRange(100, 3000))); - } - - public static void Init() - { - AutoCruiseEnabled.SettingChanged += NavigationModeChanged; - } - - public static void StartG( ) - { - if (_uiTipText != null) - { - UpdateUiTip(); - return; - } - if (UIRoot.instance?.uiGame?.generalTips?.modeText == null) - return; - Text originText = UIRoot.instance.uiGame.generalTips.modeText; - _uiTipText = Object.Instantiate(originText, originText.transform.parent); - _uiTipText.gameObject.SetActive(false); - _uiTipText.rectTransform.anchoredPosition = new Vector2(0f, 160f); - _uiTipText.fontStyle = FontStyle.Normal; - UpdateUiTip(); - } - - public static void Toggle() - { - if (!AutoCruiseEnabled.Value) - return; - if (_enabled) - StopAutoNavigation(); - else - StartAutoNavigation( ); - } - - private static void StartAutoNavigation( ) - { - if (DSPGame.IsMenuDemo || ! GameMain.isRunning) - return; - - _enabled = true; - ResetTargetState(); - UIRealtimeTip.Popup(I18NKeys.AutoNavigationStarted.Translate(), sound: false); - UpdateUiTip(); - } - - private static void StopAutoNavigation(bool showTip = true) - { - bool wasEnabled = _enabled; - _enabled = false; - ResetTargetState(); - if (wasEnabled && showTip && !DSPGame.IsMenuDemo && GameMain.isRunning) - UIRealtimeTip.Popup(I18NKeys.AutoNavigationStopped.Translate(), sound: false); - UpdateUiTip(); - } - - private static void ResetTargetState( ) - { - _targetId = 0; - _wasSailing = false; - _followModeLock = false; - _warpSteeringPending = false; - _warpHeadingBeforeRotation = Quaternion.identity; - _warpTargetDirection = default; - _targetUniversePosition = default; - _targetUniverseVelocity = default; - _targetType = default; - _targetArriveThresholdRadius = 0; - Obstacles.Clear(); - } - - private static void ResetState() - { - StopAutoNavigation(false); - } - - private static void NavigationModeChanged(object sender, EventArgs args) - { - if (!AutoCruiseEnabled.Value) - StopAutoNavigation(false); - else - UpdateUiTip(); - global::UXAssist.Functions.UIFunctions.UpdateToggleAutoCruiseCheckButtonVisiblility(); - } - - public static void UpdateUiTip() - { - if (_uiTipText == null) - return; - - bool showTip = GameMain.isRunning && !DSPGame.IsMenuDemo && AutoCruiseEnabled.Value && (_enabled || HasNavigationTarget()); - _uiTipText.gameObject.SetActive(showTip); - if (!showTip) - return; - - _uiTipText.text = _enabled - ? I18NKeys.AutoNavigationActive.Translate() - : string.Format(I18NKeys.AutoNavigationEnableHint.Translate(), KeyBindings.GetKeyBindingText(_autoDriveKey)); - } - - public static bool HasNavigationTarget() - { - Player player = GameMain.mainPlayer; - if (player == null || !TryResolveNavigationTarget(player, out NavigationTarget target)) - return false; - - return target.Type != ESpaceGuideType.Planet || GameMain.localPlanet == null || target.Id != GameMain.localPlanet.astroId; - } - - /// - /// Performs precondition checks and refreshes the current navigation target. - /// - private static bool PreCheckAndRefreshTarget(Player player) - { - if (!AutoCruiseEnabled.Value) - { - StopAutoNavigation( ); - return true; - } - if (!_enabled) - return true; - if (player.mecha.thrusterLevel < 2) - { - StopAutoNavigation( ); - return true; - } - if (VFInput._pullUp.pressing - || VFInput._pushDown.pressing - || VFInput._moveLeft.pressing - || VFInput._moveRight.pressing - || VFInput._moveForward.pressing - || VFInput._moveBackward.pressing) - { - if (StopOnArrivalAndInput.Value) - StopAutoNavigation( ); - return true; - } - - if (!TryResolveNavigationTarget(player, out NavigationTarget target)) - { - StopAutoNavigation(); - return true; - } - - bool targetChanged = _targetId != target.Id || _targetType != target.Type; - _targetId = target.Id; - _targetType = target.Type; - _targetUniversePosition = target.Position; - _targetUniverseVelocity = target.Velocity; - _targetArriveThresholdRadius = target.ArrivalRadius; - if (targetChanged) - { - _followModeLock = false; - } - return false; - } - - private static bool TryResolveNavigationTarget(Player player, out NavigationTarget target) - { - target = default; - PlayerNavigation navigation = player.navigation; - int indicatorAstroId = navigation.indicatorAstroId; - if (indicatorAstroId > DarkFogAstroIdStart) - { - int astroIndex = indicatorAstroId - DarkFogAstroIdStart; - if (astroIndex < 0 || astroIndex >= GameMain.spaceSector.astros.Length) - return false; - - AstroData astro = GameMain.spaceSector.astros[astroIndex]; - VectorLF3 localPosition = default; - astro.VelocityU(ref localPosition, out Vector3 velocity); - target = new NavigationTarget( - indicatorAstroId, - ESpaceGuideType.DFHive, - astro.uPos, - velocity, - DFHiveFollowDistance.Value * GalaxyData.AU); - return true; - } - - if (indicatorAstroId != 0) - { - if (indicatorAstroId < 0 || indicatorAstroId >= GameMain.galaxy.astrosData.Length) - return false; - if (indicatorAstroId % 100 == 0) - { - StarData star = GameMain.galaxy.StarById(indicatorAstroId / 100); - if (star == null) - return false; - target = new NavigationTarget( - indicatorAstroId, - ESpaceGuideType.Star, - star.uPosition, - default, - GameMain.galaxy.astrosData[indicatorAstroId].uRadius + StarArriveThresholdRadius); - } else - { - PlanetData planet = GameMain.galaxy.PlanetById(indicatorAstroId); - if (planet == null) - return false; - target = new NavigationTarget( - indicatorAstroId, - ESpaceGuideType.Planet, - planet.uPosition, - default, - planet.realRadius + PlanetArriveThresholdRadius); - } - return true; - } - - int enemyId = navigation.indicatorEnemyId; - if (enemyId <= 0 || enemyId >= GameMain.data.spaceSector.enemyPool.Length) - return false; - EnemyData enemy = GameMain.data.spaceSector.enemyPool[enemyId]; - if (enemy.id != enemyId) - return false; - - VectorLF3 localPositionForVelocity = enemy.pos; - Vector3 localVelocity = enemy.vel; - GameMain.data.spaceSector.TransformVelocityFromAstro_ref( - enemy.astroId, - out Vector3 enemyVelocity, - ref localPositionForVelocity, - ref localVelocity); - GameMain.data.spaceSector.TransformFromAstro_ref(enemy.astroId, out VectorLF3 position, ref enemy.pos); - target = new NavigationTarget(enemyId, ESpaceGuideType.DFCarrier, position, enemyVelocity, DFCarrierFollowDistance.Value); - return true; - } - - /// - /// Steers toward the target while avoiding nearby obstacles. - /// - private static void SailToTarget(PlayerController controller, double distance) - { - CollectObstacles(); - - Player player = controller.player; - double currentSpeed = player.uVelocity.magnitude; - VectorLF3 preliminaryDir = SafeNorm(_targetUniversePosition - player.uPosition, default); - VectorLF3 currentDir = SafeNorm(player.uVelocity, preliminaryDir); - VectorLF3 targetDir = ComputeDirection(player.uPosition, currentDir, Obstacles); - if (player.warping) - UpdateSailVelocityAndRotation(controller, currentDir, currentSpeed, targetDir, currentSpeed); - else - { - Mecha mecha = player.mecha; - bool canWarp = UseWarper.Value - && mecha.coreEnergy > UseWarperMinimalEnergy.Value * 1000 * 1000 - && mecha.coreEnergy > mecha.warpStartPowerPerSpeed * controller.actionSail.maxWarpSpeed - && player.mecha.thrusterLevel >= 3 - && player.mecha.HasWarper( ) - && GameMain.localPlanet == null - && distance > GalaxyData.AU * UseWarperDistance.Value; - if (canWarp && player.mecha.UseWarper( )) - { - UpdateSailVelocityAndRotation(controller, currentDir, currentSpeed, targetDir, currentSpeed); - player.warpCommand = true; - VFAudio.Create("warp-begin", player.transform, Vector3.zero, true); - } else - UpdateSailVelocityAndRotation(controller, currentDir, currentSpeed, targetDir, mecha.maxSailSpeed); - } - } - - private static void CollectObstacles() - { - Obstacles.Clear(); - StarData localStar = GameMain.localStar; - if (localStar == null) - return; - - if (localStar.astroId != _targetId) - Obstacles.Add(new Obstacle( - localStar.uPosition, - GameMain.galaxy.astrosData[localStar.astroId].uRadius, - StarSafeRedis)); - - foreach (PlanetData planet in localStar.planets) - { - if (planet.astroId != _targetId) - Obstacles.Add(new Obstacle(planet.uPosition, planet.realRadius, PlanetSafeRedis)); - } - - if (_targetType == ESpaceGuideType.DFHive) - return; - - EnemyDFHiveSystem hiveSys = GameMain.spaceSector.dfHives[localStar.index]; - while (hiveSys != null) - { - if (hiveSys is { realized: true, hiveAstroId: > DarkFogAstroIdStart } - && hiveSys.hiveAstroId != _targetId) - { - Obstacles.Add(new Obstacle( - GameMain.spaceSector.astros[hiveSys.hiveAstroId - DarkFogAstroIdStart].uPos, - 0, - HiveSafeRedis)); - } - hiveSys = hiveSys.nextSibling; - } - } - - /// - /// Computes a target direction with obstacle avoidance. - /// - /// Player position. - /// Nearby obstacles. - /// - private static VectorLF3 ComputeDirection(VectorLF3 playerPos, VectorLF3 currentDirection, List obstacles) - { - VectorLF3 toTarget = _targetUniversePosition - playerPos; - double toTargetSqr = toTarget.sqrMagnitude; - if (toTargetSqr < Epsilon) - return default; - - VectorLF3 baseDir = toTarget.normalized; - foreach (Obstacle obstacle in obstacles) - { - double pathRadius = GetReachablePathRadius(obstacle); - if (pathRadius <= 0.0) - continue; - - VectorLF3 toObstacle = obstacle.Position - playerPos; - double obstacleDistance = toObstacle.magnitude; - if (obstacleDistance < pathRadius) - return ComputeEscapeDirection(currentDirection, toObstacle, baseDir); - if (IsSegmentBlocked(playerPos, _targetUniversePosition, obstacle.Position, pathRadius)) - return ComputeTangentDirection(currentDirection, toObstacle, pathRadius, baseDir); - } - - return baseDir; - } - - private static double GetReachablePathRadius(Obstacle obstacle) - { - double targetClearance = (obstacle.Position - _targetUniversePosition).magnitude - _targetArriveThresholdRadius; - return Math.Min(obstacle.PathRadius, targetClearance); - } - - private static bool IsSegmentBlocked( - VectorLF3 start, - VectorLF3 end, - VectorLF3 center, - double pathRadius) - { - VectorLF3 segment = end - start; - double segmentLength = segment.magnitude; - if (segmentLength < Epsilon) - return false; - - VectorLF3 toCenter = center - start; - double projection = VectorLF3.Dot(toCenter, segment) / segmentLength; - double closestDistance = projection <= 0.0 - ? toCenter.magnitude - : projection >= segmentLength - ? (center - end).magnitude - : Math.Sqrt(Math.Max(0.0, toCenter.sqrMagnitude - projection * projection)); - return closestDistance < pathRadius; - } - - private static VectorLF3 ComputeEscapeDirection(VectorLF3 currentDirection, VectorLF3 toObstacle, VectorLF3 fallback) - { - VectorLF3 outward = SafeNorm(-toObstacle, -fallback); - VectorLF3 tangent = currentDirection - outward * VectorLF3.Dot(currentDirection, outward); - tangent = SafeNorm(tangent, GetPerpendicularDirection(outward, VectorLF3.unit_y)); - return SafeNorm(outward + tangent * 0.5, outward); - } - - private static VectorLF3 ComputeTangentDirection( - VectorLF3 currentDirection, - VectorLF3 toObstacle, - double pathRadius, - VectorLF3 fallback) - { - double obstacleDistance = toObstacle.magnitude; - if (obstacleDistance < Epsilon) - return ComputeEscapeDirection(currentDirection, toObstacle, fallback); - - VectorLF3 radial = toObstacle / obstacleDistance; - double cosAngle = Clamp(pathRadius / obstacleDistance, 0.0, 1.0); - double sinAngle = Math.Sqrt(Math.Max(0.0, 1.0 - cosAngle * cosAngle)); - VectorLF3 side = currentDirection - radial * VectorLF3.Dot(currentDirection, radial); - if (side.sqrMagnitude < Epsilon) - side = _targetUniverseVelocity - radial * VectorLF3.Dot(_targetUniverseVelocity, radial); - if (side.sqrMagnitude < Epsilon) - side = fallback - radial * VectorLF3.Dot(fallback, radial); - if (side.sqrMagnitude < Epsilon) - side = GetPerpendicularDirection(radial, VectorLF3.unit_y); - - return SafeNorm(radial * cosAngle + side.normalized * sinAngle, fallback); - } - - /// - /// Steers toward and follows a moving target without avoidance after close-range lock. - /// Distance to the target. - /// - private static void FollowMovingTarget(PlayerController controller, double distance) - { - double arriveRadius = _targetArriveThresholdRadius; - double exitLockRadius = arriveRadius * 1.05; - double axialTolerance = arriveRadius * 0.8; - double lateralTolerance = arriveRadius * 0.8; - double axialSlowDownDistance = arriveRadius * 10; - double lateralSlowDownDistance = arriveRadius * 5; - - Player player = controller.player; - double mechaMaxSailSpeed = player.mecha.maxSailSpeed; - VectorLF3 playerPos = player.uPosition; - VectorLF3 playerVelocity = player.uVelocity; - double playerSpeed = playerVelocity.magnitude; - VectorLF3 targetPos = _targetUniversePosition; - VectorLF3 targetVelocity = _targetUniverseVelocity; - VectorLF3 toTarget = targetPos - playerPos; - if (distance < Epsilon) - return; - VectorLF3 toTargetDir = toTarget / distance; - VectorLF3 targetVelocityDir = SafeNorm(targetVelocity, toTargetDir); - - if (distance > FollowModeUseWarpDistance) - { - SailToTarget(controller, distance); - return; - } - if (player.warping) - { - player.warpCommand = false; - return; - } - if (distance > exitLockRadius) - _followModeLock = false; - else if (distance <= arriveRadius) - _followModeLock = true; - - // Match the target velocity after entering the follow sphere. - if (_followModeLock) - { - UpdateSailVelocityAndRotation( - controller: controller, - currentDir: SafeNorm(playerVelocity, targetVelocityDir), - currentSpeed: playerSpeed, - targetDir: targetVelocityDir, - targetSpeed: targetVelocity.magnitude); - return; - } - - // Resolve the position error into axial and lateral components. - double axialError = VectorLF3.Dot(toTarget, targetVelocityDir); - VectorLF3 lateralVector = toTarget - targetVelocityDir * axialError; - double lateralError = lateralVector.magnitude; - VectorLF3 lateralDir = lateralError > Epsilon ? lateralVector / lateralError : default; - - // Axial approach. - double axialEffectiveError = Math.Max(Math.Abs(axialError) - axialTolerance, 0.0); - double axialApproachSpeed = mechaMaxSailSpeed * axialEffectiveError / (axialEffectiveError + axialSlowDownDistance); - VectorLF3 axialDir = axialError >= 0 ? targetVelocityDir : - targetVelocityDir; - - // Lateral approach. - double lateralEffectiveError = Math.Max(lateralError - lateralTolerance, 0.0); - double lateralApproachSpeed = - mechaMaxSailSpeed * lateralEffectiveError / (lateralEffectiveError + lateralSlowDownDistance); - - VectorLF3 relativeVelocityDesired = axialDir * axialApproachSpeed + lateralDir * lateralApproachSpeed; - - // Residual velocity compensation. - if (distance > arriveRadius) - { - double cWeight = (distance - arriveRadius) / ResidualCompensationMaxDistance; - cWeight = Clamp(cWeight, 0, 1); - cWeight = cWeight * cWeight * (3.0 - 2.0 * cWeight); - double cSpeed = player.mecha.maxSailSpeed * cWeight * ResidualCompensationSpeedRatio - + ResidualCompensationMinSpeed; - double dot = VectorLF3.Dot(relativeVelocityDesired, toTargetDir); - if (dot < cSpeed) - relativeVelocityDesired += toTargetDir * cSpeed; - } - - // Combine target and approach velocities. - VectorLF3 desiredVelocity = targetVelocity + relativeVelocityDesired; - double desiredSpeed = Math.Min(desiredVelocity.magnitude, mechaMaxSailSpeed); - VectorLF3 desiredDirection = SafeNorm(desiredVelocity, toTargetDir); - VectorLF3 playerDir = SafeNorm(playerVelocity, desiredDirection); - UpdateSailVelocityAndRotation( - controller: controller, - currentDir: playerDir, - currentSpeed: playerSpeed, - targetDir: desiredDirection, - targetSpeed: desiredSpeed); - } - - private static VectorLF3 SafeNorm(VectorLF3 vector, VectorLF3 fallback) => - vector.sqrMagnitude < Epsilon ? fallback : vector.normalized; - - private static VectorLF3 GetPerpendicularDirection(VectorLF3 direction, VectorLF3 reference) - { - VectorLF3 perpendicular = reference - direction * VectorLF3.Dot(reference, direction); - if (perpendicular.sqrMagnitude < Epsilon) - perpendicular = VectorLF3.Cross(direction, VectorLF3.unit_x); - if (perpendicular.sqrMagnitude < Epsilon) - perpendicular = VectorLF3.Cross(direction, VectorLF3.unit_z); - return perpendicular.sqrMagnitude < Epsilon ? VectorLF3.unit_y : perpendicular.normalized; - } - - /// - /// Updates sail acceleration, steering, rotation, and visual velocity. - /// - private static void UpdateSailVelocityAndRotation( - PlayerController controller, - VectorLF3 currentDir, - double currentSpeed, - VectorLF3 targetDir, - double targetSpeed) - { - PlayerMove_Sail sail = controller.actionSail; - Player player = controller.player; - Mecha mecha = player.mecha; - VectorLF3 currentVel = currentDir * currentSpeed; - double desiredSpeed = Math.Min(targetSpeed, mecha.maxSailSpeed); - double stepSpeed = currentSpeed; - - // Acceleration and braking. - bool speedUp = UseSpeedUp.Value && mecha.coreEnergy > UseSpeedUpMinimalEnergy.Value * 1000 * 1000; - if (speedUp && desiredSpeed > currentSpeed) - { - double dSpeed = Clamp(currentSpeed * 0.02, 7.0, sail.max_acc); - dSpeed = Math.Min(dSpeed, desiredSpeed - currentSpeed); - dSpeed = Math.Min(dSpeed, mecha.maxSailSpeed - currentSpeed); - if (dSpeed > 0) - stepSpeed = currentSpeed + dSpeed * sail.UseSailEnergy(dSpeed); - } else if (desiredSpeed < currentSpeed) - { - VectorLF3 dVelocityBrake = currentVel * 0.008; - sail.UseSailEnergy(ref dVelocityBrake, 1.5); - stepSpeed = Math.Max(0, (currentVel - dVelocityBrake).magnitude); - } - - _warpSteeringPending = player.warping && targetDir.sqrMagnitude > Epsilon; - _warpHeadingBeforeRotation = player.uRotation; - _warpTargetDirection = _warpSteeringPending ? targetDir : default; - - AdaptWarpSpeedControl(controller, targetDir); - - // Smooth velocity changes. - VectorLF3 targetVelocity = targetDir * stepSpeed; - float angle = Vector3.Angle(targetVelocity, currentVel); - var t = 1.6f / Mathf.Max(10f, angle); - VectorLF3 smoothedVelocity = SmoothVelocity(currentVel, targetVelocity, t, sail.sailPoser.targetURot * Vector3.up); - VectorLF3 dVelocity = smoothedVelocity - currentVel; - sail.UseSailEnergy(ref dVelocity, 0.36); - VectorLF3 newVelocity = currentVel + dVelocity; - - sail.input_aff_1 = 1.0; - player.uVelocity = newVelocity; - UpdateRotation(controller: controller); - } - - [HarmonyPatch(typeof(PlayerController), "UpdateRotation")] - [HarmonyPostfix] - private static void PlayerController_UpdateRotation_Postfix(PlayerController __instance) - { - if (!_enabled || !_warpSteeringPending) - return; - - _warpSteeringPending = false; - Player player = __instance.player; - if (player == null || __instance.movementStateInFrame != EMovementState.Sail || !player.warping) - return; - - Vector3 previousDirection = _warpHeadingBeforeRotation * Vector3.forward; - Vector3 currentDirection = player.uRotation * Vector3.forward; - Vector3 targetDirection = (Vector3)_warpTargetDirection; - float appliedAngle = Vector3.Angle(previousDirection, currentDirection); - float targetAngle = Vector3.Angle(currentDirection, targetDirection); - float remainingAngle = Mathf.Min(targetAngle, Mathf.Max(0f, WarpTurnDegreesPerTick - appliedAngle)); - if (remainingAngle < 0.01f) - return; - - Vector3 turnAxis = GetStableTurnAxis(currentDirection, targetDirection); - player.uRotation = Quaternion.AngleAxis(remainingAngle, turnAxis) * player.uRotation; - } - - private static void AdaptWarpSpeedControl(PlayerController controller, VectorLF3 targetDir) - { - Player player = controller.player; - if (!player.warping || VFInput._sailSpeedUp || controller.input0.y < 0f) - return; - - Vector3 warpDirection = player.uRotation * Vector3.forward; - float turnAngle = Vector3.Angle(warpDirection, targetDir); - double turnSeverity = Clamp((turnAngle - 15.0) / 45.0, 0.0, 1.0); - double targetControl = 1.0 - turnSeverity * turnSeverity * (3.0 - 2.0 * turnSeverity) * 0.8; - double controlDelta = Clamp( - targetControl - controller.actionSail.warpSpeedControl, - -0.02, - 0.02); - controller.actionSail.warpSpeedControl = Clamp( - controller.actionSail.warpSpeedControl + controlDelta, - 0.2, - 1.0); - } - - private static VectorLF3 SmoothVelocity( - VectorLF3 currentVelocity, - VectorLF3 targetVelocity, - float interpolation, - VectorLF3 turnReference) - { - double currentMagnitude = currentVelocity.magnitude; - double targetMagnitude = targetVelocity.magnitude; - if (currentMagnitude < Epsilon && targetMagnitude < Epsilon) - return VectorLF3.zero; - - Vector3 currentDirection = currentMagnitude >= Epsilon - ? (Vector3)(currentVelocity / currentMagnitude) - : (targetMagnitude >= Epsilon ? (Vector3)(targetVelocity / targetMagnitude) : Vector3.forward); - Vector3 targetDirection = targetMagnitude >= Epsilon - ? (Vector3)(targetVelocity / targetMagnitude) - : currentDirection; - Vector3 direction; - if (Vector3.Dot(currentDirection, targetDirection) < -0.9999f) - { - float angle = Vector3.Angle(currentDirection, targetDirection); - Vector3 axis = GetStableTurnAxis(currentDirection, (Vector3)turnReference); - direction = Quaternion.AngleAxis(angle * interpolation, axis) * currentDirection; - } - else - { - direction = Vector3.Slerp(currentDirection, targetDirection, interpolation); - } - - double magnitude = currentMagnitude + (targetMagnitude - currentMagnitude) * interpolation; - return (VectorLF3)(direction.normalized * (float)magnitude); - } - - private static Vector3 GetStableTurnAxis(Vector3 direction, Vector3 reference) - { - Vector3 projectedReference = reference - direction * Vector3.Dot(reference, direction); - if (projectedReference.sqrMagnitude < 1e-10f) - { - projectedReference = Vector3.Cross(direction, Vector3.right); - if (projectedReference.sqrMagnitude < 1e-10f) - projectedReference = Vector3.Cross(direction, Vector3.up); - } - return Vector3.Cross(direction, projectedReference).normalized; - } - - /// - /// Updates player orientation. - /// - private static void UpdateRotation(PlayerController controller) - { - Player player = controller.player; - PlayerMove_Sail sail = controller.actionSail; - VectorLF3 newVelocity = player.uVelocity; - // Use the camera up vector to stabilize orientation. - if (newVelocity.magnitude > Epsilon) - { - VectorLF3 forward = newVelocity.normalized; - Vector3 cameraUp = controller.actionSail.sailPoser.targetURot * Vector3.up; - VectorLF3 cameraUpWorld = cameraUp; - double dot = VectorLF3.Dot(cameraUpWorld, forward); - VectorLF3 projectedUp = cameraUpWorld - forward * dot; - Vector3 newUp; - if (projectedUp.sqrMagnitude < Epsilon) - { - Vector3 cameraRight = controller.actionSail.sailPoser.targetURot * Vector3.right; - newUp = Vector3.Cross(cameraRight, forward); - if (newUp.sqrMagnitude < Epsilon) - newUp = Vector3.up; - else - newUp.Normalize( ); - } else - newUp = ((Vector3)projectedUp).normalized; - Quaternion targetRot = Quaternion.LookRotation(forward, newUp); - float rotAngle = Quaternion.Angle(player.uRotation, targetRot); - float rotT = Mathf.Min(0.15f, 10f / Mathf.Max(10f, rotAngle)); - player.uRotation = Quaternion.Slerp(player.uRotation, targetRot, rotT); - } - // Keep visual velocity consistent with universal velocity. - PlanetData localPlanet = GameMain.localPlanet; - if (localPlanet != null) - { - VectorLF3 planetVel = localPlanet.GetUniversalVelocityAtLocalPoint(GameMain.gameTime, player.position); - sail.visual_uvel = newVelocity - planetVel; - } else - sail.visual_uvel = newVelocity; - } - - private static double Clamp(double value, double min, double max) => value < min ? min : value > max ? max : value; - - // Harmony transpiler: PlayerController_GameTick_Transpiler - // Target: PlayerController.GameTick - // Fallback: Return the original instructions if the insertion point cannot be found. - [HarmonyTranspiler] - [HarmonyPatch(typeof(PlayerController), nameof(PlayerController.GameTick))] - private static IEnumerable PlayerController_GameTick_Transpiler( - IEnumerable instructions, - ILGenerator generator) - { - var original = new List(instructions); - var matcher = new CodeMatcher(original, generator); - matcher.MatchForward( - false, - new CodeMatch( - OpCodes.Callvirt, - AccessTools.Method(typeof(BuildModel), nameof(BuildModel.EarlyGameTickIgnoreActive))) - ).Advance(1).InsertAndAdvance( - new CodeInstruction(OpCodes.Ldarg_0), - Transpilers.EmitDelegate((PlayerController controller) => - { - EMovementState movementState = controller.movementStateInFrame; - if (movementState is not (EMovementState.Walk or EMovementState.Drift or EMovementState.Fly)) - return; - if (PreCheckAndRefreshTarget(controller.player) || DetermineTargetLocal( )) - return; - if (movementState == EMovementState.Fly) - { - controller.input1.y = 1f; - controller.input0.y = 1f; - } - else - controller.input0.z = 1f; - }) - ); - return matcher.Finish(original, UXAssist.Logger, nameof(PlayerController_GameTick_Transpiler)); - - // Detect arrival while walking or flying. - static bool DetermineTargetLocal( ) - { - if (_targetId != 0 && (_targetType != ESpaceGuideType.Planet || GameMain.localPlanet?.astroId != _targetId)) - return false; - StopAutoNavigation( ); - return true; - } - } - - [HarmonyPatch(typeof(PlayerMove_Sail), nameof(PlayerMove_Sail.GameTick)), HarmonyPostfix] - // ReSharper disable once InconsistentNaming - private static void PlayerMoveSailPostfix(PlayerMove_Sail __instance) - { - PlayerController controller = __instance.controller; - Player player = __instance.player; - if (PreCheckAndRefreshTarget(player)) - return; - bool isSailing = controller.movementStateInFrame == EMovementState.Sail; - bool enteredSailing = isSailing && !_wasSailing; - _wasSailing = isSailing; - if (!isSailing) - return; - VectorLF3 playerPos = player.uPosition; - VectorLF3 targetVector = _targetUniversePosition - playerPos; - double distance = targetVector.magnitude; - if (enteredSailing && targetVector.sqrMagnitude >= Epsilon) - __instance.sailPoser.targetURotWanted = Quaternion.LookRotation(targetVector); - - // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault - switch (_targetType) - { - case ESpaceGuideType.Star: - case ESpaceGuideType.Planet: - // Stop after reaching a fixed target. - if (distance < _targetArriveThresholdRadius) - { - if (player.warping) - player.warpCommand = false; - StopAutoNavigation( ); - return; - } - SailToTarget(controller, distance); - break; - case ESpaceGuideType.DFHive: - case ESpaceGuideType.DFCarrier: - FollowMovingTarget(controller, distance); - break; - } - } - } - - private readonly struct NavigationTarget( - int id, - ESpaceGuideType type, - VectorLF3 position, - VectorLF3 velocity, - double arrivalRadius) - { - public int Id { get; } = id; - public ESpaceGuideType Type { get; } = type; - public VectorLF3 Position { get; } = position; - public VectorLF3 Velocity { get; } = velocity; - public double ArrivalRadius { get; } = arrivalRadius; - } - - private readonly struct Obstacle(VectorLF3 position, double radius, double safetyMargin) - { - public VectorLF3 Position { get; } = position; - public double Radius { get; } = radius; - public double PathRadius { get; } = radius + safetyMargin; - } - - #endregion + #region Auto-cruise navigation + + public class AutoNavigation : PatchImpl + { + private const double Epsilon = 1e-12; + private const int DarkFogAstroIdStart = 1000000; + private const int StarArriveThresholdRadius = 4000; + private const int PlanetArriveThresholdRadius = 100; + private const double StarSafeRadius = 2000; + private const double PlanetSafeRadius = 2000; + private const double HiveSafeRadius = GalaxyData.AU * 0.5; + private const double FollowModeUseWarpDistance = GalaxyData.AU * 1.5; + private const double ResidualCompensationMaxDistance = GalaxyData.AU * 0.5; + private const double ResidualCompensationSpeedRatio = 0.5; + private const double ResidualCompensationMinSpeed = 100; + private const float WarpTurnDegreesPerTick = 1.6f; + + // Reference-frame blending, mirroring PlayerMove_Sail.GameTick: the planet frame velocity + // fades out between 150 m and 600 m of altitude and is fully gone above that. + private const double ReferenceFrameFadeAltitude = 600.0; + private const double ReferenceFrameFadeRange = 450.0; + + // Approach braking. PlayerMove_Sail decelerates by 0.8% of the current velocity per tick, so + // slowing from v to a standstill covers v / (0.008 * 60) = 2.08 * v metres. The constant below + // carries a safety margin on top of that so the brake starts early enough. + private const double SailBrakeRatePerTick = 0.008; + private const double SailBrakeSecondsPerSpeed = 2.6; + // PlayerMove_Sail only hands over to PlayerMove_Fly below 75 m/s of planet-relative speed, so + // a planet approach has to end well under that or the mecha can never land. + private const double PlanetApproachArrivalSpeed = 60.0; + private const double StarApproachArrivalSpeed = 300.0; + + private static bool _enabled; + private static Text _uiTipText; + + private static int _targetId; + private static VectorLF3 _targetUniversePosition; + private static VectorLF3 _targetUniverseVelocity; + private static ESpaceGuideType _targetType; + private static double _targetArriveThresholdRadius; + + private static readonly List Obstacles = new(64); + private static bool _wasSailing; + private static bool _followModeLock; + private static bool _warpSteeringPending; + private static Quaternion _warpHeadingBeforeRotation; + private static VectorLF3 _warpTargetDirection; + + + public static bool IsActive => _enabled; + + protected override void OnEnable() + { + EnsureUiTip(); + global::UXAssist.Common.GameLogic.OnGameBegin += EnsureUiTip; + global::UXAssist.Common.GameLogic.OnGameEnd += ResetState; + } + + protected override void OnDisable() + { + global::UXAssist.Common.GameLogic.OnGameBegin -= EnsureUiTip; + global::UXAssist.Common.GameLogic.OnGameEnd -= ResetState; + ResetState(); + if (_uiTipText != null) + { + Object.Destroy(_uiTipText.gameObject); + _uiTipText = null; + } + } + + public static void Awake(ConfigFile config) + { + AutoCruiseEnabled = config.Bind( + "Player", + "AutoCruise", + true, + "Enable auto-cruise"); + StopOnArrivalAndInput = config.Bind("Player", nameof(StopOnArrivalAndInput), true, "Stop auto-cruise on arrival or manual input"); + UseWarper = config.Bind("Player", nameof(UseWarper), true, "Use warp during auto-cruise"); + UseWarperMinimalEnergy = config.Bind( + "Player", + nameof(UseWarperMinimalEnergy), + 800, + new ConfigDescription("Minimum energy required to use warp (MJ)", new AcceptableValueRange(50, 1000))); + UseWarperDistance = config.Bind("Player", nameof(UseWarperDistance), 2.0, + new ConfigDescription("Minimum distance to use warp (AU)", new AcceptableValueRange(0.5, 20))); + UseSpeedUp = config.Bind("Player", nameof(UseSpeedUp), true, "Use automatic acceleration during auto-cruise"); + UseSpeedUpMinimalEnergy = config.Bind( + "Player", + nameof(UseSpeedUpMinimalEnergy), + 100, + new ConfigDescription("Minimum energy required for automatic acceleration (MJ)", new AcceptableValueRange(50, 1000))); + DFHiveFollowDistance = config.Bind( + "Player", + nameof(DFHiveFollowDistance), + 0.5, + new ConfigDescription("Dark Fog Hive follow distance (AU)", new AcceptableValueRange(0.1, 5))); + DFCarrierFollowDistance = config.Bind( + "Player", + nameof(DFCarrierFollowDistance), + 1000, + new ConfigDescription("Dark Fog Carrier follow distance (m)", new AcceptableValueRange(100, 3000))); + } + + public static void Init() + { + AutoCruiseEnabled.SettingChanged += NavigationModeChanged; + } + + public static void EnsureUiTip() + { + if (_uiTipText != null) + { + UpdateUiTip(); + return; + } + if (UIRoot.instance?.uiGame?.generalTips?.modeText == null) + return; + Text originText = UIRoot.instance.uiGame.generalTips.modeText; + _uiTipText = Object.Instantiate(originText, originText.transform.parent); + _uiTipText.gameObject.SetActive(false); + _uiTipText.rectTransform.anchoredPosition = new Vector2(0f, 160f); + _uiTipText.fontStyle = FontStyle.Normal; + UpdateUiTip(); + } + + public static void Toggle() + { + if (!AutoCruiseEnabled.Value) + return; + if (_enabled) + StopAutoNavigation(); + else + StartAutoNavigation(); + } + + private static void StartAutoNavigation() + { + if (DSPGame.IsMenuDemo || !GameMain.isRunning) + return; + // Without this check the next tick would immediately fail to resolve a target and stop + // again, producing a "started" and a "stopped" popup back to back. + if (!HasNavigationTarget()) + { + UIRealtimeTip.Popup(I18NKeys.AutoCruiseNoTarget.Translate(), sound: false); + return; + } + + _enabled = true; + ResetTargetState(); + UIRealtimeTip.Popup(I18NKeys.AutoCruiseStarted.Translate(), sound: false); + UpdateUiTip(); + } + + private static void StopAutoNavigation(bool showTip = true) + { + bool wasEnabled = _enabled; + _enabled = false; + ResetTargetState(); + if (wasEnabled && showTip && !DSPGame.IsMenuDemo && GameMain.isRunning) + UIRealtimeTip.Popup(I18NKeys.AutoCruiseStopped.Translate(), sound: false); + UpdateUiTip(); + } + + private static void ResetTargetState() + { + _targetId = 0; + _wasSailing = false; + _followModeLock = false; + _warpSteeringPending = false; + _warpHeadingBeforeRotation = Quaternion.identity; + _warpTargetDirection = default; + _targetUniversePosition = default; + _targetUniverseVelocity = default; + _targetType = default; + _targetArriveThresholdRadius = 0; + Obstacles.Clear(); + } + + private static void ResetState() + { + StopAutoNavigation(false); + } + + private static void NavigationModeChanged(object sender, EventArgs args) + { + if (!AutoCruiseEnabled.Value) + StopAutoNavigation(false); + // Follow the config with the Harmony patches themselves, so a user who turns auto-cruise off + // does not keep a transpiler on PlayerController.GameTick and two postfixes installed. + Enable(AutoCruiseEnabled.Value); + if (AutoCruiseEnabled.Value) + UpdateUiTip(); + global::UXAssist.Functions.UIFunctions.UpdateToggleAutoCruiseCheckButtonVisiblility(); + } + + public static void UpdateUiTip() + { + if (_uiTipText == null) + return; + + bool showTip = GameMain.isRunning && !DSPGame.IsMenuDemo && AutoCruiseEnabled.Value && (_enabled || HasNavigationTarget()); + _uiTipText.gameObject.SetActive(showTip); + if (!showTip) + return; + + _uiTipText.text = _enabled + ? I18NKeys.AutoCruiseActive.Translate() + : string.Format(I18NKeys.AutoCruiseEnableHint.Translate(), KeyBindings.GetKeyBindingText(_autoDriveKey)); + } + + public static bool HasNavigationTarget() + { + Player player = GameMain.mainPlayer; + if (player == null || !TryResolveNavigationTarget(player, out NavigationTarget target)) + return false; + + return target.Type != ESpaceGuideType.Planet || GameMain.localPlanet == null || target.Id != GameMain.localPlanet.astroId; + } + + /// + /// Performs precondition checks and refreshes the current navigation target. + /// + /// True when auto-cruise may drive the mecha this tick. + private static bool TryRefreshNavigationTarget(Player player) + { + if (!AutoCruiseEnabled.Value) + { + StopAutoNavigation(); + return false; + } + if (!_enabled) + return false; + if (player.mecha.thrusterLevel < 2) + { + StopAutoNavigation(); + return false; + } + // The game's own autopilot zeroes the movement input inside PlayerMove_Sail/PlayerMove_Fly + // and drives uVelocity itself. Yield to it instead of fighting over the same state, the same + // way AutoConstructPatch does. + if (player.navigation.navigating) + { + StopAutoNavigation(); + return false; + } + if (global::UXAssist.Common.Utils.PlayerInputUtil.HasManualMovementInput()) + { + if (StopOnArrivalAndInput.Value) + StopAutoNavigation(); + return false; + } + + if (!TryResolveNavigationTarget(player, out NavigationTarget target)) + { + StopAutoNavigation(); + return false; + } + + bool targetChanged = _targetId != target.Id || _targetType != target.Type; + _targetId = target.Id; + _targetType = target.Type; + _targetUniversePosition = target.Position; + _targetUniverseVelocity = target.Velocity; + _targetArriveThresholdRadius = target.ArrivalRadius; + if (targetChanged) + { + _followModeLock = false; + } + return true; + } + + private static bool TryResolveNavigationTarget(Player player, out NavigationTarget target) + { + target = default; + PlayerNavigation navigation = player.navigation; + int indicatorAstroId = navigation.indicatorAstroId; + if (indicatorAstroId > DarkFogAstroIdStart) + { + int astroIndex = indicatorAstroId - DarkFogAstroIdStart; + if (astroIndex < 0 || astroIndex >= GameMain.spaceSector.astros.Length) + return false; + + AstroData astro = GameMain.spaceSector.astros[astroIndex]; + VectorLF3 localPosition = default; + astro.VelocityU(ref localPosition, out Vector3 velocity); + target = new NavigationTarget( + indicatorAstroId, + ESpaceGuideType.DFHive, + astro.uPos, + velocity, + DFHiveFollowDistance.Value * GalaxyData.AU); + return true; + } + + if (indicatorAstroId != 0) + { + if (indicatorAstroId < 0 || indicatorAstroId >= GameMain.galaxy.astrosData.Length) + return false; + if (indicatorAstroId % 100 == 0) + { + StarData star = GameMain.galaxy.StarById(indicatorAstroId / 100); + if (star == null) + return false; + target = new NavigationTarget( + indicatorAstroId, + ESpaceGuideType.Star, + star.uPosition, + default, + GameMain.galaxy.astrosData[indicatorAstroId].uRadius + StarArriveThresholdRadius); + } else + { + PlanetData planet = GameMain.galaxy.PlanetById(indicatorAstroId); + if (planet == null) + return false; + target = new NavigationTarget( + indicatorAstroId, + ESpaceGuideType.Planet, + planet.uPosition, + default, + planet.realRadius + PlanetArriveThresholdRadius); + } + return true; + } + + int enemyId = navigation.indicatorEnemyId; + if (enemyId <= 0 || enemyId >= GameMain.data.spaceSector.enemyPool.Length) + return false; + EnemyData enemy = GameMain.data.spaceSector.enemyPool[enemyId]; + if (enemy.id != enemyId) + return false; + + VectorLF3 localPositionForVelocity = enemy.pos; + Vector3 localVelocity = enemy.vel; + GameMain.data.spaceSector.TransformVelocityFromAstro_ref( + enemy.astroId, + out Vector3 enemyVelocity, + ref localPositionForVelocity, + ref localVelocity); + GameMain.data.spaceSector.TransformFromAstro_ref(enemy.astroId, out VectorLF3 position, ref enemy.pos); + target = new NavigationTarget(enemyId, ESpaceGuideType.DFCarrier, position, enemyVelocity, DFCarrierFollowDistance.Value); + return true; + } + + /// + /// Steers toward the target while avoiding nearby obstacles. + /// + private static void SailToTarget(PlayerController controller, double distance) + { + CollectObstacles(); + + Player player = controller.player; + double currentSpeed = player.uVelocity.magnitude; + VectorLF3 preliminaryDir = SafeNorm(_targetUniversePosition - player.uPosition, default); + VectorLF3 currentDir = SafeNorm(player.uVelocity, preliminaryDir); + VectorLF3 targetDir = ComputeDirection(player.uPosition, currentDir, Obstacles); + if (player.warping) + { + // Leave warp early enough that the ordinary sail brake can still settle the mecha before + // the arrival radius. Mirrors the 0.1 s look-ahead PlayerMove_Sail uses for its own + // planet warp guard, which does not cover star targets at all. + PlayerMove_Sail sail = controller.actionSail; + double warpExitDistance = _targetArriveThresholdRadius + + sail.currentWarpSpeed * 0.1 + + player.mecha.maxSailSpeed * SailBrakeSecondsPerSpeed; + if (distance <= warpExitDistance) + player.warpCommand = false; + UpdateSailVelocity(controller, currentDir, currentSpeed, targetDir, currentSpeed); + return; + } + + Mecha mecha = player.mecha; + bool canWarp = UseWarper.Value + && mecha.coreEnergy > UseWarperMinimalEnergy.Value * 1000 * 1000 + && mecha.coreEnergy > mecha.warpStartPowerPerSpeed * controller.actionSail.maxWarpSpeed + && player.mecha.thrusterLevel >= 3 + && player.mecha.HasWarper() + && GameMain.localPlanet == null + && distance > GalaxyData.AU * UseWarperDistance.Value; + if (canWarp && player.mecha.UseWarper()) + { + UpdateSailVelocity(controller, currentDir, currentSpeed, targetDir, currentSpeed); + player.warpCommand = true; + VFAudio.Create("warp-begin", player.transform, Vector3.zero, true); + return; + } + + UpdateSailVelocity(controller, currentDir, currentSpeed, targetDir, GetApproachSpeedLimit(mecha, distance)); + } + + /// + /// Caps the cruise speed so the sail brake can still bring the mecha down to a usable arrival + /// speed by the time it reaches the arrival radius of a fixed target. + /// + private static double GetApproachSpeedLimit(Mecha mecha, double distance) + { + double arrivalSpeed = _targetType == ESpaceGuideType.Planet + ? PlanetApproachArrivalSpeed + : StarApproachArrivalSpeed; + double remaining = distance - _targetArriveThresholdRadius; + if (remaining <= 0.0) + return arrivalSpeed; + return Math.Min(mecha.maxSailSpeed, arrivalSpeed + remaining / SailBrakeSecondsPerSpeed); + } + + /// + /// Planet frame velocity blended by altitude, matching PlayerMove_Sail.GameTick and + /// PlayerNavigation.DetermineSailVelocity. Subtracting the unblended planet velocity + /// would corrupt visual_uvel, which the game turns into the mecha's heading and the + /// speed readout. + /// + private static VectorLF3 GetReferenceFrameVelocity(Player player) + { + PlanetData localPlanet = GameMain.localPlanet; + if (localPlanet == null) + return default; + + double altitude = (player.uPosition - localPlanet.uPosition).magnitude - localPlanet.realRadius; + double weight = Clamp((ReferenceFrameFadeAltitude - altitude) / ReferenceFrameFadeRange, 0.0, 1.0); + if (weight <= 0.0) + return default; + + return localPlanet.GetUniversalVelocityAtLocalPoint(GameMain.gameTime, player.position) * weight; + } + + private static void CollectObstacles() + { + Obstacles.Clear(); + StarData localStar = GameMain.localStar; + if (localStar == null) + return; + + if (localStar.astroId != _targetId) + Obstacles.Add(new Obstacle( + localStar.uPosition, + GameMain.galaxy.astrosData[localStar.astroId].uRadius, + StarSafeRadius)); + + foreach (PlanetData planet in localStar.planets) + { + if (planet.astroId != _targetId) + Obstacles.Add(new Obstacle(planet.uPosition, planet.realRadius, PlanetSafeRadius)); + } + + if (_targetType == ESpaceGuideType.DFHive) + return; + + // SpaceSector.Init does not allocate dfHives; only SetForNewGame does, and Import only does + // so when the save actually carries hive data. The game null-checks it everywhere for that + // reason, and this runs on every sailing tick. + SpaceSector sector = GameMain.spaceSector; + EnemyDFHiveSystem[] hives = sector.dfHives; + if (hives == null || localStar.index < 0 || localStar.index >= hives.Length) + return; + + AstroData[] astros = sector.astros; + for (EnemyDFHiveSystem hiveSys = hives[localStar.index]; hiveSys != null; hiveSys = hiveSys.nextSibling) + { + if (hiveSys is not { realized: true, hiveAstroId: > DarkFogAstroIdStart } + || hiveSys.hiveAstroId == _targetId) + continue; + + int astroIndex = hiveSys.hiveAstroId - DarkFogAstroIdStart; + if (astros == null || astroIndex >= astros.Length) + continue; + + Obstacles.Add(new Obstacle(astros[astroIndex].uPos, 0, HiveSafeRadius)); + } + } + + /// + /// Computes a target direction with obstacle avoidance. + /// + /// Player position. + /// Nearby obstacles. + /// + private static VectorLF3 ComputeDirection(VectorLF3 playerPos, VectorLF3 currentDirection, List obstacles) + { + VectorLF3 toTarget = _targetUniversePosition - playerPos; + double toTargetSqr = toTarget.sqrMagnitude; + if (toTargetSqr < Epsilon) + return default; + + VectorLF3 baseDir = toTarget.normalized; + foreach (Obstacle obstacle in obstacles) + { + double pathRadius = GetReachablePathRadius(obstacle); + if (pathRadius <= 0.0) + continue; + + VectorLF3 toObstacle = obstacle.Position - playerPos; + double obstacleDistance = toObstacle.magnitude; + if (obstacleDistance < pathRadius) + return ComputeEscapeDirection(currentDirection, toObstacle, baseDir); + if (IsSegmentBlocked(playerPos, _targetUniversePosition, obstacle.Position, pathRadius)) + return ComputeTangentDirection(currentDirection, toObstacle, pathRadius, baseDir); + } + + return baseDir; + } + + private static double GetReachablePathRadius(Obstacle obstacle) + { + double targetClearance = (obstacle.Position - _targetUniversePosition).magnitude - _targetArriveThresholdRadius; + return Math.Min(obstacle.PathRadius, targetClearance); + } + + private static bool IsSegmentBlocked( + VectorLF3 start, + VectorLF3 end, + VectorLF3 center, + double pathRadius) + { + VectorLF3 segment = end - start; + double segmentLength = segment.magnitude; + if (segmentLength < Epsilon) + return false; + + VectorLF3 toCenter = center - start; + double projection = VectorLF3.Dot(toCenter, segment) / segmentLength; + double closestDistance = projection <= 0.0 + ? toCenter.magnitude + : projection >= segmentLength + ? (center - end).magnitude + : Math.Sqrt(Math.Max(0.0, toCenter.sqrMagnitude - projection * projection)); + return closestDistance < pathRadius; + } + + private static VectorLF3 ComputeEscapeDirection(VectorLF3 currentDirection, VectorLF3 toObstacle, VectorLF3 fallback) + { + VectorLF3 outward = SafeNorm(-toObstacle, -fallback); + VectorLF3 tangent = currentDirection - outward * VectorLF3.Dot(currentDirection, outward); + tangent = SafeNorm(tangent, GetPerpendicularDirection(outward, VectorLF3.unit_y)); + return SafeNorm(outward + tangent * 0.5, outward); + } + + private static VectorLF3 ComputeTangentDirection( + VectorLF3 currentDirection, + VectorLF3 toObstacle, + double pathRadius, + VectorLF3 fallback) + { + double obstacleDistance = toObstacle.magnitude; + if (obstacleDistance < Epsilon) + return ComputeEscapeDirection(currentDirection, toObstacle, fallback); + + VectorLF3 radial = toObstacle / obstacleDistance; + double cosAngle = Clamp(pathRadius / obstacleDistance, 0.0, 1.0); + double sinAngle = Math.Sqrt(Math.Max(0.0, 1.0 - cosAngle * cosAngle)); + VectorLF3 side = currentDirection - radial * VectorLF3.Dot(currentDirection, radial); + if (side.sqrMagnitude < Epsilon) + side = _targetUniverseVelocity - radial * VectorLF3.Dot(_targetUniverseVelocity, radial); + if (side.sqrMagnitude < Epsilon) + side = fallback - radial * VectorLF3.Dot(fallback, radial); + if (side.sqrMagnitude < Epsilon) + side = GetPerpendicularDirection(radial, VectorLF3.unit_y); + + return SafeNorm(radial * cosAngle + side.normalized * sinAngle, fallback); + } + + /// + /// Steers toward and follows a moving target without avoidance after close-range lock. + /// Distance to the target. + /// + private static void FollowMovingTarget(PlayerController controller, double distance) + { + double arriveRadius = _targetArriveThresholdRadius; + double exitLockRadius = arriveRadius * 1.05; + double axialTolerance = arriveRadius * 0.8; + double lateralTolerance = arriveRadius * 0.8; + double axialSlowDownDistance = arriveRadius * 10; + double lateralSlowDownDistance = arriveRadius * 5; + + Player player = controller.player; + double mechaMaxSailSpeed = player.mecha.maxSailSpeed; + VectorLF3 playerPos = player.uPosition; + VectorLF3 playerVelocity = player.uVelocity; + double playerSpeed = playerVelocity.magnitude; + VectorLF3 targetPos = _targetUniversePosition; + VectorLF3 targetVelocity = _targetUniverseVelocity; + VectorLF3 toTarget = targetPos - playerPos; + if (distance < Epsilon) + return; + VectorLF3 toTargetDir = toTarget / distance; + VectorLF3 targetVelocityDir = SafeNorm(targetVelocity, toTargetDir); + + if (distance > FollowModeUseWarpDistance) + { + SailToTarget(controller, distance); + return; + } + if (player.warping) + { + player.warpCommand = false; + return; + } + if (distance > exitLockRadius) + _followModeLock = false; + else if (distance <= arriveRadius) + _followModeLock = true; + + // Match the target velocity after entering the follow sphere. + if (_followModeLock) + { + UpdateSailVelocity( + controller: controller, + currentDir: SafeNorm(playerVelocity, targetVelocityDir), + currentSpeed: playerSpeed, + targetDir: targetVelocityDir, + targetSpeed: targetVelocity.magnitude); + return; + } + + // Resolve the position error into axial and lateral components. + double axialError = VectorLF3.Dot(toTarget, targetVelocityDir); + VectorLF3 lateralVector = toTarget - targetVelocityDir * axialError; + double lateralError = lateralVector.magnitude; + VectorLF3 lateralDir = lateralError > Epsilon ? lateralVector / lateralError : default; + + // Axial approach. + double axialEffectiveError = Math.Max(Math.Abs(axialError) - axialTolerance, 0.0); + double axialApproachSpeed = mechaMaxSailSpeed * axialEffectiveError / (axialEffectiveError + axialSlowDownDistance); + VectorLF3 axialDir = axialError >= 0 ? targetVelocityDir : - targetVelocityDir; + + // Lateral approach. + double lateralEffectiveError = Math.Max(lateralError - lateralTolerance, 0.0); + double lateralApproachSpeed = + mechaMaxSailSpeed * lateralEffectiveError / (lateralEffectiveError + lateralSlowDownDistance); + + VectorLF3 relativeVelocityDesired = axialDir * axialApproachSpeed + lateralDir * lateralApproachSpeed; + + // Residual velocity compensation. + if (distance > arriveRadius) + { + double cWeight = (distance - arriveRadius) / ResidualCompensationMaxDistance; + cWeight = Clamp(cWeight, 0, 1); + cWeight = cWeight * cWeight * (3.0 - 2.0 * cWeight); + double cSpeed = player.mecha.maxSailSpeed * cWeight * ResidualCompensationSpeedRatio + + ResidualCompensationMinSpeed; + double dot = VectorLF3.Dot(relativeVelocityDesired, toTargetDir); + if (dot < cSpeed) + relativeVelocityDesired += toTargetDir * cSpeed; + } + + // Combine target and approach velocities. + VectorLF3 desiredVelocity = targetVelocity + relativeVelocityDesired; + double desiredSpeed = Math.Min(desiredVelocity.magnitude, mechaMaxSailSpeed); + VectorLF3 desiredDirection = SafeNorm(desiredVelocity, toTargetDir); + VectorLF3 playerDir = SafeNorm(playerVelocity, desiredDirection); + UpdateSailVelocity( + controller: controller, + currentDir: playerDir, + currentSpeed: playerSpeed, + targetDir: desiredDirection, + targetSpeed: desiredSpeed); + } + + private static VectorLF3 SafeNorm(VectorLF3 vector, VectorLF3 fallback) => + vector.sqrMagnitude < Epsilon ? fallback : vector.normalized; + + private static VectorLF3 GetPerpendicularDirection(VectorLF3 direction, VectorLF3 reference) + { + VectorLF3 perpendicular = reference - direction * VectorLF3.Dot(reference, direction); + if (perpendicular.sqrMagnitude < Epsilon) + perpendicular = VectorLF3.Cross(direction, VectorLF3.unit_x); + if (perpendicular.sqrMagnitude < Epsilon) + perpendicular = VectorLF3.Cross(direction, VectorLF3.unit_z); + return perpendicular.sqrMagnitude < Epsilon ? VectorLF3.unit_y : perpendicular.normalized; + } + + /// + /// Updates sail acceleration, braking, steering and the visual velocity the game derives the + /// mecha heading from. + /// + private static void UpdateSailVelocity( + PlayerController controller, + VectorLF3 currentDir, + double currentSpeed, + VectorLF3 targetDir, + double targetSpeed) + { + PlayerMove_Sail sail = controller.actionSail; + Player player = controller.player; + Mecha mecha = player.mecha; + VectorLF3 currentVel = currentDir * currentSpeed; + double desiredSpeed = Math.Min(targetSpeed, mecha.maxSailSpeed); + double stepSpeed = currentSpeed; + bool brake = desiredSpeed < currentSpeed && !player.warping; + + // Acceleration mirrors PlayerMove_Sail.GameTick: the step is folded into the interpolated + // target velocity below, so the turn interpolation damps it exactly like the original does. + bool speedUp = UseSpeedUp.Value && mecha.coreEnergy > UseSpeedUpMinimalEnergy.Value * 1000 * 1000; + if (speedUp && desiredSpeed > currentSpeed) + { + double dSpeed = Clamp(currentSpeed * 0.02, 7.0, sail.max_acc); + dSpeed = Math.Min(dSpeed, desiredSpeed - currentSpeed); + dSpeed = Math.Min(dSpeed, mecha.maxSailSpeed - currentSpeed); + if (dSpeed > 0) + stepSpeed = currentSpeed + dSpeed * sail.UseSailEnergy(dSpeed); + } + + _warpSteeringPending = player.warping && targetDir.sqrMagnitude > Epsilon; + _warpHeadingBeforeRotation = player.uRotation; + _warpTargetDirection = _warpSteeringPending ? targetDir : default; + + AdaptWarpSpeedControl(controller, targetDir); + + // Smooth velocity changes. + VectorLF3 targetVelocity = targetDir * stepSpeed; + float angle = Vector3.Angle(targetVelocity, currentVel); + var t = 1.6f / Mathf.Max(10f, angle); + VectorLF3 smoothedVelocity = SmoothVelocity(currentVel, targetVelocity, t, sail.sailPoser.targetURot * Vector3.up); + VectorLF3 dVelocity = smoothedVelocity - currentVel; + sail.UseSailEnergy(ref dVelocity, 0.36); + VectorLF3 newVelocity = currentVel + dVelocity; + + // Braking mirrors PlayerMove_Sail.GameTick's dedicated deceleration branch, which applies the + // full per-tick decay directly. Folding it into the turn interpolation instead would weaken + // the brake by a factor of up to 1/t (roughly 6x while flying straight at the target), which + // is far too weak to settle below the 75 m/s the game requires before it hands over to + // PlayerMove_Fly. + if (brake) + { + VectorLF3 brakeVelocity = newVelocity * SailBrakeRatePerTick; + sail.UseSailEnergy(ref brakeVelocity, 1.5); + VectorLF3 brakedVelocity = newVelocity - brakeVelocity; + newVelocity = brakedVelocity.magnitude < desiredSpeed + ? SafeNorm(brakedVelocity, targetDir) * desiredSpeed + : brakedVelocity; + } + + sail.input_aff_1 = 1.0; + player.uVelocity = newVelocity; + UpdateSailVisualVelocity(player, sail, newVelocity); + } + + [HarmonyPatch(typeof(PlayerController), "UpdateRotation")] + [HarmonyPostfix] + private static void PlayerController_UpdateRotation_Postfix(PlayerController __instance) + { + if (!_enabled || !_warpSteeringPending) + return; + + _warpSteeringPending = false; + Player player = __instance.player; + if (player == null || __instance.movementStateInFrame != EMovementState.Sail || !player.warping) + return; + + Vector3 previousDirection = _warpHeadingBeforeRotation * Vector3.forward; + Vector3 currentDirection = player.uRotation * Vector3.forward; + Vector3 targetDirection = (Vector3)_warpTargetDirection; + float appliedAngle = Vector3.Angle(previousDirection, currentDirection); + float targetAngle = Vector3.Angle(currentDirection, targetDirection); + float remainingAngle = Mathf.Min(targetAngle, Mathf.Max(0f, WarpTurnDegreesPerTick - appliedAngle)); + if (remainingAngle < 0.01f) + return; + + Vector3 turnAxis = GetStableTurnAxis(currentDirection, targetDirection); + player.uRotation = Quaternion.AngleAxis(remainingAngle, turnAxis) * player.uRotation; + } + + private static void AdaptWarpSpeedControl(PlayerController controller, VectorLF3 targetDir) + { + Player player = controller.player; + if (!player.warping || VFInput._sailSpeedUp || controller.input0.y < 0f) + return; + + Vector3 warpDirection = player.uRotation * Vector3.forward; + float turnAngle = Vector3.Angle(warpDirection, targetDir); + double turnSeverity = Clamp((turnAngle - 15.0) / 45.0, 0.0, 1.0); + double targetControl = 1.0 - turnSeverity * turnSeverity * (3.0 - 2.0 * turnSeverity) * 0.8; + double controlDelta = Clamp( + targetControl - controller.actionSail.warpSpeedControl, + -0.02, + 0.02); + controller.actionSail.warpSpeedControl = Clamp( + controller.actionSail.warpSpeedControl + controlDelta, + 0.2, + 1.0); + } + + private static VectorLF3 SmoothVelocity( + VectorLF3 currentVelocity, + VectorLF3 targetVelocity, + float interpolation, + VectorLF3 turnReference) + { + double currentMagnitude = currentVelocity.magnitude; + double targetMagnitude = targetVelocity.magnitude; + if (currentMagnitude < Epsilon && targetMagnitude < Epsilon) + return VectorLF3.zero; + + Vector3 currentDirection = currentMagnitude >= Epsilon + ? (Vector3)(currentVelocity / currentMagnitude) + : (targetMagnitude >= Epsilon ? (Vector3)(targetVelocity / targetMagnitude) : Vector3.forward); + Vector3 targetDirection = targetMagnitude >= Epsilon + ? (Vector3)(targetVelocity / targetMagnitude) + : currentDirection; + Vector3 direction; + if (Vector3.Dot(currentDirection, targetDirection) < -0.9999f) + { + float angle = Vector3.Angle(currentDirection, targetDirection); + Vector3 axis = GetStableTurnAxis(currentDirection, (Vector3)turnReference); + direction = Quaternion.AngleAxis(angle * interpolation, axis) * currentDirection; + } + else + { + direction = Vector3.Slerp(currentDirection, targetDirection, interpolation); + } + + double magnitude = currentMagnitude + (targetMagnitude - currentMagnitude) * interpolation; + return (VectorLF3)(direction.normalized * (float)magnitude); + } + + private static Vector3 GetStableTurnAxis(Vector3 direction, Vector3 reference) + { + Vector3 projectedReference = reference - direction * Vector3.Dot(reference, direction); + if (projectedReference.sqrMagnitude < 1e-10f) + { + projectedReference = Vector3.Cross(direction, Vector3.right); + if (projectedReference.sqrMagnitude < 1e-10f) + projectedReference = Vector3.Cross(direction, Vector3.up); + } + return Vector3.Cross(direction, projectedReference).normalized; + } + + /// + /// Keeps PlayerMove_Sail.visual_uvel consistent with the universal velocity we just + /// wrote. + /// + /// + /// This intentionally does not touch player.uRotation. The game's own + /// PlayerController.UpdateRotation runs later in the same tick, after the whole action + /// loop, and recomputes the sailing rotation from visual_uvel anyway, so any rotation + /// written here would simply be overwritten. The warp heading, which the game does not steer + /// fast enough on its own, is topped up afterwards in + /// . + /// + private static void UpdateSailVisualVelocity(Player player, PlayerMove_Sail sail, VectorLF3 newVelocity) + { + sail.visual_uvel = newVelocity - GetReferenceFrameVelocity(player); + } + + private static double Clamp(double value, double min, double max) => value < min ? min : value > max ? max : value; + + // Harmony transpiler: PlayerController_GameTick_Transpiler + // Target: PlayerController.GameTick + // Fallback: Return the original instructions if the insertion point cannot be found. + [HarmonyTranspiler] + [HarmonyPatch(typeof(PlayerController), nameof(PlayerController.GameTick))] + private static IEnumerable PlayerController_GameTick_Transpiler( + IEnumerable instructions, + ILGenerator generator) + { + var original = new List(instructions); + var matcher = new CodeMatcher(original, generator); + matcher.MatchForward( + false, + new CodeMatch( + OpCodes.Callvirt, + AccessTools.Method(typeof(BuildModel), nameof(BuildModel.EarlyGameTickIgnoreActive))) + ).Advance(1).InsertAndAdvance( + new CodeInstruction(OpCodes.Ldarg_0), + Transpilers.EmitDelegate((PlayerController controller) => + { + EMovementState movementState = controller.movementStateInFrame; + if (movementState is not (EMovementState.Walk or EMovementState.Drift or EMovementState.Fly)) + return; + if (!TryRefreshNavigationTarget(controller.player) || HasArrivedLocally()) + return; + if (movementState == EMovementState.Fly) + { + // PlayerController.GetInput maps input0.y to forward movement and input1.y to the + // vertical thruster, so this is exactly manual "hold forward and climb". + controller.input1.y = 1f; + controller.input0.y = 1f; + } + else + // input0.z is the jump axis. PlayerMove_Walk turns the first press into a jump and + // the next one into SwitchToFly, so holding it lifts off within two ticks. + controller.input0.z = 1f; + }) + ); + return matcher.Finish(original, UXAssist.Logger, nameof(PlayerController_GameTick_Transpiler)); + + // Detect arrival while walking or flying. + static bool HasArrivedLocally() + { + if (_targetId != 0 && (_targetType != ESpaceGuideType.Planet || GameMain.localPlanet?.astroId != _targetId)) + return false; + StopAutoNavigation(); + return true; + } + } + + [HarmonyPatch(typeof(PlayerMove_Sail), nameof(PlayerMove_Sail.GameTick)), HarmonyPostfix] + // ReSharper disable once InconsistentNaming + private static void PlayerMoveSailPostfix(PlayerMove_Sail __instance) + { + PlayerController controller = __instance.controller; + Player player = __instance.player; + if (!TryRefreshNavigationTarget(player)) + return; + bool isSailing = controller.movementStateInFrame == EMovementState.Sail; + bool enteredSailing = isSailing && !_wasSailing; + _wasSailing = isSailing; + if (!isSailing) + return; + VectorLF3 playerPos = player.uPosition; + VectorLF3 targetVector = _targetUniversePosition - playerPos; + double distance = targetVector.magnitude; + if (enteredSailing && targetVector.sqrMagnitude >= Epsilon) + __instance.sailPoser.targetURotWanted = Quaternion.LookRotation(targetVector); + + // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault + switch (_targetType) + { + case ESpaceGuideType.Star: + case ESpaceGuideType.Planet: + // Stop after reaching a fixed target. + if (distance < _targetArriveThresholdRadius) + { + if (player.warping) + player.warpCommand = false; + StopAutoNavigation(); + return; + } + SailToTarget(controller, distance); + break; + case ESpaceGuideType.DFHive: + case ESpaceGuideType.DFCarrier: + FollowMovingTarget(controller, distance); + break; + } + } + } + + private readonly struct NavigationTarget( + int id, + ESpaceGuideType type, + VectorLF3 position, + VectorLF3 velocity, + double arrivalRadius) + { + public int Id { get; } = id; + public ESpaceGuideType Type { get; } = type; + public VectorLF3 Position { get; } = position; + public VectorLF3 Velocity { get; } = velocity; + public double ArrivalRadius { get; } = arrivalRadius; + } + + private readonly struct Obstacle(VectorLF3 position, double radius, double safetyMargin) + { + public VectorLF3 Position { get; } = position; + public double PathRadius { get; } = radius + safetyMargin; + } + + #endregion } diff --git a/UXAssist/UIConfigWindow.cs b/UXAssist/UIConfigWindow.cs index d23eb42..f07896f 100644 --- a/UXAssist/UIConfigWindow.cs +++ b/UXAssist/UIConfigWindow.cs @@ -700,7 +700,7 @@ public static class UIConfigWindow y += 36f; var autoCruiseCheckBox = wnd.AddCheckBox(x, y, tab4, PlayerPatch.AutoCruiseEnabled, I18NKeys.EnableAutoCruise); y += 27f; - var autoStopCheckBox = wnd.AddCheckBox(x + 20f, y, tab4, PlayerPatch.StopOnArrivalAndInput, I18NKeys.StopAutoNavigationOnManualInput, 13); + var autoStopCheckBox = wnd.AddCheckBox(x + 20f, y, tab4, PlayerPatch.StopOnArrivalAndInput, I18NKeys.StopAutoCruiseOnManualInput, 13); y += 27f; var useWarpCheckBox = wnd.AddCheckBox(x + 20f, y, tab4, PlayerPatch.UseWarper, I18NKeys.UseWarp, 13); y += 27f;