mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
fix(cheatenabler): make tech downgrades safe and refresh docs
Validate the full dependency cascade and capacity reductions before applying tech downgrades. Preserve shared recipes, restore native bonus values and station limits, and clamp stored energy to the remaining capacity. Fix warning integration and tech-tree help button ownership, cleanup and localization. Use the shared patch lifecycle and guarded transpilers. Refresh bilingual feature and usage documentation, and consolidate the 2.4.7 changelog around the final user-visible behavior.
This commit is contained in:
1 parent
99bcf7fa5f
commit
5fb8695348
13 files changed
+555
-813
No files matched your search
@@ -20,7 +20,8 @@ internal static class DowngradeMode
|
||||
/// <summary>Per-frame <c>Caps Lock</c> poll; driven by the mod feature registry input hook.</summary>
|
||||
public static void Update()
|
||||
{
|
||||
if (TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value)
|
||||
if (TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value ||
|
||||
TechTweaksPatch.Impl.GetHarmony() == null || DSPGame.IsMenuDemo || !GameMain.isRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -45,6 +46,8 @@ internal static class DowngradeMode
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
if (!IsOn) return;
|
||||
IsOn = false;
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,7 @@ using System;
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point injected into <c>UITechNode.OnPointerDown</c>. Decides between "do nothing", "hand over
|
||||
/// to the built-in UnlockTech feature", "upgrade" and "downgrade".
|
||||
/// Entry point injected into UITechNode.OnPointerDown, shared by upgrade and downgrade clicks.
|
||||
/// </summary>
|
||||
internal static class TechClickHandler
|
||||
{
|
||||
|
||||
@@ -1,320 +1,176 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Downgrade side - decrease a tech by clicking it with a key-modifier held while downgrade mode is on.
|
||||
///
|
||||
/// The recursion is the mirror image of <see cref="TechUnlock"/>: the unlock walks into the *pre*-techs
|
||||
/// so the tech tree is never left with a gap, the downgrade walks into the *post*-techs so it is never
|
||||
/// left with "prerequisite locked, dependent unlocked".
|
||||
///
|
||||
/// Downgrading is limited to levels the tech actually has applied, never goes below zero and does
|
||||
/// nothing at all for a tech that is not unlocked yet.
|
||||
/// Plans the complete dependency cascade before changing tech states or live game objects.
|
||||
/// A dependent loses all applied levels when its prerequisite can no longer be researched.
|
||||
/// </summary>
|
||||
internal static class TechDowngrade
|
||||
{
|
||||
private static readonly HashSet<int> Visited = new HashSet<int>();
|
||||
|
||||
private static readonly HashSet<int> DirtyFuncs = new HashSet<int>();
|
||||
|
||||
/// <summary>techId -> new curLevel, for every tech touched by the current click.</summary>
|
||||
private static readonly Dictionary<int, int> Touched = new Dictionary<int, int>();
|
||||
internal const int DeliveryPackageRecipeId = 122;
|
||||
|
||||
// Values are the last applied levels after this click, rather than the next research levels.
|
||||
private static readonly Dictionary<int, int> Targets = new();
|
||||
private static readonly HashSet<int> DirtyFuncs = new();
|
||||
private static readonly HashSet<int> Recipes = new();
|
||||
private static bool _inserterDirty;
|
||||
|
||||
public static void Run(GameHistoryData history, TechProto techProto, int steps)
|
||||
{
|
||||
if (history?.techStates == null || techProto == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(techProto.ID, out TechState state))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int lastApplied = GetLastAppliedLevel(state);
|
||||
if (lastApplied < techProto.Level)
|
||||
{
|
||||
// Nothing applied yet: clicking a tech that is not unlocked does nothing.
|
||||
return;
|
||||
}
|
||||
if (!TryGetLastAppliedLevel(history, techProto, out int lastApplied) || steps <= 0) return;
|
||||
|
||||
int target = steps == TechKeyCombo.LevelToMax
|
||||
? techProto.Level - 1
|
||||
: lastApplied - steps;
|
||||
if (target < techProto.Level)
|
||||
{
|
||||
target = techProto.Level - 1;
|
||||
}
|
||||
|
||||
if (target >= lastApplied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Visited.Clear();
|
||||
: System.Math.Max(techProto.Level - 1, lastApplied - steps);
|
||||
Targets.Clear();
|
||||
DirtyFuncs.Clear();
|
||||
Touched.Clear();
|
||||
Recipes.Clear();
|
||||
_inserterDirty = false;
|
||||
Plan(history, techProto, target);
|
||||
|
||||
DowngradeTo(history, techProto, lastApplied, target);
|
||||
if (!TechFuncRevert.CanRevert(history, Targets)) return;
|
||||
|
||||
int localStorageBefore = history.localStationExtraStorage;
|
||||
int remoteStorageBefore = history.remoteStationExtraStorage;
|
||||
foreach (var pair in Targets)
|
||||
{
|
||||
Apply(history, LDB.techs.Select(pair.Key), pair.Value);
|
||||
}
|
||||
|
||||
// All states must be final before checking shared recipes or recomputing function values.
|
||||
foreach (int recipeId in Recipes)
|
||||
{
|
||||
if (IsRecipeGranted(history, recipeId)) continue;
|
||||
history.recipeUnlocked.Remove(recipeId);
|
||||
if (recipeId == DeliveryPackageRecipeId)
|
||||
{
|
||||
GameMain.mainPlayer.deliveryPackage.unlocked = false;
|
||||
GameMain.mainPlayer.deliveryPackage.NotifySizeChange();
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int func in DirtyFuncs)
|
||||
{
|
||||
try
|
||||
{
|
||||
TechFuncRevert.Recompute(history, func);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
TechLog.Warn($"recomputing tech function {func} failed: {e}");
|
||||
}
|
||||
// Both functions share one package layout and must only resize it once.
|
||||
if (func == 38 && DirtyFuncs.Contains(5)) continue;
|
||||
TechFuncRevert.Recompute(history, func);
|
||||
}
|
||||
|
||||
if (_inserterDirty && history.gameData != null)
|
||||
{
|
||||
history.gameData.OnInserterTechChange();
|
||||
}
|
||||
TechFuncRevert.ReconcileStationStorage(history, localStorageBefore, remoteStorageBefore);
|
||||
if (_inserterDirty) history.gameData.OnInserterTechChange();
|
||||
|
||||
TechUnlock.FinishClick(history);
|
||||
|
||||
RefreshOpenWindow();
|
||||
}
|
||||
|
||||
internal static void MarkDirty(int func) => DirtyFuncs.Add(func);
|
||||
|
||||
internal static void MarkInserterDirty() => _inserterDirty = true;
|
||||
|
||||
/// <summary>
|
||||
/// <c>curLevel</c> means "levels completed plus one" while the tech is being researched, but
|
||||
/// "the max level" once it is unlocked. This helper hides that difference and returns the index of
|
||||
/// the highest level whose <c>UnlockTechFunction</c> calls have already been applied.
|
||||
/// </summary>
|
||||
/// <summary>Completed techs store the last applied level; other techs store the next level.</summary>
|
||||
internal static int GetLastAppliedLevel(TechState state) => state.unlocked ? state.curLevel : state.curLevel - 1;
|
||||
|
||||
internal static bool TryGetLastAppliedLevel(GameHistoryData history, TechProto proto, out int lastApplied)
|
||||
{
|
||||
lastApplied = 0;
|
||||
if (history?.techStates == null || proto == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(proto.ID, out TechState state))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (history?.techStates == null || proto == null ||
|
||||
!history.techStates.TryGetValue(proto.ID, out TechState state)) return false;
|
||||
|
||||
lastApplied = GetLastAppliedLevel(state);
|
||||
return lastApplied >= proto.Level;
|
||||
}
|
||||
|
||||
internal static bool HasAnyAppliedLevel(GameHistoryData history, TechProto proto) =>
|
||||
TryGetLastAppliedLevel(history, proto, out int _);
|
||||
TryGetLastAppliedLevel(history, proto, out _);
|
||||
|
||||
private static void DowngradeTo(GameHistoryData history, TechProto proto, int lastApplied, int target)
|
||||
private static void Plan(GameHistoryData history, TechProto proto, int target)
|
||||
{
|
||||
if (!Visited.Add(proto.ID))
|
||||
if (Targets.ContainsKey(proto.ID) || !history.techStates.TryGetValue(proto.ID, out TechState state)) return;
|
||||
Targets.Add(proto.ID, target);
|
||||
|
||||
foreach (TechProto post in LDB.techs.dataArray)
|
||||
{
|
||||
return;
|
||||
if (post == null || post.ID == proto.ID ||
|
||||
!(Contains(post.PreTechs, proto.ID) || Contains(post.PreTechsImplicit, proto.ID))) continue;
|
||||
|
||||
// Mirrors GameHistoryData.TechUnlocked(id, max). A partially researched dependent also
|
||||
// needs to be reset; its own unlocked flag does not describe its prerequisite's validity.
|
||||
if (state.unlocked && target >= state.curLevel && (!post.PreTechsMax || target == state.maxLevel)) continue;
|
||||
if (!history.techStates.TryGetValue(post.ID, out TechState postState)) continue;
|
||||
if (GetLastAppliedLevel(postState) < post.Level && postState.hashUploaded == 0) continue;
|
||||
Plan(history, post, post.Level - 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(proto.ID, out TechState state))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (target >= lastApplied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool willBeUnlocked = target >= state.maxLevel;
|
||||
|
||||
RevertDependentTechs(history, proto, willBeUnlocked, target, state.maxLevel);
|
||||
|
||||
for (int level = lastApplied; level > target; level--)
|
||||
private static void Apply(GameHistoryData history, TechProto proto, int target)
|
||||
{
|
||||
TechState state = history.techStates[proto.ID];
|
||||
for (int level = GetLastAppliedLevel(state); level > target; level--)
|
||||
{
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
// One failing function must not abort the whole downgrade: that would leave the tech
|
||||
// state updated for some techs and stale for others.
|
||||
try
|
||||
{
|
||||
TechFuncRevert.Revert(history, proto.UnlockFunctions[j], proto.UnlockValues[j], level);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
TechLog.Warn($"reverting tech function {proto.UnlockFunctions[j]} of tech {proto.ID} " +
|
||||
$"at level {level} failed: {e}");
|
||||
}
|
||||
TechFuncRevert.Revert(history, proto.UnlockFunctions[j], proto.UnlockValues[j], level);
|
||||
}
|
||||
}
|
||||
|
||||
// Recipes are unlocked when the tech reaches level 0 (see TechUnlock); they are locked again
|
||||
// only when the tech itself becomes locked.
|
||||
state.unlocked = target >= state.maxLevel;
|
||||
state.curLevel = state.unlocked ? state.maxLevel : target + 1;
|
||||
state.hashNeeded = proto.GetHashNeeded(state.curLevel);
|
||||
state.hashUploaded = state.unlocked ? state.hashNeeded : 0L;
|
||||
state.unlockTick = 0;
|
||||
history.techStates[proto.ID] = state;
|
||||
if (target < proto.Level)
|
||||
{
|
||||
foreach (int recipe in proto.UnlockRecipes)
|
||||
{
|
||||
LockRecipeIfUnused(history, recipe, proto.ID);
|
||||
}
|
||||
}
|
||||
|
||||
state = history.techStates[proto.ID];
|
||||
state.unlocked = willBeUnlocked;
|
||||
state.curLevel = willBeUnlocked ? state.maxLevel : target + 1;
|
||||
state.hashNeeded = proto.GetHashNeeded(state.curLevel);
|
||||
state.hashUploaded = willBeUnlocked ? state.hashNeeded : 0L;
|
||||
history.techStates[proto.ID] = state;
|
||||
Touched[proto.ID] = state.curLevel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls back every already-unlocked dependent tech whose prerequisite requirement would be
|
||||
/// violated by this downgrade. <c>PreTechsMax</c> demands the prerequisite to be fully unlocked, so
|
||||
/// the dependent is dropped to "not unlocked" (<c>maxLevel - 1</c> applied levels); a prerequisite
|
||||
/// that becomes fully locked forces the dependent to be locked as well.
|
||||
/// </summary>
|
||||
private static void RevertDependentTechs(GameHistoryData history, TechProto proto, bool willBeUnlocked,
|
||||
int target, int maxLevel)
|
||||
{
|
||||
bool preMaxSatisfied = willBeUnlocked && target >= maxLevel;
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto post = all[i];
|
||||
if (post == null || post.ID == proto.ID || !DependsOn(post, proto.ID))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!history.techStates.TryGetValue(post.ID, out TechState postState))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int postLast = GetLastAppliedLevel(postState);
|
||||
if (postLast < post.Level)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only techs that currently meet their requirement can become illegal.
|
||||
bool currentlyOk = post.PreTechsMax
|
||||
? postState.unlocked && postState.curLevel == postState.maxLevel
|
||||
: postState.unlocked;
|
||||
bool stillOk = post.PreTechsMax ? preMaxSatisfied : willBeUnlocked;
|
||||
if (!currentlyOk || stillOk)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int postTarget = postState.maxLevel - 1;
|
||||
if (postTarget < post.Level)
|
||||
{
|
||||
postTarget = post.Level - 1;
|
||||
}
|
||||
|
||||
if (postTarget >= postLast)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
DowngradeTo(history, post, postLast, postTarget);
|
||||
foreach (int recipe in proto.UnlockRecipes) Recipes.Add(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool DependsOn(TechProto post, int techId) =>
|
||||
Contains(post.PreTechs, techId) || Contains(post.PreTechsImplicit, techId);
|
||||
|
||||
private static bool Contains(int[] array, int value)
|
||||
internal static bool Contains(int[] array, int value)
|
||||
{
|
||||
if (array == null)
|
||||
if (array == null) return false;
|
||||
foreach (int item in array)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
if (array[i] == value)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (item == value) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a recipe from the unlocked set unless another tech that still has levels applied
|
||||
/// unlocks it too. <c>GameHistoryData</c> only exposes <c>UnlockRecipe</c>, so the Set is edited
|
||||
/// directly and the one special recipe id (the delivery package, recipe 122) is reverted by hand.
|
||||
/// </summary>
|
||||
private static void LockRecipeIfUnused(GameHistoryData history, int recipeId, int excludeTechId)
|
||||
internal static bool IsRecipeGranted(GameHistoryData history, int recipeId,
|
||||
IReadOnlyDictionary<int, int> targets = null)
|
||||
{
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
if (Contains(Configs.freeMode.recipes, recipeId)) return true;
|
||||
foreach (TechProto proto in LDB.techs.dataArray)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto == null || proto.ID == excludeTechId || !HasAnyAppliedLevel(history, proto))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Contains(proto.UnlockRecipes, recipeId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (proto == null || !Contains(proto.UnlockRecipes, recipeId)) continue;
|
||||
int last = targets != null && targets.TryGetValue(proto.ID, out int target)
|
||||
? target
|
||||
: history.techStates.TryGetValue(proto.ID, out TechState state) ? GetLastAppliedLevel(state) : proto.Level - 1;
|
||||
if (last >= proto.Level) return true;
|
||||
}
|
||||
|
||||
if (history.recipeUnlocked != null)
|
||||
{
|
||||
history.recipeUnlocked.Remove(recipeId);
|
||||
}
|
||||
|
||||
const int dispenserRecipeId = 122;
|
||||
if (recipeId == dispenserRecipeId)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (player?.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.unlocked = false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replays the per-node refresh the game performs on an upgrade, without firing the "research
|
||||
/// complete" popup or the scenario hooks (a downgrade is not a research event).
|
||||
/// </summary>
|
||||
private static void RefreshTechTree()
|
||||
internal static void RefreshOpenWindow()
|
||||
{
|
||||
UITechTree window = UIRoot.instance?.uiGame?.techTree;
|
||||
if (window == null || !window.active || Touched.Count == 0)
|
||||
if (window == null || !window.active) return;
|
||||
|
||||
// Restore native layering for all nodes once, without emitting research-complete events
|
||||
// or promoting downgraded nodes through the upgrade-only SortUnlockedNode path.
|
||||
window.SortTechNodeOrderInGroup(window.graphGroup0);
|
||||
window.SortTechNodeOrderInGroup(window.graphGroup1);
|
||||
foreach (UITechNode node in window.nodes.Values)
|
||||
{
|
||||
return;
|
||||
node.UpdateInfoComplete();
|
||||
node.UpdateInfoDynamic(true);
|
||||
node.UpdateLayoutDynamic(true, true);
|
||||
node.UpdateConnDynamic();
|
||||
}
|
||||
|
||||
MethodInfo refresh = AccessTools.Method(typeof(UITechTree), "OnTechUnlocked",
|
||||
new[] { typeof(int), typeof(int), typeof(bool) });
|
||||
if (refresh == null)
|
||||
{
|
||||
window.RefreshDataValueText();
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var pair in Touched)
|
||||
{
|
||||
refresh.Invoke(window, new object[] { pair.Key, pair.Value, true });
|
||||
}
|
||||
window.selected?.RefreshPreTechCheckboxes();
|
||||
window.ResetTipDelay();
|
||||
window.RefreshDataValueText();
|
||||
}
|
||||
|
||||
internal static void RefreshOpenWindow() => RefreshTechTree();
|
||||
}
|
||||
@@ -5,29 +5,10 @@ using UnityEngine;
|
||||
namespace CheatEnabler.Patches.Tech
|
||||
{
|
||||
/// <summary>
|
||||
/// F4 - the downgrade side of <c>GameHistoryData.UnlockTechFunction</c>.
|
||||
///
|
||||
/// <para><b>Chosen approach: A (per-function inverse operation), with recomputation for the
|
||||
/// functions where an inverse is either impossible or not drift free.</b></para>
|
||||
///
|
||||
/// <para>Why A rather than B (reset to base plus full replay): a replay has to re-run every side
|
||||
/// effect of <c>UnlockTechFunction</c> on the live game objects. Several of those are ratchets that
|
||||
/// cannot be replayed safely - <c>func 30/31</c> rescale existing logistics station storage
|
||||
/// proportionally through <c>PlanetTransport.OnTechFunctionUnlocked</c>, and <c>func 5/38</c> resize
|
||||
/// the player's package. Replaying them would double-apply the scaling instead of restoring it.
|
||||
/// Inverse operations touch exactly the field that was changed and nothing else, and they need no
|
||||
/// snapshot, so they also survive save/load.</para>
|
||||
///
|
||||
/// <para>Where an inverse is not available the value is recomputed from
|
||||
/// <c>Configs.freeMode</c> - the very table <c>GameHistoryData.SetForNewGame</c> uses to
|
||||
/// initialise the field - plus the set of levels still applied across all techs. That covers the
|
||||
/// multiplicative functions (no float drift, and <c>func 20</c> recovers from the game's 0 clamp,
|
||||
/// which a division can never undo), the assignment functions (a plain subtraction is wrong when
|
||||
/// the value came from a different tech) and the boolean / one-way functions (there is no
|
||||
/// "unset" call in the game).</para>
|
||||
///
|
||||
/// <para>Every case of the original switch (1-45, 61-86, 99 - ids 46-60 and 87-98 do not exist)
|
||||
/// is handled below or explicitly delegated to <see cref="Recompute"/>.</para>
|
||||
/// Reverts the fields changed by GameHistoryData.UnlockTechFunction. Lossy, multiplicative,
|
||||
/// assignment and boolean functions are recomputed from native defaults and surviving levels.
|
||||
/// Package geometry and station limits are reconciled once per click; native unlock side effects
|
||||
/// must never be replayed across the whole tech tree.
|
||||
/// </summary>
|
||||
internal static class TechFuncRevert
|
||||
{
|
||||
@@ -113,6 +94,7 @@ namespace CheatEnabler.Patches.Tech
|
||||
{
|
||||
mecha.coreEnergyCap = 0.0;
|
||||
}
|
||||
mecha.coreEnergy = Math.Min(mecha.coreEnergy, mecha.coreEnergyCap);
|
||||
}
|
||||
|
||||
TechDowngrade.MarkDirty(func);
|
||||
@@ -224,9 +206,7 @@ namespace CheatEnabler.Patches.Tech
|
||||
break;
|
||||
|
||||
case 30:
|
||||
// PlanetTransport.OnTechFunctionUnlocked rescaled every local station's storage when
|
||||
// this was applied; shrinking the *count* back is the inverse the game itself uses
|
||||
// when the field is lowered, so no extra rescale is performed here.
|
||||
// Existing station limits are rescaled once after all levels have been reverted.
|
||||
history.localStationExtraStorage = Math.Max(0, history.localStationExtraStorage - num);
|
||||
break;
|
||||
|
||||
@@ -260,7 +240,7 @@ namespace CheatEnabler.Patches.Tech
|
||||
break;
|
||||
|
||||
case 36:
|
||||
history.dispenserDeliveryMaxAngle = Math.Max(0f, history.dispenserDeliveryMaxAngle - (float)value);
|
||||
history.dispenserDeliveryMaxAngle = Math.Max(0f, history.dispenserDeliveryMaxAngle - num);
|
||||
break;
|
||||
|
||||
case 37: // feature keys: recomputed
|
||||
@@ -321,6 +301,7 @@ namespace CheatEnabler.Patches.Tech
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldCapacity = Math.Max(0L, mecha.energyShieldCapacity - num);
|
||||
mecha.energyShieldEnergy = Math.Min(mecha.energyShieldEnergy, mecha.energyShieldCapacity);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -369,25 +350,25 @@ namespace CheatEnabler.Patches.Tech
|
||||
case 77:
|
||||
if (mecha != null && mecha.groundCombatModule != null)
|
||||
{
|
||||
mecha.groundCombatModule.fleetCount = Math.Max(0, mecha.groundCombatModule.fleetCount - num);
|
||||
mecha.groundCombatModule.fleetCount = Math.Max(0, mecha.groundCombatModule.fleetCount - (int)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 78:
|
||||
history.groundFleetPortCount = Math.Max(0, history.groundFleetPortCount - num);
|
||||
history.groundFleetPortCount = Math.Max(0, history.groundFleetPortCount - (int)value);
|
||||
break;
|
||||
|
||||
case 79:
|
||||
if (mecha != null && mecha.spaceCombatModule != null)
|
||||
{
|
||||
mecha.spaceCombatModule.fleetCount = Math.Max(0, mecha.spaceCombatModule.fleetCount - num);
|
||||
mecha.spaceCombatModule.fleetCount = Math.Max(0, mecha.spaceCombatModule.fleetCount - (int)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 80:
|
||||
history.spaceFleetPortCount = Math.Max(0, history.spaceFleetPortCount - num);
|
||||
history.spaceFleetPortCount = Math.Max(0, history.spaceFleetPortCount - (int)value);
|
||||
break;
|
||||
|
||||
case 81:
|
||||
@@ -399,18 +380,8 @@ namespace CheatEnabler.Patches.Tech
|
||||
break;
|
||||
|
||||
case 82:
|
||||
// The forward operation is `range *= 1 + value / range`, which is exactly
|
||||
// `range += value`; the inverse is therefore a plain subtraction.
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.laserLocalAttackRange = Math.Max(0f, mecha.laserLocalAttackRange - (float)value);
|
||||
mecha.laserSpaceAttackRange = Math.Max(0f, mecha.laserSpaceAttackRange - (float)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 83:
|
||||
RevertLaserDamage(mecha, num);
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 84:
|
||||
@@ -466,7 +437,7 @@ namespace CheatEnabler.Patches.Tech
|
||||
{
|
||||
case 5:
|
||||
case 38:
|
||||
ReconcilePackage(history, freeMode);
|
||||
ReconcilePackage(history);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
@@ -576,7 +547,15 @@ namespace CheatEnabler.Patches.Tech
|
||||
break;
|
||||
|
||||
case 76:
|
||||
history.autoReconstructSpeed = PickMax(history, func, 0);
|
||||
int speed = 0;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
speed = Math.Max(speed, (int)value));
|
||||
history.autoReconstructSpeed = speed;
|
||||
break;
|
||||
|
||||
case 82:
|
||||
case 83:
|
||||
RecomputeLaser(history, freeMode, mecha, func);
|
||||
break;
|
||||
|
||||
case 86:
|
||||
@@ -728,7 +707,8 @@ namespace CheatEnabler.Patches.Tech
|
||||
return found;
|
||||
}
|
||||
|
||||
internal static void ForEachAppliedFunction(GameHistoryData history, int func, Action<TechProto, int, double> visit)
|
||||
internal static void ForEachAppliedFunction(GameHistoryData history, int func, Action<TechProto, int, double> visit,
|
||||
IReadOnlyDictionary<int, int> targets = null)
|
||||
{
|
||||
if (history.techStates == null)
|
||||
{
|
||||
@@ -744,7 +724,13 @@ namespace CheatEnabler.Patches.Tech
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TechDowngrade.TryGetLastAppliedLevel(history, proto, out int lastApplied))
|
||||
int lastApplied;
|
||||
if (targets != null && targets.TryGetValue(proto.ID, out int target))
|
||||
{
|
||||
lastApplied = target;
|
||||
if (lastApplied < proto.Level) continue;
|
||||
}
|
||||
else if (!TechDowngrade.TryGetLastAppliedLevel(history, proto, out lastApplied))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -774,158 +760,233 @@ namespace CheatEnabler.Patches.Tech
|
||||
mecha.hp = maxApplied;
|
||||
}
|
||||
|
||||
if (mecha.hp < 1)
|
||||
{
|
||||
mecha.hp = 1;
|
||||
}
|
||||
mecha.hp = Math.Max(0, mecha.hp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 83 scales every laser stat by <c>1 + num / laserLocalDamage</c> measured *before* the
|
||||
/// change. The integer rounding makes the transform lossy, so the previous damage value is
|
||||
/// recovered as <c>laserLocalDamage - num</c> and the other stats are divided by the same
|
||||
/// factor.
|
||||
/// Both ranges use the factor computed from the local range. Damage and energy use native
|
||||
/// integer rounding on every level, so division cannot recover the previous values exactly.
|
||||
/// </summary>
|
||||
private static void RevertLaserDamage(Mecha mecha, int num)
|
||||
private static void RecomputeLaser(GameHistoryData history, ModeConfig config, Mecha mecha, int func)
|
||||
{
|
||||
if (mecha == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int damageAfter = mecha.laserLocalDamage;
|
||||
int damageBefore = damageAfter - num;
|
||||
if (damageBefore < 1)
|
||||
if (func == 82)
|
||||
{
|
||||
damageBefore = 1;
|
||||
mecha.laserLocalAttackRange = config.mechaLocalLaserAttackRange;
|
||||
mecha.laserSpaceAttackRange = config.mechaSpaceLaserAttackRange;
|
||||
}
|
||||
else
|
||||
{
|
||||
mecha.laserLocalDamage = config.mechaLocalLaserDamage;
|
||||
mecha.laserSpaceDamage = config.mechaSpaceLaserDamage;
|
||||
mecha.laserEnergyCapacity = config.mechaLaserEnergyCapacity;
|
||||
mecha.laserLocalEnergyCost = config.mechaLocalLaserEnergyCost;
|
||||
mecha.laserSpaceEnergyCost = config.mechaSpaceLaserEnergyCost;
|
||||
}
|
||||
|
||||
float inverseFactor = damageAfter > 0 ? (float)damageBefore / damageAfter : 1f;
|
||||
mecha.laserLocalDamage = damageBefore;
|
||||
mecha.laserSpaceDamage = (int)(mecha.laserSpaceDamage * inverseFactor + 0.5f);
|
||||
mecha.laserEnergyCapacity = (int)(mecha.laserEnergyCapacity * inverseFactor + 0.5f);
|
||||
mecha.laserLocalEnergyCost = (int)(mecha.laserLocalEnergyCost * inverseFactor + 0.5f);
|
||||
mecha.laserSpaceEnergyCost = (int)(mecha.laserSpaceEnergyCost * inverseFactor + 0.5f);
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
for (int level = proto.Level; level <= lastApplied; level++)
|
||||
{
|
||||
if (func == 82)
|
||||
{
|
||||
float factor = 1f + (float)(value / mecha.laserLocalAttackRange);
|
||||
mecha.laserLocalAttackRange *= factor;
|
||||
mecha.laserSpaceAttackRange *= factor;
|
||||
}
|
||||
else
|
||||
{
|
||||
float factor = 1f + (float)ToInt(value) / mecha.laserLocalDamage;
|
||||
mecha.laserLocalDamage = (int)(mecha.laserLocalDamage * factor + 0.5f);
|
||||
mecha.laserSpaceDamage = (int)(mecha.laserSpaceDamage * factor + 0.5f);
|
||||
mecha.laserEnergyCapacity = (int)(mecha.laserEnergyCapacity * factor + 0.5f);
|
||||
mecha.laserLocalEnergyCost = (int)(mecha.laserLocalEnergyCost * factor + 0.5f);
|
||||
mecha.laserSpaceEnergyCost = (int)(mecha.laserSpaceEnergyCost * factor + 0.5f);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (func == 83) mecha.laserEnergy = Math.Min(mecha.laserEnergy, mecha.laserEnergyCapacity);
|
||||
}
|
||||
|
||||
/// <summary>Rejects the whole cascade before any state changes if capacity would hide live contents.</summary>
|
||||
internal static bool CanRevert(GameHistoryData history, IReadOnlyDictionary<int, int> targets)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (Configs.freeMode == null || history.gameData == null || player?.mecha == null ||
|
||||
player.package?.grids == null || player.deliveryPackage?.grids == null)
|
||||
{
|
||||
TechLog.Warn("downgrade skipped: game data is not ready");
|
||||
return false;
|
||||
}
|
||||
|
||||
var removed = new Dictionary<int, int>();
|
||||
bool deliveryUnlockRemoved = false;
|
||||
foreach (var pair in targets)
|
||||
{
|
||||
TechProto proto = LDB.techs.Select(pair.Key);
|
||||
int count = TechDowngrade.GetLastAppliedLevel(history.techStates[pair.Key]) - pair.Value;
|
||||
deliveryUnlockRemoved |= pair.Value < proto.Level &&
|
||||
TechDowngrade.Contains(proto.UnlockRecipes, TechDowngrade.DeliveryPackageRecipeId);
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
int func = proto.UnlockFunctions[j];
|
||||
if (!(func is >= 1 and <= 45 or >= 61 and <= 86 or 99))
|
||||
{
|
||||
TechLog.Warn($"downgrade skipped: unsupported tech function {func} in tech {proto.ID}");
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeUnsupportedFunction.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
int value = func is >= 77 and <= 80 ? (int)proto.UnlockValues[j] : ToInt(proto.UnlockValues[j]);
|
||||
removed.TryGetValue(func, out int previous);
|
||||
removed[func] = previous + value * count;
|
||||
}
|
||||
}
|
||||
|
||||
int packageCols = player.GetPackageColumnCount();
|
||||
int packageRows = (player.package.size - 1) / packageCols + 1;
|
||||
bool resizePackage = removed.ContainsKey(5) || removed.ContainsKey(38);
|
||||
if (resizePackage)
|
||||
{
|
||||
GetPackageGeometry(history, targets, out packageCols, out packageRows);
|
||||
if (!CanResizePackage(player, packageCols, packageRows))
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.PackageResizeSkippedOccupiedCells.Translate());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
DeliveryPackage delivery = player.deliveryPackage;
|
||||
removed.TryGetValue(32, out int deliveryColsRemoved);
|
||||
int deliveryCols = Math.Max(0, delivery.colCount - deliveryColsRemoved);
|
||||
int deliveryRows = resizePackage ? Math.Min(DeliveryPackage.MAX_ROWCOUNT, packageRows) : delivery.rowCount;
|
||||
bool deliveryLocked = deliveryUnlockRemoved &&
|
||||
!TechDowngrade.IsRecipeGranted(history, TechDowngrade.DeliveryPackageRecipeId, targets);
|
||||
for (int i = 0; i < delivery.grids.Length; i++)
|
||||
{
|
||||
if (!delivery.IsGridActive(i) || (!deliveryLocked &&
|
||||
i / DeliveryPackage.MAX_COLCOUNT < deliveryRows &&
|
||||
DeliveryPackage.MAX_COLCOUNT - 1 - i % DeliveryPackage.MAX_COLCOUNT < deliveryCols)) continue;
|
||||
if (delivery.grids[i].count > 0 || delivery.grids[i].ordered != 0)
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeDeliveryOccupied.Translate());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
removed.TryGetValue(1, out int dronesRemoved);
|
||||
if (dronesRemoved > player.mecha.constructionModule.droneIdleCount)
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeDronesBusy.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
removed.TryGetValue(77, out int groundFleetsRemoved);
|
||||
removed.TryGetValue(79, out int spaceFleetsRemoved);
|
||||
if (!CanRemoveFleets(player.mecha.groundCombatModule, groundFleetsRemoved) ||
|
||||
!CanRemoveFleets(player.mecha.spaceCombatModule, spaceFleetsRemoved))
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeFleetsOccupied.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool CanRemoveFleets(CombatModuleComponent module, int removed)
|
||||
{
|
||||
if (removed <= 0 || module?.moduleFleets == null) return true;
|
||||
int target = Math.Max(0, module.fleetCount - removed);
|
||||
for (int i = target; i < Math.Min(module.fleetCount, module.moduleFleets.Length); i++)
|
||||
{
|
||||
ModuleFleet fleet = module.moduleFleets[i];
|
||||
if (fleet.fleetId != 0) return false;
|
||||
if (fleet.fighters == null) continue;
|
||||
foreach (ModuleFighter fighter in fleet.fighters)
|
||||
{
|
||||
if (fighter.count > 0 || fighter.craftId != 0) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static void ReconcileStationStorage(GameHistoryData history, int localBefore, int remoteBefore)
|
||||
{
|
||||
int localDelta = history.localStationExtraStorage - localBefore;
|
||||
int remoteDelta = history.remoteStationExtraStorage - remoteBefore;
|
||||
if (localDelta == 0 && remoteDelta == 0) return;
|
||||
GameData data = history.gameData;
|
||||
for (int i = 0; i < data.factoryCount; i++)
|
||||
{
|
||||
PlanetTransport transport = data.factories[i]?.transport;
|
||||
if (transport == null) continue;
|
||||
// Native scaling uses the already updated capacity and the signed change. Passing a
|
||||
// negative delta restores the configured station limits without removing stored items.
|
||||
if (localDelta != 0) transport.OnTechFunctionUnlocked(30, localDelta, 0);
|
||||
if (remoteDelta != 0) transport.OnTechFunctionUnlocked(31, remoteDelta, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void GetPackageGeometry(GameHistoryData history, IReadOnlyDictionary<int, int> targets,
|
||||
out int columns, out int rows)
|
||||
{
|
||||
const int baseColumns = 10;
|
||||
int baseSize = Configs.freeMode.playerPackageSize;
|
||||
int columnCount = baseColumns;
|
||||
int rowCount = (baseSize - 1) / baseColumns + 1;
|
||||
ForEachAppliedFunction(history, 38, (proto, last, value) =>
|
||||
columnCount += ToInt(value) * (last - proto.Level + 1), targets);
|
||||
ForEachAppliedFunction(history, 5, (proto, last, value) =>
|
||||
rowCount += ToInt(value) * (last - proto.Level + 1), targets);
|
||||
columns = columnCount;
|
||||
rows = rowCount;
|
||||
}
|
||||
|
||||
private static bool CanResizePackage(Player player, int columns, int rows)
|
||||
{
|
||||
StorageComponent package = player.package;
|
||||
int oldColumns = player.GetPackageColumnCount();
|
||||
for (int i = 0; i < package.size; i++)
|
||||
{
|
||||
if (package.grids[i].itemId != 0 && (i / oldColumns >= rows || i % oldColumns >= columns))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 5 and func 38 both resize the player's package: func 5 adds whole rows
|
||||
/// (<c>SetSize(size + num * colCount)</c>) and func 38 changes the column count, which re-lays-out
|
||||
/// every row.
|
||||
///
|
||||
/// Neither can be undone by simply calling the game's resize in reverse:
|
||||
/// <c>StorageComponent.SetSize(int, int, int)</c> iterates the *whole* backing array and computes
|
||||
/// <c>row * newcol + col</c>, so shrinking the column count runs past the new size and throws
|
||||
/// <c>IndexOutOfRangeException</c> (verified in game). The geometry is therefore recomputed from
|
||||
/// the base values and the levels still applied, and the grid is re-laid-out cell by cell.
|
||||
///
|
||||
/// If an occupied cell would fall outside the target layout the resize is refused and reported -
|
||||
/// no item is ever destroyed, and the tech level is still reverted.
|
||||
/// Native SetSize cannot shrink columns safely. Preserve each retained cell's position and
|
||||
/// metadata; CanRevert has already checked every cell that the new layout would remove.
|
||||
/// </summary>
|
||||
private static void ReconcilePackage(GameHistoryData history, ModeConfig freeMode)
|
||||
private static void ReconcilePackage(GameHistoryData history)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (player?.package == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Player.SetForNewGame(): packageColCount = 10, package = Configs.freeMode.playerPackageSize cells.
|
||||
const int baseCols = 10;
|
||||
int baseSize = freeMode.playerPackageSize;
|
||||
if (baseSize <= 0)
|
||||
{
|
||||
baseSize = baseCols * 4;
|
||||
}
|
||||
|
||||
int baseRows = (baseSize - 1) / baseCols + 1;
|
||||
int targetCols = baseCols;
|
||||
int targetRows = baseRows;
|
||||
|
||||
// Each applied level adds its value: func 38 to the column count, func 5 to the row count.
|
||||
ForEachAppliedFunction(history, 38, (proto, lastApplied, value) =>
|
||||
targetCols += ToInt(value) * (lastApplied - proto.Level + 1));
|
||||
ForEachAppliedFunction(history, 5, (proto, lastApplied, value) =>
|
||||
targetRows += ToInt(value) * (lastApplied - proto.Level + 1));
|
||||
|
||||
if (targetCols < baseCols)
|
||||
{
|
||||
targetCols = baseCols;
|
||||
}
|
||||
|
||||
if (targetRows < baseRows)
|
||||
{
|
||||
targetRows = baseRows;
|
||||
}
|
||||
|
||||
GetPackageGeometry(history, null, out int targetCols, out int targetRows);
|
||||
int targetSize = targetRows * targetCols;
|
||||
|
||||
StorageComponent package = player.package;
|
||||
StorageComponent.GRID[] oldGrid = package.grids;
|
||||
if (oldGrid == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldCols = player.packageColCount < 1 ? baseCols : player.packageColCount;
|
||||
int oldSize = package.size;
|
||||
if (oldSize <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldRows = (oldSize - 1) / oldCols + 1;
|
||||
if (oldCols == targetCols && oldSize == targetSize)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (int r = 0; r < oldRows; r++)
|
||||
{
|
||||
for (int c = 0; c < oldCols; c++)
|
||||
{
|
||||
int index = r * oldCols + c;
|
||||
if (index >= oldGrid.Length || index >= oldSize || oldGrid[index].itemId == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (r < targetRows && c < targetCols)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
TechLog.Warn($"package resize skipped: cell {index} (row {r}, column {c}) is not empty and would " +
|
||||
"fall outside the new layout, so no item is destroyed. The tech level was still reverted.");
|
||||
UIRealtimeTip.Popup(Localization.PackageResizeSkippedOccupiedCells.Translate());
|
||||
return;
|
||||
}
|
||||
}
|
||||
int oldCols = player.GetPackageColumnCount();
|
||||
if (oldCols == targetCols && package.size == targetSize) return;
|
||||
|
||||
var newGrid = new StorageComponent.GRID[targetSize];
|
||||
for (int r = 0; r < oldRows; r++)
|
||||
for (int i = 0; i < package.size; i++)
|
||||
{
|
||||
for (int c = 0; c < oldCols; c++)
|
||||
{
|
||||
if (r >= targetRows || c >= targetCols)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int from = r * oldCols + c;
|
||||
if (from >= oldGrid.Length || from >= oldSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
newGrid[r * targetCols + c] = oldGrid[from];
|
||||
}
|
||||
int row = i / oldCols;
|
||||
int col = i % oldCols;
|
||||
if (row < targetRows && col < targetCols) newGrid[row * targetCols + col] = package.grids[i];
|
||||
}
|
||||
|
||||
player.packageColCount = targetCols;
|
||||
package.grids = newGrid;
|
||||
package.size = targetSize;
|
||||
package.searchStart = 0;
|
||||
package.SetBans(Math.Min(package.bans, targetSize));
|
||||
package.ResetOptimizationFlags();
|
||||
package.NotifyStorageChange();
|
||||
package.NotifyStorageSizeChange();
|
||||
|
||||
@@ -3,8 +3,7 @@ namespace CheatEnabler.Patches.Tech;
|
||||
/// <summary>
|
||||
/// The key-modifier semantics shared by the upgrade and the downgrade side.
|
||||
///
|
||||
/// The mapping mirrors the built-in <see cref="GamePatch.UnlockTech"/> handler so both features behave
|
||||
/// identically, and the downgrade side is its exact mirror:
|
||||
/// Both directions use the same modifier mapping:
|
||||
///
|
||||
/// <list type="table">
|
||||
/// <item><term>Shift</term><description>+1 / -1</description></item>
|
||||
|
||||
@@ -1,183 +1,81 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UIUtil = UXAssist.UI.Util;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Help button for the tech / upgrade window.
|
||||
///
|
||||
/// The button is created once under the <c>UITechTree</c> window itself, so it inherits the window's
|
||||
/// lifetime and disappears with it.
|
||||
///
|
||||
/// It is anchored directly under the "Tech" tab caption in the top-left corner
|
||||
/// (<c>UITechTree.tabButtonText0</c>). It was originally placed in the bottom-left corner, but the
|
||||
/// tooltip is tall and the game's bottom HUD bar clipped it there.
|
||||
///
|
||||
/// The button clones the game's own tip-button prefab used by the sandbox settings
|
||||
/// (<c>galaxySelect.sandboxToggle</c> parent / <c>tip-button</c>), which is what UXAssist's
|
||||
/// <c>LayoutHelper.AddTipsButton</c> does as well. The prefab's <c>UIButton.TipSettings</c> carries
|
||||
/// the tip prefab plumbing and tip delay, so it is saved before the button state is normalised and
|
||||
/// restored afterwards - dropping it would produce a button without a tooltip.
|
||||
/// </summary>
|
||||
/// <summary>Owns the cloned native help button, including its lifetime and localized tooltip.</summary>
|
||||
internal static class TechTreeUI
|
||||
{
|
||||
private const float HelpButtonGap = 4f;
|
||||
private const float HelpButtonLeftFallback = 24f;
|
||||
private const float HelpButtonBottomFallback = 24f;
|
||||
|
||||
private static RectTransform _root;
|
||||
private static UITechTree _window;
|
||||
private static UIButton _helpButton;
|
||||
|
||||
public static void OnTechTreeOpened(UITechTree window)
|
||||
{
|
||||
EnsureCreated(window);
|
||||
}
|
||||
if (window == null) return;
|
||||
if (_window != window) Reset();
|
||||
_window = window;
|
||||
if (_helpButton != null) return;
|
||||
|
||||
/// <summary>
|
||||
/// The window's whole GameObject is destroyed when it is freed, taking our elements with it,
|
||||
/// so the cached references only have to be dropped.
|
||||
/// </summary>
|
||||
public static void OnTechTreeFreed()
|
||||
{
|
||||
_root = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
Transform source = UIRoot.instance?.galaxySelect?.sandboxToggle?.transform.parent?.Find("tip-button");
|
||||
if (source == null) return;
|
||||
|
||||
/// <summary>
|
||||
/// Drops the created elements. The window's own GameObject may still be alive here (the feature was
|
||||
/// switched off while the tech tree was open), so the root is destroyed explicitly instead of only
|
||||
/// clearing the cached references.
|
||||
/// </summary>
|
||||
public static void Reset()
|
||||
{
|
||||
if (_root != null)
|
||||
{
|
||||
Object.Destroy(_root.gameObject);
|
||||
}
|
||||
|
||||
_root = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
|
||||
private static void EnsureCreated(UITechTree window)
|
||||
{
|
||||
if (_root != null || window == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(window.transform is RectTransform windowRect))
|
||||
{
|
||||
TechLog.Warn("tech tree window has no RectTransform, help button was not created");
|
||||
return;
|
||||
}
|
||||
|
||||
var rootGo = new GameObject("TechTweaks-UI", typeof(RectTransform));
|
||||
_root = (RectTransform)rootGo.transform;
|
||||
_root.SetParent(windowRect, false);
|
||||
_root.anchorMin = Vector2.zero;
|
||||
_root.anchorMax = Vector2.one;
|
||||
_root.pivot = new Vector2(0.5f, 0.5f);
|
||||
_root.anchoredPosition3D = Vector3.zero;
|
||||
_root.offsetMin = Vector2.zero;
|
||||
_root.offsetMax = Vector2.zero;
|
||||
_root.SetAsLastSibling();
|
||||
|
||||
_helpButton = CreateHelpButton(window, _root);
|
||||
}
|
||||
|
||||
private static UIButton CreateHelpButton(UITechTree window, RectTransform root)
|
||||
{
|
||||
Transform source = FindTipsButtonPrefab();
|
||||
if (source == null)
|
||||
{
|
||||
TechLog.Warn("native tip-button prefab not found, tech tree help button was not created");
|
||||
return null;
|
||||
}
|
||||
|
||||
GameObject clone = Object.Instantiate(source.gameObject);
|
||||
GameObject clone = Object.Instantiate(source.gameObject, window.transform, false);
|
||||
clone.name = "TechTweaks-HelpButton";
|
||||
var button = clone.GetComponent<UIButton>();
|
||||
if (button == null)
|
||||
_helpButton = clone.GetComponent<UIButton>();
|
||||
if (_helpButton == null)
|
||||
{
|
||||
TechLog.Warn("tip-button prefab has no UIButton, tech tree help button was not created");
|
||||
Object.Destroy(clone);
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the prefab's tip plumbing (simpleGeneralTipPrefab, level, delay, corner, width)
|
||||
// before the state reset wipes it out.
|
||||
UIButton.TipSettings tipSettings = button.tips;
|
||||
button.Init();
|
||||
button.enabled = true;
|
||||
button.highlighted = false;
|
||||
button.updating = true;
|
||||
button.data = 0;
|
||||
if (button.button != null)
|
||||
{
|
||||
button.button.onClick.RemoveAllListeners();
|
||||
button.button.enabled = true;
|
||||
button.button.interactable = true;
|
||||
}
|
||||
|
||||
button.MReset();
|
||||
button.tips = tipSettings;
|
||||
button.tips.topLevel = true;
|
||||
// corner selects which corner of the button the tooltip hangs off (3 = below-right, see
|
||||
// UISimpleGeneralTip.SetTip). The prefab defaults to a vertically centred placement, which
|
||||
// pushes a tall tooltip off the top of the screen once the button sits in the header area.
|
||||
button.tips.corner = 3;
|
||||
// Same title and body as the config panel's tooltip button, so the two read identically.
|
||||
button.tips.tipTitle = Localization.UnlockDowngradeTechWithKeyModifiers.Translate();
|
||||
button.tips.tipText = Localization.TechModifierHelpBody.Translate();
|
||||
// Reset cloned runtime state while retaining the native tooltip prefab and timing.
|
||||
UIButton.TipSettings tipSettings = _helpButton.tips;
|
||||
_helpButton.button?.onClick.RemoveAllListeners();
|
||||
UIUtil.ResetButton(_helpButton);
|
||||
_helpButton.tips = tipSettings;
|
||||
_helpButton.tips.topLevel = true;
|
||||
_helpButton.tips.corner = 3;
|
||||
|
||||
var rect = (RectTransform)clone.transform;
|
||||
PlaceHelpButton(window, rect, root);
|
||||
button.UpdateTip();
|
||||
clone.SetActive(true);
|
||||
return button;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the button right under the "Tech" tab caption in the window's top-left corner, reusing
|
||||
/// that caption's anchors and pivot so the offset means the same thing at any resolution. Falls
|
||||
/// back to the bottom-left corner if the caption is not available.
|
||||
/// </summary>
|
||||
private static void PlaceHelpButton(UITechTree window, RectTransform rect, RectTransform root)
|
||||
{
|
||||
Text caption = window.tabButtonText0;
|
||||
RectTransform captionRect = caption != null ? caption.rectTransform : null;
|
||||
|
||||
if (captionRect != null && captionRect.parent != null)
|
||||
if (caption != null)
|
||||
{
|
||||
RectTransform captionRect = caption.rectTransform;
|
||||
rect.SetParent(captionRect.parent, false);
|
||||
rect.anchorMin = captionRect.anchorMin;
|
||||
rect.anchorMax = captionRect.anchorMax;
|
||||
rect.pivot = captionRect.pivot;
|
||||
Vector3 position = captionRect.anchoredPosition3D;
|
||||
rect.anchoredPosition3D = new Vector3(
|
||||
position.x,
|
||||
position.y - captionRect.rect.height - HelpButtonGap,
|
||||
position.z);
|
||||
rect.localScale = Vector3.one;
|
||||
return;
|
||||
rect.anchoredPosition3D = captionRect.anchoredPosition3D -
|
||||
new Vector3(0f, captionRect.rect.height + 4f, 0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
UIUtil.NormalizeRectWithBottomLeft(rect, 24f, 24f, window.transform);
|
||||
}
|
||||
|
||||
rect.SetParent(root, false);
|
||||
rect.anchorMin = new Vector2(0f, 0f);
|
||||
rect.anchorMax = new Vector2(0f, 0f);
|
||||
rect.pivot = new Vector2(0f, 0f);
|
||||
rect.anchoredPosition3D = new Vector3(HelpButtonLeftFallback, HelpButtonBottomFallback, 0f);
|
||||
rect.localScale = Vector3.one;
|
||||
RefreshText();
|
||||
clone.SetActive(true);
|
||||
}
|
||||
|
||||
private static Transform FindTipsButtonPrefab()
|
||||
public static void RefreshText()
|
||||
{
|
||||
UIGalaxySelect galaxySelect = UIRoot.instance != null ? UIRoot.instance.galaxySelect : null;
|
||||
Transform sandboxToggle = galaxySelect?.sandboxToggle != null
|
||||
? galaxySelect.sandboxToggle.transform
|
||||
: null;
|
||||
Transform container = sandboxToggle != null ? sandboxToggle.parent : null;
|
||||
return container != null ? container.Find("tip-button") : null;
|
||||
if (_helpButton == null) return;
|
||||
_helpButton.tips.tipTitle = Localization.UnlockDowngradeTechWithKeyModifiers.Translate();
|
||||
_helpButton.tips.tipText = Localization.TechModifierHelpBody.Translate();
|
||||
_helpButton.UpdateTip();
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.gameObject.SetActive(false);
|
||||
Object.Destroy(_helpButton.gameObject);
|
||||
}
|
||||
|
||||
_window = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,8 @@ namespace CheatEnabler.Patches.Tech;
|
||||
/// <summary>
|
||||
/// Upgrade side - unlock techs by clicking them with a key-modifier held while downgrade mode is off.
|
||||
///
|
||||
/// <see cref="UnlockTechRecursive"/> mirrors the built-in <see cref="GamePatch.UnlockTech"/>
|
||||
/// implementation so the reference behaviour is reproduced exactly: prerequisites are unlocked
|
||||
/// <see cref="UnlockTechRecursive"/> preserves the previous modifier-click upgrade behavior. The
|
||||
/// prerequisites are unlocked
|
||||
/// recursively (<c>PreTechs</c> / <c>PreTechsImplicit</c>, driven by <c>PreTechsMax</c>), recipes are
|
||||
/// unlocked on level 0, every level calls <c>UnlockTechFunction</c>, tech awards are granted, the hash
|
||||
/// counters are maintained and <c>NotifyTechUnlock</c> plus <c>RegFeatureKey(1000100)</c> are fired.
|
||||
|
||||
Reference in new issue
Block a user