Files
bd2/plugins/BetterExperience/Life/LifeBatchEdit.cs
T

369 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using BD2.GameNames;
using FieldEvent.Common;
using FieldEvent.Life;
using FieldEvent.Life.Chunk;
using HarmonyLib;
using Proto.Design.common;
using Proto.Net;
using UnityEngine;
using UnityEngine.EventSystems;
using TextComponent = BD2.GameSdk.Component;
namespace Bd2BetterExperience.Life;
// The farm editor's multi-select can only move the selection. This module
// gives it the single selection's rotate and remove buttons: rotate turns the
// whole selection a quarter turn about its centre, remove takes every
// selected object off the farm after one confirmation.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal sealed class LifeBatchEdit : IModule
{
private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const int ItemObject = 1, BuildingObject = 3, DecorationObject = 4, ExchangeItem = 64;
private const int BelowMinimumText = 160079, InventoryFullText = 160074;
private static Group group;
public string Id => "LifeBatchEdit";
public string Description => "Rotate and remove a multi-selection in the farm editor.";
public void Install(Harmony harmony)
{
Type ui = typeof(AvatarLifeHousingEditUI_EditUI);
harmony.Patch(Method(ui, "SetMultipleSelectedLPOs"), postfix: Hook(nameof(Selected)));
harmony.Patch(Method(ui, "ClearMultiState"), postfix: Hook(nameof(Cleared)));
harmony.Patch(Method(ui, "OnClickUI"), prefix: Hook(nameof(Click)));
harmony.Patch(Method(ui, "OnDragMultiple"), prefix: Hook(nameof(Drag)));
harmony.Patch(Method(ui, "OnClickConfirmMulti"), prefix: Hook(nameof(Confirm)));
harmony.Patch(Method(ui, "OnClickCancelMulti"), prefix: Hook(nameof(Cancel)));
}
private static MethodInfo Method(Type owner, string name) =>
owner.GetGameMethod(name, Fields | BindingFlags.DeclaredOnly) ?? throw new MissingMethodException(owner.Name, name);
private static HarmonyMethod Hook(string name) => new(typeof(LifeBatchEdit), name);
private static T Get<T>(object owner, string name) => (T)(owner.GetType().GetGameField(name, Fields) ??
throw new MissingFieldException(owner.GetType().Name, name)).GetValue(owner);
private static void Set(object owner, string name, object value) => (owner.GetType().GetGameField(name, Fields) ??
throw new MissingFieldException(owner.GetType().Name, name)).SetValue(owner, value);
private static object Call(object owner, string name, params object[] arguments) =>
Method(owner.GetType(), name).Invoke(owner, arguments);
private static string Text(string key) => TextComponent.Translatable(key).GetString();
// Native multi-select state, read straight from the editor.
private sealed class Group(AvatarLifeHousingEditUI_EditUI ui)
{
internal AvatarLifeHousingEditUI_EditUI UI { get; } = ui;
internal List<LifePlaceableObject> Objects => Get<List<LifePlaceableObject>>(UI, "_multiSelectedLPOs");
internal List<PlacementData> Originals => Get<List<PlacementData>>(UI, "_multiOriginalPlacements");
internal List<Vector2Int> Offsets => Get<List<Vector2Int>>(UI, "_multiRelativeCellOffsets");
internal LifeChunkController Chunks => Get<LifeChunkController>(UI, "_chunkController");
internal AvatarLifeHousingEditUI Parent => Get<AvatarLifeHousingEditUI>(UI, "_parentUI");
internal Vector2Int Center { get => Get<Vector2Int>(UI, "_currentGroupCenterCell"); set => Set(UI, "_currentGroupCenterCell", value); }
// Each object's rotation once the quarter turns are applied; while it
// matches the originals the game's own move code still applies.
internal List<int> Rotations { get; } = [];
internal bool Turned { get; set; }
}
private static void Selected(AvatarLifeHousingEditUI_EditUI __instance)
{
group = null;
try
{
var current = new Group(__instance);
if (current.Chunks == null || current.Objects.Count == 0) return;
current.Rotations.AddRange(current.Originals.Select(placement => placement.rotation));
group = current;
ButtonOnOffComponent rotate = Get<ButtonOnOffComponent>(__instance, "_rotateBtn");
rotate.gameObject.SetActive(true);
rotate.Set(current.Objects.Any(item => item != null && item.RotationType > RotationType.NoRotation));
// The removal buttons have no disabled look (Set(false) hides them),
// so the one shown stays enabled and a refusal explains itself on click.
RemoveButton(__instance, current.Objects).Set(true);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit selection: " + error); }
}
// The game's own button for removing this kind of object: put away for
// items, demolish for buildings, delete for decorations. A mixed
// selection uses demolish.
private static ButtonOnOffComponent RemoveButton(AvatarLifeHousingEditUI_EditUI ui, IList<LifePlaceableObject> objects)
{
int[] types = [.. objects.Select(item => item?.DBInfo == null ? 0 : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId)?.ObjectType ?? 0).Distinct()];
return Get<ButtonOnOffComponent>(ui, types.Length != 1 ? "_demolishBtn" : types[0] switch
{
ItemObject => "_invenBtn",
DecorationObject => "_deleteBtn",
_ => "_demolishBtn",
});
}
private static void Cleared(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI == __instance) group = null;
}
private static bool Click(AvatarLifeHousingEditUI_EditUI __instance, GameObject __0, ref bool __result)
{
if (group?.UI != __instance || __0 == null || !Get<bool>(__instance, "_isMultiMode")) return true;
try
{
if (__0 == Get<ButtonOnOffComponent>(__instance, "_rotateBtn").gameObject) { Rotate(group); __result = true; return false; }
if (__0 == RemoveButton(__instance, group.Objects).gameObject) { Remove(group); __result = true; return false; }
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit click: " + error); __result = true; return false; }
return true;
}
// Quarter turn clockwise. Footprints turn about their anchors through
// ApplyRotationOrFlip (x, z) -> (z, -x), so the anchors' offsets from the
// group centre turn the same way and the layout stays rigid.
private static void Rotate(Group current)
{
GroundChunkManager chunks = current.Chunks.GetChunkManager();
if (chunks == null) return;
List<Vector2Int> offsets = current.Offsets;
var turned = offsets.Select(offset => new Vector2Int(offset.y, -offset.x)).ToList();
foreach (Vector2Int offset in turned)
{
Vector2Int cell = current.Center + offset;
if (!chunks.GetCellAtWorldCell(cell.x, cell.y).isValid) { UIManager.OpenBarNotice(Text("life.batch.rotate_outside"), false, null); return; }
}
List<LifePlaceableObject> objects = current.Objects;
for (int i = 0; i < objects.Count; i++)
{
offsets[i] = turned[i];
LifePlaceableObject item = objects[i];
if (item != null && item.RotationType > RotationType.NoRotation) current.Rotations[i] = item.GetNextRotation(current.Rotations[i]);
}
current.Turned = true;
Get<IndexedCommonSoundEmitter>(current.UI, "_moveCellSoundEmitter")?.PlayManualIndexiedCommonSound();
Show(current, chunks);
}
// The game's drag, with the group's own rotations instead of the originals.
private static bool Drag(AvatarLifeHousingEditUI_EditUI __instance, PointerEventData __0)
{
if (group?.UI != __instance || !group.Turned) return true;
try
{
var world = (Vector3)Call(__instance, "ScreenToWorldPosition", (Vector3)__0.position);
if (world == Vector3.zero) return false;
var center = (Vector2Int)Call(__instance, "WorldPositionToWorldCellDirect", world);
if (center == group.Center) return false;
GroundChunkManager chunks = group.Chunks.GetChunkManager();
if (chunks == null) return false;
foreach (Vector2Int offset in group.Offsets)
{
Vector2Int cell = center + offset;
if (!chunks.GetCellAtWorldCell(cell.x, cell.y).isValid) return false;
}
Get<IndexedCommonSoundEmitter>(__instance, "_moveCellSoundEmitter")?.PlayManualIndexiedCommonSound();
group.Center = center;
Show(group, chunks);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit drag: " + error); }
return false;
}
// Places every object at the group centre with its current rotation and
// checks the result as OnDragMultiple does.
private static void Show(Group current, GroundChunkManager chunks)
{
List<LifePlaceableObject> objects = current.Objects;
List<PlacementData> originals = current.Originals;
List<Vector2Int> offsets = current.Offsets;
for (int i = 0; i < objects.Count; i++)
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], false, originals[i].rotation, 0);
bool valid = true;
var occupied = new HashSet<long>();
for (int i = 0; i < objects.Count; i++)
{
Vector2Int cell = current.Center + offsets[i];
CellInfo anchor = chunks.GetCellAtWorldCell(cell.x, cell.y);
int rotation = current.Rotations[i];
LifePlaceableObject item = objects[i];
item.transform.position = chunks.GetCellWorldPosition(anchor.chunkId, anchor.localX, anchor.localY, item, rotation);
item.ApplyVisualRotation(rotation);
item.UpdatePlacementPreview(chunks, anchor, rotation);
if (!(bool)Call(current.UI, "CheckPlacementValidForLPO", chunks, item, anchor, rotation)) valid = false;
if (valid && !(bool)Call(current.UI, "CollectOccupiedWorldCells", chunks, item, anchor, rotation, occupied)) valid = false;
}
for (int i = 0; i < objects.Count; i++)
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], true, originals[i].rotation, objects[i].LpoId);
Set(current.UI, "_isCurrentPlacementValid", valid);
Get<ButtonOnOffComponent>(current.UI, "_checkBtn")?.Set(valid);
Call(current.UI, "UpdateEditMenuPositionMulti");
}
// OnClickConfirmMulti with the group's rotations. A turned group no longer
// moves by one shared delta, so it saves every object's own position.
private static bool Confirm(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI != __instance || !group.Turned) return true;
Group current = group;
try
{
if (!Get<bool>(__instance, "_isCurrentPlacementValid")) return false;
LifeChunkController controller = current.Chunks;
GroundChunkManager chunks = controller?.GetChunkManager();
if (chunks == null) return false;
List<LifePlaceableObject> objects = current.Objects;
List<PlacementData> originals = current.Originals;
for (int i = 0; i < objects.Count; i++)
{
if (objects[i] == null || objects[i].IsTemporaryBuilding) continue;
chunks.SetCellsOccupied(originals[i].chunkId, originals[i].localCellX, originals[i].localCellY, objects[i], false, originals[i].rotation, 0);
}
for (int i = 0; i < objects.Count; i++)
{
if (objects[i] == null) continue;
Vector2Int cell = current.Center + current.Offsets[i];
objects[i].HidePlacementPreview();
new ConfirmPlacementEvent(objects[i], originals[i], chunks.GetCellAtWorldCell(cell.x, cell.y), current.Rotations[i], null, true).Send();
}
var saved = new List<LifePlaceableObject>(objects);
var keys = saved.Select(item => item?.DBInfo != null ? new PlacedObjectKey(item.ChunkIDDBInfo, item.DBInfo.ObjectId, item.DBInfo.X, item.DBInfo.Y) : default).ToList();
bool delta = LifePacket.UseDeltaPositionSave;
LifePacket.UseDeltaPositionSave = false;
try { LifePacket.SendLifeWorldObjectPositionSave(saved, () => controller.ReKeyPlacedObjects(saved, keys)); }
finally { LifePacket.UseDeltaPositionSave = delta; }
AvatarLifeHousingEditUI parent = current.Parent;
if (parent != null) { parent.RefreshBuildList(); parent.ClearSelectionHighlight(); }
Call(__instance, "ClearMultiState");
__instance.SetActive(false);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit confirm: " + error); }
return false;
}
// Cancel restores positions; turn the objects back before it does.
private static void Cancel(AvatarLifeHousingEditUI_EditUI __instance)
{
if (group?.UI != __instance || !group.Turned) return;
try
{
List<LifePlaceableObject> objects = group.Objects;
List<PlacementData> originals = group.Originals;
for (int i = 0; i < objects.Count; i++) if (objects[i] != null) objects[i].ApplyVisualRotation(originals[i].rotation);
}
catch (Exception error) { Plugin.Log?.LogWarning("Life batch edit cancel: " + error); }
}
// The single selection's delete rules, applied to the whole selection:
// only placed items, buildings and decorations, never below a group's
// minimum count, and never refunding past an item's stack limit.
private static bool Removable(IList<LifePlaceableObject> objects, out int notice)
{
notice = 0;
var removed = new Dictionary<LifeObjectGroupTable, int>();
var refunds = new Dictionary<int, int>();
foreach (LifePlaceableObject item in objects)
{
LifeObjectGroupTable table = item == null || item.IsTemporaryBuilding || item.DBInfo == null ? null : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId);
if (table == null || table.ObjectType is not (ItemObject or BuildingObject or DecorationObject)) return false;
removed[table] = removed.TryGetValue(table, out int count) ? count + 1 : 1;
if (table.ObjectType != BuildingObject) continue;
LifeBuildingObjectTable building = LifeInfo.GetLifeBuildingObjectTable(table.Id);
if (building == null) continue;
for (int i = 0; i < building.RequireItemType.Count; i++)
{
if (building.RequireItemType[i] == ExchangeItem) continue;
int id = building.RequireItemId[i];
refunds[id] = (refunds.TryGetValue(id, out int total) ? total : 0) + building.RequireItemCount[i];
}
}
foreach (KeyValuePair<LifeObjectGroupTable, int> pair in removed)
if (pair.Key.MinCount > 0 && LifePacket.GetLifeWorldObjectDbList(pair.Key.Id).Count - pair.Value < pair.Key.MinCount) { notice = BelowMinimumText; return false; }
foreach (KeyValuePair<int, int> pair in refunds)
if (LifePacket.GetItemInfoCount(pair.Key) + pair.Value > LifeInfo.GetLifeItemTable(pair.Key).StackCount) { notice = InventoryFullText; return false; }
return true;
}
private static void Remove(Group current)
{
var objects = current.Objects.Where(item => item != null).ToList();
if (objects.Count == 0) return;
if (!Removable(objects, out int notice))
{
UIManager.OpenBarNotice(notice != 0 ? LocalTextInfo.GetText(notice) : Text("life.batch.remove_blocked"), false, null);
return;
}
string title = string.Format(CultureInfo.CurrentCulture, Text("life.batch.remove_name"), objects.Count);
LifePlaceableObject[] returned = [.. objects.Where(item => Table(item)?.ObjectType is ItemObject or BuildingObject)];
if (returned.Length == 0)
{
// Decorations give nothing back; the game's own delete warning says so.
UIManager.AddUI<AvatarLifeItemDeletePopupUI>(popup =>
{
popup.SetUI(title, () => RemoveAll(current, objects));
// One confirmation covers the whole batch, so never offer to skip it.
Get<ButtonOnOffComponent>(popup, "_todayOnOffButton")?.gameObject.SetActive(false);
});
return;
}
UIManager.AddUI<AvatarLifeBuildDeletePopupUI>(popup => ShowReturns(popup, title, returned, () => RemoveAll(current, objects)));
}
private static LifeObjectGroupTable Table(LifePlaceableObject item) =>
item == null || item.DBInfo == null ? null : LifeInfo.GetLifeObjectGroupTable(item.DBInfo.ObjectId);
// The game's demolish popup, filled with everything the batch gives back:
// each building's materials and each put-away item, totalled per kind.
private static void ShowReturns(AvatarLifeBuildDeletePopupUI popup, string title, IList<LifePlaceableObject> returned, Action confirm)
{
LifePlaceableObject first = returned[0];
popup.SetUI(first.DBInfo.ObjectId, first.DBInfo.Index, confirm);
var totals = new Dictionary<(Define_LifeObjectType Kind, int Type, int Id), int>();
void add(Define_LifeObjectType kind, int type, int id, int count) =>
totals[(kind, type, id)] = (totals.TryGetValue((kind, type, id), out int total) ? total : 0) + count;
string info = LocalTextInfo.GetText(160073);
var notes = new HashSet<int>();
foreach (LifePlaceableObject item in returned)
{
LifeObjectGroupTable table = Table(item);
if (table.ObjectType == ItemObject) { add(Define_LifeObjectType.LifeCraftingObject, 0, table.Id, 1); continue; }
LifeBuildingObjectTable building = LifeInfo.GetLifeBuildingObjectTable(table.Id);
if (building == null) continue;
for (int i = 0; i < building.RequireItemType.Count; i++)
add(Define_LifeObjectType.LifeBuildingObject, building.RequireItemType[i], building.RequireItemId[i], building.RequireItemCount[i]);
// Same warnings as demolishing one helper house that is in use.
if (building.FunctionType == 101 && LifePacket.GetLifeHelperDBInfo(item.DBInfo.Index) != null) notes.Add(160262);
else if (building.FunctionType == 101 && LifePacket.GetLifeHelperGachaDBInfo(item.DBInfo.Index) != null) notes.Add(160254);
}
foreach (int note in notes.OrderBy(note => note)) info += "\n\n" + LocalTextInfo.GetText(note);
int index = 0;
foreach (KeyValuePair<(Define_LifeObjectType Kind, int Type, int Id), int> entry in totals)
Call(popup, "AddIcon", index++, entry.Key.Kind, entry.Key.Type, entry.Key.Id, entry.Value);
List<AvatarLifeBuildDeletePopupUI_ScrollItem> icons = Get<List<AvatarLifeBuildDeletePopupUI_ScrollItem>>(popup, "_itemList");
for (int i = index; i < icons.Count; i++) icons[i].gameObject.SetActive(false);
Get<TMPro.TMP_Text>(popup, "_textName").SetText(title, true);
Get<TMPro.TMP_Text>(popup, "_textInfo").text = info;
}
private static void RemoveAll(Group current, List<LifePlaceableObject> objects)
{
AvatarLifeHousingEditUI parent = current.Parent;
// Put the selection back where it was, then remove one object at a
// time so each unplace finishes before the next starts.
Call(current.UI, "OnClickCancelMulti", false);
void Next(int index)
{
while (index < objects.Count && objects[index] == null) index++;
if (index >= objects.Count) { if (parent != null) parent.RefreshBuildList(); return; }
new DeletePlacementEvent(objects[index], () => Next(index + 1)).Send();
}
Next(0);
}
}