diff --git a/Assets/Scripts/Editor/InventoryGridParityCapture.cs b/Assets/Scripts/Editor/InventoryGridParityCapture.cs index 2437f3280..1f476b020 100644 --- a/Assets/Scripts/Editor/InventoryGridParityCapture.cs +++ b/Assets/Scripts/Editor/InventoryGridParityCapture.cs @@ -6,7 +6,9 @@ using System.Reflection; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; +using UnityEngine.EventSystems; using UnityEngine.UI; +using UniRx; using UniRx.Triggers; using GameCult.Caching; using int2 = CultMath.int2; @@ -14,10 +16,11 @@ using int2 = CultMath.int2; // The parity harness of the inventory grid (map IG): the sheet sprites are the oracle and InventoryGrid is judged against them. // Every check logs one "[InventoryGridParity]" line, and the run exits 0 when every bound holds, 1 otherwise. // -// Unity -batchmode -projectPath -executeMethod InventoryGridParityCapture.Run [-pngOut ] [-mutant ] [-hullOnly] [-recordsOut ] -logFile +// Unity -batchmode -projectPath -executeMethod InventoryGridParityCapture.Run [-pngOut ] [-mutant ] [-hullOnly] [-recordsIn ] -logFile // -// -recordsOut writes the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's -// rect), read off the panel as it stands. The golden is a run output, kept outside git; Soul regenerates it from the first commit of the cut. +// -recordsIn is the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's +// rect) that the first commit of the switch cut wrote from the sprite panels (`-recordsOut`, which exists only at that commit); the live +// panels must equal it. The golden is a run output, kept outside git; Soul regenerates it from that commit. // // Needs a GPU device; do not pass -nographics or -quit. A mutant is one named perturbation of the new path (see Mutants); the // run must then fail a bound. @@ -41,12 +44,12 @@ public static class InventoryGridParityCapture private static double _thermalWorst, _thermalHullWorst; private static string _mutant = ""; - private static string _pngOut, _recordsOut; + private static string _pngOut, _recordsIn; private static readonly List Breaches = new List(); public static readonly string[] Mutants = { - "rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1", "flip-ignored", "pipe-width-minus" + "rule-inset-2", "softness-1.25", "fill-inset-2.5", "arms-0", "icon-multiplier-1", "flip-ignored", "pipe-width-minus", "ghost-full-alpha" }; private static void Log(string line) => Debug.Log("[InventoryGridParity] " + line); @@ -58,7 +61,8 @@ public static class InventoryGridParityCapture var args = Environment.GetCommandLineArgs(); string Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; } _pngOut = Arg("-pngOut"); - _recordsOut = Arg("-recordsOut"); + _recordsIn = Arg("-recordsIn"); + if (Arg("-recordsOut") != null) throw new InvalidOperationException("-recordsOut writes the golden from the sprite panels and exists only at the first commit of the switch cut."); _mutant = Arg("-mutant") ?? ""; if (Arg("-atlasBound") != null) AtlasBound = int.Parse(Arg("-atlasBound")); if (Arg("-thermalBound") != null) ThermalHullBound = ThermalBound = double.Parse(Arg("-thermalBound"), System.Globalization.CultureInfo.InvariantCulture); @@ -73,8 +77,8 @@ public static class InventoryGridParityCapture if (!hullOnly) Masked(); if (!hullOnly) LateLook(); if (!hullOnly) AlphaAndClip(); - if (Array.IndexOf(args, "-noHull") < 0) Hull(); - if (_recordsOut != null) WriteGolden(); + if (Array.IndexOf(args, "-noHull") < 0) { Hull(); Interact(); } + if (Array.IndexOf(args, "-noHull") < 0) CheckBranchCounts(); Log($"SUMMARY atlasWorst={_atlasWorst} hullWorst={_hullWorst} thermalWorstRms={_thermalWorst:F4} thermalHullRms={_thermalHullWorst:F4} maskedWorst={_maskedWorst} alphaClipWorst={_alphaClipWorst} bounds atlas={AtlasBound} thermal={ThermalBound} thermalHull={ThermalHullBound}"); if (Breaches.Count > 0) @@ -871,26 +875,6 @@ public static class InventoryGridParityCapture HullStateCheck(rig, fixture, state, width); } - // Every cell's record, read back from the sprite cells: the mask from the sprite name's index, plus the two colours. - private static Dictionary ReadRecords(InventoryPanel panel, bool thermal) - { - var records = new Dictionary(); - foreach (var (v, cell) in panel.CellInstances) - { - var iconName = cell.Icon.sprite.name; - var iconIndex = int.Parse(iconName.Substring(iconName.LastIndexOf('_') + 1)); - var bgName = cell.Background.sprite.name; - var bgIndex = int.Parse(bgName.Substring(bgName.LastIndexOf('_') + 1)); - records[v] = new CellRecord - { - Mask = (byte) (bgIndex & 255), Present = true, - Item = !thermal && iconIndex >= 256, Conductivity = thermal ? (byte) (iconIndex & 15) : (byte) 0, - Icon = cell.Icon.color, Background = cell.Background.color - }; - } - return records; - } - // The scene's own panel, copied into the rig page as it is authored: nothing about its rect, cell size, start corner, Flip or // multiplier is set here. The scene is opened additively for the copy and closed. private static GameObject SceneClone(string path, RectTransform page) @@ -927,24 +911,14 @@ public static class InventoryGridParityCapture panelRect.anchoredPosition = Vector2.zero; panelRect.sizeDelta = new Vector2(1200, 900); } - var content = (RectTransform) panel.Grid.transform; - var fitter = content.GetComponent(); var iconMultiplier = panel.NodePrototype.GetComponent().Icon.pixelsPerUnitMultiplier; - // The thermal branch subscribes to a click trigger the edit-mode instance of the prefab does not carry. - var prototypeCell = panel.NodePrototype.GetComponent(); - if ((state.Thermal || state.Cargo) && !prototypeCell.PointerClickTrigger) prototypeCell.PointerClickTrigger = prototypeCell.gameObject.AddComponent(); - if (state.Cargo) - { - if (!prototypeCell.BeginDragTrigger) prototypeCell.BeginDragTrigger = prototypeCell.gameObject.AddComponent(); - if (!prototypeCell.DragTrigger) prototypeCell.DragTrigger = prototypeCell.gameObject.AddComponent(); - if (!prototypeCell.EndDragTrigger) prototypeCell.EndDragTrigger = prototypeCell.gameObject.AddComponent(); - if (!prototypeCell.PointerEnterTrigger) prototypeCell.PointerEnterTrigger = prototypeCell.gameObject.AddComponent(); - if (!prototypeCell.PointerExitTrigger) prototypeCell.PointerExitTrigger = prototypeCell.gameObject.AddComponent(); - } + var grid = panel.Grid; state.Setup?.Invoke(panel, fixture); if (state.Cargo) panel.Display(fixture.Ship.CargoBays.First()); else panel.Display(fixture.Ship, state.Hud, state.Thermal); - LayoutRebuilder.ForceRebuildLayoutImmediate(content); + MutateLook(panel, state); + // The container of the cells lays them out (the menu's Content sizes itself to them). + LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) grid.transform.parent); Canvas.ForceUpdateCanvases(); // The temperature display follows the first cell in Update, which edit mode never runs: run it once, without the labels, which @@ -954,38 +928,44 @@ public static class InventoryGridParityCapture panel.MinTempLabel = panel.MaxTempLabel = null; typeof(InventoryPanel).GetMethod("Update", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(panel, null); } - var records = ReadRecords(panel, state.Thermal); - var columns = panel.Grid.constraintCount; - var rows = (panel.CellInstances.Count + panel.EmptyCells.Count) / columns; - var cellSize = panel.Grid.cellSize.x; - var padding = panel.Grid.padding; - var orientation = panel.Grid.startCorner == GridLayoutGroup.Corner.UpperRight ? GridOrientation.UpperRight : GridOrientation.LowerLeft; - var cellRects = panel.CellInstances.ToDictionary(pair => pair.Key, pair => (RectTransform) pair.Value.transform); + var records = LiveRecords(grid); + var columns = grid.Width; + var rows = grid.Height; + var gridRect = grid.rectTransform; + CountBranches(fixture, panel, state, records); + CompareGolden(rig, state, panel, records, width); - if (width == 1920) RecordGolden(rig, state.Name, records, cellRects, panel.TemperatureDisplay && state.Name != "cargo" ? (RectTransform) panel.TemperatureDisplay.transform : null); - var old = rig.Render(); - - // New: the grid in the content's place over the same rect; the cells off. - foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false); - if (fitter) fitter.enabled = false; - panel.Grid.enabled = false; - var gridObject = new GameObject("Parity grid", typeof(RectTransform), typeof(CanvasRenderer)) { layer = panelObject.layer }; - var gridRect = (RectTransform) gridObject.transform; - gridRect.SetParent(content.parent, false); - gridRect.SetSiblingIndex(content.GetSiblingIndex()); - gridRect.anchorMin = content.anchorMin; - gridRect.anchorMax = content.anchorMax; - gridRect.pivot = content.pivot; - gridRect.anchoredPosition = content.anchoredPosition; - gridRect.sizeDelta = content.sizeDelta; - gridRect.localScale = content.localScale; - var grid = gridObject.AddComponent(); - Look(grid, iconMultiplier); - grid.Thermal = state.Thermal; - grid.Resize(columns, rows, cellSize, padding, state.Enemy && _mutant == "flip-ignored" ? GridOrientation.LowerLeft : orientation); - foreach (var (v, record) in records) grid.SetCell(v, record); + // The live panel as it draws. var fresh = rig.Render(); + // The oracle: the sheets' own sprite cells of the same records at the live cell rects, the grid hidden. + var cellRects = new Dictionary(); + var oracle = new Dictionary(); + foreach (var (v, record) in records) + { + var cell = panel.NodePrototype.Instantiate(); + // Under the grid's own object: in the same mask as the grid and outside the container's layout group (the menu's), which would + // move them. The grid is hidden by a clear vertex colour, not by disabling it: a disabled grid leaves the layout and the + // container collapses. + cell.transform.SetParent(grid.transform, false); + var rect = (RectTransform) cell.transform; + var at = grid.CellRect(v); + rect.anchorMin = rect.anchorMax = Vector2.zero; + rect.pivot = Vector2.zero; + rect.sizeDelta = at.size; + rect.position = gridRect.TransformPoint(at.min); + cell.Background.sprite = panel.NodeBackgroundTextures[record.Mask]; + cell.Background.color = record.Background; + cell.Icon.sprite = state.Thermal ? panel.ThermalTextures[record.Conductivity] : panel.NodeTextures[record.Mask + (record.Item ? 256 : 0)]; + cell.Icon.color = record.Icon; + oracle.Add(v, cell); + cellRects.Add(v, rect); + } + grid.color = Color.clear; + var old = rig.Render(); + grid.color = Color.white; + foreach (var cell in oracle.Values) cell.gameObject.SetActive(false); + // Judge the whole panel's pixels; cells whose sprite has a known authoring slip are judged outside its footprint. var camera = rig.Camera; Rect PixelRect(RectTransform rect) @@ -1067,7 +1047,7 @@ public static class InventoryGridParityCapture foreach (var (diff, v, where) in perCell.OrderByDescending(c => c.diff).Take(8)) { var r = records[v]; - Log($" worst cell {v.x},{v.y} {where}: diff {diff} mask {r.Mask} ({Convert.ToString(r.Mask, 2).PadLeft(8, '0')}) item {r.Item} icon {r.Icon} bg {r.Background} sprite {panel.CellInstances[v].Icon.sprite.name}/{panel.CellInstances[v].Background.sprite.name}"); + Log($" worst cell {v.x},{v.y} {where}: diff {diff} mask {r.Mask} ({Convert.ToString(r.Mask, 2).PadLeft(8, '0')}) item {r.Item} icon {r.Icon} bg {r.Background} sprite {oracle[v].Icon.sprite.name}/{oracle[v].Background.sprite.name}"); } } Log($"hull {state.Name} w={width} cells={records.Count} max8bitDiff={worst} at {worstAt} boundaryPixelsNotJudged={ties}" + (state.Thermal ? " (thermal: the pipes are a fit, judged by cell rms)" : "")); @@ -1093,17 +1073,17 @@ public static class InventoryGridParityCapture Log($"hull thermal w={width} worst cell rms={worstRms:F4}"); // The background layer of every thermal cell, icons hidden in both paths, judged by the atlas bound. - foreach (var cell in panel.CellInstances.Values) + foreach (var cell in oracle.Values) { cell.gameObject.SetActive(true); var hidden = cell.Icon.color; hidden.a = 0; cell.Icon.color = hidden; } - grid.gameObject.SetActive(false); + grid.color = Color.clear; var old2 = rig.Render(); - foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false); - grid.gameObject.SetActive(true); + foreach (var cell in oracle.Values) cell.gameObject.SetActive(false); + grid.color = Color.white; foreach (var (v, record) in records) { var hiddenRecord = record; @@ -1149,7 +1129,247 @@ public static class InventoryGridParityCapture ClearPage(rig); } - // ---- The golden ------------------------------------------------------------------------------------------------------ + // ---- Interaction: pointer events through the grid ---------------------------------------------------------------------- + + private static void Check(bool holds, string what) + { + Log((holds ? "ok " : "FAILED ") + "interact: " + what); + if (!holds) Breaches.Add("interact: " + what); + } + + private static Rect ScreenRect(Camera camera, RectTransform rect) + { + var corners = new Vector3[4]; + rect.GetWorldCorners(corners); + var a = RectTransformUtility.WorldToScreenPoint(camera, corners[0]); + var b = RectTransformUtility.WorldToScreenPoint(camera, corners[2]); + return Rect.MinMaxRect(Mathf.Min(a.x, b.x), Mathf.Min(a.y, b.y), Mathf.Max(a.x, b.x), Mathf.Max(a.y, b.y)); + } + + // Two prefab panels (equipment and cargo) and a drag parent on one page, an event system, and events sent to the grids with + // ExecuteEvents at cell centres: what the input module would send, with the canvas' raycaster as the event module. + private static void Interact() + { + using var fixture = Fixture.Build(); + using var rig = new Rig(2560); + var canvas = rig.Page.GetComponentInParent(); + var raycaster = canvas.gameObject.AddComponent(); + var eventSystem = new GameObject("Parity event system", typeof(EventSystem)).GetComponent(); + var prefab = AssetDatabase.LoadAssetAtPath(PrefabPath); + var settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset"); + var dragParent = (RectTransform) new GameObject("Drag parent", typeof(RectTransform)) { layer = rig.Page.gameObject.layer }.transform; + dragParent.SetParent(rig.Page, false); + + InventoryPanel MakePanel(float x) + { + var go = (GameObject) PrefabUtility.InstantiatePrefab(prefab, rig.Page); + // Edit mode refuses to reparent a prefab instance's child, which the drag ghost does. + PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); + var panel = go.GetComponent() ?? go.GetComponentInChildren(true); + panel.GameManager = fixture.Manager; + if (!panel.Settings) panel.Settings = settings; + panel.DragParent = dragParent; + panel.NodePrototype.gameObject.SetActive(false); + var rect = (RectTransform) panel.transform; + rect.anchorMin = rect.anchorMax = new Vector2(.5f, .5f); + rect.pivot = new Vector2(.5f, .5f); + rect.anchoredPosition = new Vector2(x, 0); + rect.sizeDelta = new Vector2(800, 900); + dragParent.SetAsLastSibling(); + return panel; + } + + PointerEventData Pointer(GameObject target, Vector2 position, Vector2? press = null) + { + var hit = new RaycastResult { gameObject = target, module = raycaster }; + return new PointerEventData(eventSystem) + { + position = position, pressPosition = press ?? position, button = PointerEventData.InputButton.Left, + pointerCurrentRaycast = hit, pointerPressRaycast = hit, pointerEnter = target, pointerPress = target, pointerDrag = target + }; + } + Vector2 ScreenOf(InventoryGrid grid, Vector2 gridLocal) => RectTransformUtility.WorldToScreenPoint(rig.Camera, grid.rectTransform.TransformPoint(gridLocal)); + Vector2 Centre(InventoryGrid grid, int2 v) => ScreenOf(grid, grid.CellRect(v).center); + void Layout(InventoryPanel panel) + { + LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) panel.Grid.transform.parent); + Canvas.ForceUpdateCanvases(); + } + Color32[] RenderAll() => rig.Render(); + + try + { + var ship = fixture.Ship; + var hull = fixture.Hull; + var equipment = MakePanel(-400); + var cargoPanel = MakePanel(500); + equipment.Display(ship); + Layout(equipment); + var grid = equipment.Grid; + // The smallest equipped item whose cells are all on the screen with a margin (the hull is taller than the page). + bool OnScreen(int2 v) + { + var r = grid.CellRect(v); + var a = ScreenOf(grid, r.min); + var b = ScreenOf(grid, r.max); + return Mathf.Min(a.x, b.x) > 40 && Mathf.Max(a.x, b.x) < rig.Width - 40 && Mathf.Min(a.y, b.y) > 40 && Mathf.Max(a.y, b.y) < rig.Height - 40; + } + var equipped = ship.Equipment.Where(e => e.EquippableItem != null) + .Where(e => hull.Shape.Inset(e.Data.Shape, e.Position, e.EquippableItem.Rotation).Coordinates.All(OnScreen)) + .OrderBy(e => e.Data.Shape.Coordinates.Length).First(); + var item = equipped.EquippableItem; + var occupancy = hull.Shape.Inset(equipped.Data.Shape, equipped.Position, item.Rotation); + var itemCells = occupancy.Coordinates.ToArray(); + var other = hull.Shape.AllCoordinates.First(c => hull.Shape[c] && !itemCells.Any(i => i.Equals(c))); + Check(grid.GetComponent() && grid.GetComponent(), "an interactive panel's grid carries the triggers its subscriptions added"); + + // Clicks: (v, 1), then (v, 2); a press on one cell released on another gives none. + var clicks = new List<(int2 cell, int count)>(); + using (equipment.OnClickAsObservable().Subscribe(e => clicks.Add((e.data.Position, e.clickCount)))) + { + var a = itemCells[0]; + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, a)), ExecuteEvents.pointerClickHandler); + Check(clicks.Count == 1 && clicks[0].cell.Equals(a) && clicks[0].count == 1, $"a click on cell {a.x},{a.y} gives ({a.x},{a.y}), 1"); + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, a)), ExecuteEvents.pointerClickHandler); + Check(clicks.Count == 2 && clicks[1].cell.Equals(a) && clicks[1].count == 2, "a second click on it gives its count 2"); + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, Centre(grid, other), Centre(grid, a)), ExecuteEvents.pointerClickHandler); + Check(clicks.Count == 2, "a press on one cell released on another gives no click"); + } + + // The selection highlight: every item cell draws GetColor(v, true), and the next refresh clears it. + equipment.SetHighlight(item, true); + var highlighted = itemCells.All(v => Pack(grid.RecordAt(v).Icon) == Pack(equipment.GetColor(v, true))); + var distinct = itemCells.All(v => Pack(equipment.GetColor(v, true)) != Pack(equipment.GetColor(v))); + Check(highlighted && distinct, "SetHighlight(item, true) draws GetColor(v, true) on each of the item's cells, which differs from GetColor(v)"); + equipment.RefreshCells(); + Check(itemCells.All(v => Pack(grid.RecordAt(v).Icon) == Pack(equipment.GetColor(v))), "the next RefreshCells clears the highlight"); + + // The panel whose item is dragged over the other panel: a begin drag on an item cell shows the ghost; the pointer moving over a + // fitting cell of the cargo panel sets its FakeOccupancy, and leaving clears it. + var bay = ship.CargoBays.First(); + foreach (var stored in bay.Occupancy.Cast().Where(i => i != null).Distinct().ToArray()) bay.Remove(stored); + cargoPanel.Display(bay); + Layout(cargoPanel); + var cargoGrid = cargoPanel.Grid; + var offset = equipped.Position - itemCells[0]; + var target = bay.Data.InteriorShape.AllCoordinates.FirstOrDefault(h => bay.Data.InteriorShape[h] && bay.ItemFits(item, h + offset)); + var fits = bay.Data.InteriorShape[target] && bay.ItemFits(item, target + offset); + Check(fits, $"an equipped item fits the emptied bay (item {equipped.Data.Name}, shape {equipped.Data.Shape.Width}x{equipped.Data.Shape.Height}, bay {bay.Data.InteriorShape.Width}x{bay.Data.InteriorShape.Height})"); + + if (_mutant == "ghost-full-alpha") equipment.DragGhost.color = Color.white; + var press = Centre(grid, itemCells[0]); + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press), ExecuteEvents.beginDragHandler); + var ghost = equipment.DragGhost; + Check(ghost.gameObject.activeSelf && ghost.transform.parent == dragParent, $"a begin drag on an item cell activates DragGhost under DragParent (active {ghost.gameObject.activeSelf}, parent {ghost.transform.parent?.name}, DragParent {dragParent.name})"); + var min = new int2(itemCells.Min(c => c.x), itemCells.Min(c => c.y)); + var present = Enumerable.Range(0, ghost.Height).SelectMany(y => Enumerable.Range(0, ghost.Width).Select(x => new int2(x, y))).Count(c => ghost.RecordAt(c).Present); + Check(itemCells.All(v => ghost.RecordAt(v - min).Present) && present == itemCells.Length, $"the ghost holds the item's {itemCells.Length} cells and no other"); + Check(itemCells.All(v => equipment.IgnoreOccupancy?[v] ?? false), "the dragged item's cells are ignored (IgnoreOccupancy)"); + Check(fixture.Manager.DragObject is EquippedItemDragObject, "the drag protocol began with the item"); + + // Its rect is the union of the item cells' rects. + var union = itemCells.Select(v => PageRect(rig, grid.rectTransform.TransformPoint(grid.CellRect(v).min), grid.rectTransform.TransformPoint(grid.CellRect(v).max))).ToArray(); + var want = new[] { union.Min(r => r[0]), union.Min(r => r[1]), 0f, 0f }; + want[2] = union.Max(r => r[0] + r[2]) - want[0]; + want[3] = union.Max(r => r[1] + r[3]) - want[1]; + var rectGap = Worst(PageRect(rig, ghost.rectTransform), want); + Check(rectGap <= RectBound, $"the ghost's rect is the union of the item's cell rects (worst {rectGap:F5}, bound {RectBound}; ghost {string.Join(",", PageRect(rig, ghost.rectTransform))}, union {string.Join(",", want)})"); + + // Its pixels against the sprite cells of the same records at half alpha. + Canvas.ForceUpdateCanvases(); + var withGhost = RenderAll(); + ghost.gameObject.SetActive(false); + var excluded = new List(); + var oracle = new List(); + foreach (var v in itemCells) + { + var record = ghost.RecordAt(v - min); + var cell = equipment.NodePrototype.Instantiate(); + cell.transform.SetParent(rig.Page, false); + var rect = (RectTransform) cell.transform; + var at = ghost.CellRect(v - min); + rect.anchorMin = rect.anchorMax = Vector2.zero; + rect.pivot = Vector2.zero; + rect.sizeDelta = at.size; + rect.position = ghost.rectTransform.TransformPoint(at.min); + cell.Background.sprite = equipment.NodeBackgroundTextures[record.Mask]; + cell.Icon.sprite = equipment.NodeTextures[record.Mask + (record.Item ? 256 : 0)]; + Color Half(Color32 c) => new Color(c.r / 255f, c.g / 255f, c.b / 255f, c.a / 255f * .5f); + cell.Background.color = Half(record.Background); + cell.Icon.color = Half(record.Icon); + oracle.Add(cell.gameObject); + var iconMask = record.Mask + (record.Item ? 256 : 0); + if (record.Mask == 33 || iconMask == 33 || iconMask == 289 || record.Mask == 136 || iconMask == 392) excluded.Add(ScreenRect(rig.Camera, rect)); + } + var withOracle = RenderAll(); + foreach (var cell in oracle) UnityEngine.Object.DestroyImmediate(cell); + var ghostPixels = ScreenRect(rig.Camera, ghost.rectTransform); + var worstGhost = 0; + var litGhost = 0; + for (var y = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.yMin) - 2); y < Mathf.Min(rig.Height, Mathf.CeilToInt(ghostPixels.yMax) + 2); y++) + for (var x = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.xMin) - 2); x < Mathf.Min(rig.Width, Mathf.CeilToInt(ghostPixels.xMax) + 2); x++) + { + if (excluded.Any(r => x + .5f > r.xMin - 2 && x + .5f < r.xMax + 2 && y + .5f > r.yMin - 2 && y + .5f < r.yMax + 2)) continue; + worstGhost = Mathf.Max(worstGhost, MaxDifference(withGhost[y * rig.Width + x], withOracle[y * rig.Width + x])); + if (withOracle[y * rig.Width + x].r > 20) litGhost++; + } + Check(worstGhost <= AtlasBound && litGhost > 100, $"the ghost's pixels equal the oracle cells at half alpha (max channel diff {worstGhost}, bound {AtlasBound}, {litGhost} lit pixels judged, {excluded.Count} slip cells not judged, ghost px {ghostPixels})"); + if (_pngOut != null) + SaveSideBySide("interact-ghost.png", rig, withOracle, withGhost, new RectInt(Mathf.Max(0, (int) ghostPixels.xMin - 16), Mathf.Max(0, (int) ghostPixels.yMin - 16), (int) ghostPixels.width + 32, (int) ghostPixels.height + 32)); + ghost.gameObject.SetActive(true); + + // A drag moves the ghost by the pointer's delta. + var before = ghost.rectTransform.position; + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press + new Vector2(40, -25), press), ExecuteEvents.dragHandler); + var moved = ghost.rectTransform.position - before; + Check(Vector2.Distance(moved, new Vector2(40, -25)) < .01f && Mathf.Abs(moved.z) < 1e-4f, $"a drag moves the ghost by the pointer's delta (moved {moved})"); + + // Over a fitting cell of the other panel: FakeOccupancy; leaving it clears. + if (fits) + { + ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(cargoGrid.gameObject, Centre(cargoGrid, target)), ExecuteEvents.pointerMoveHandler); + Check(cargoPanel.FakeItem == item && cargoPanel.FakeOccupancy != null && cargoPanel.FakeOccupancy.Coordinates.Any(), "the pointer moving onto a fitting cell of the other panel sets its FakeOccupancy"); + ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(cargoGrid.gameObject, Centre(cargoGrid, target)), ExecuteEvents.pointerExitHandler); + Check(cargoPanel.FakeItem == null && cargoPanel.FakeOccupancy == null, "the pointer leaving it clears the FakeOccupancy"); + } + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press + new Vector2(40, -25), press), ExecuteEvents.endDragHandler); + Check(!ghost.gameObject.activeSelf && equipment.IgnoreOccupancy == null && fixture.Manager.DragObject == null, "an end drag deactivates the ghost and ends the drag"); + + // The thermal view: a click in the left toggle region of a cell toggles the left conductivity. + equipment.Display(ship, false, true); + Layout(equipment); + var thermal = hull.Shape.AllCoordinates.First(c => hull.Shape[c] && hull.Shape[new int2(c.x - 1, c.y)]); + var left = new int2(thermal.x - 1, thermal.y); + var wasOn = ship.HullConductivity[left.x, left.y].x; + var cell01 = grid.CellRect(thermal); + var inRegion = ScreenOf(grid, cell01.min + new Vector2(cell01.width * equipment.ThermalToggleRegionSize * .25f, cell01.height * .5f)); + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, inRegion), ExecuteEvents.pointerClickHandler); + var toggled = ship.HullConductivity[left.x, left.y].x != wasOn; + var drawn = ((grid.RecordAt(thermal).Conductivity & 8) != 0) == ship.HullConductivity[left.x, left.y].x; + Check(toggled && drawn, $"a thermal click at the left of cell {thermal.x},{thermal.y} toggles the left conductivity and draws it"); + ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, inRegion), ExecuteEvents.pointerClickHandler); + Check(ship.HullConductivity[left.x, left.y].x == wasOn, "a second thermal click restores it"); + + // A HUD panel is not interactive: its grid gets no trigger component. + var hud = SceneClone("Canvas/Gameplay/Hud Schematic/Inventory", rig.Page).GetComponent(); + hud.GameManager = fixture.Manager; + if (!hud.Settings) hud.Settings = settings; + hud.Display(ship, true); + Check(!hud.Interactive && hud.Grid.GetComponents().Length == 0, "a HUD panel (Interactive false) adds no trigger component to its grid"); + } + finally + { + UnityEngine.Object.DestroyImmediate(eventSystem.gameObject); + UnityEngine.Object.DestroyImmediate(raycaster); + } + } + + // ---- The live panel against the golden ----------------------------------------------------------------------------- + + // The bound on a cell rect or the temperature display's rect against the golden, in page canvas units. The shipped reading is 0 (rects + // are the same floats as the sprite panels', or within the float spacing near 1000, 6e-5), taken as 1e-4; mutant temperature-anchor-0 + // moves the display one cell, 8 units at the HUD's smallest cell. lodur:ruling:deterministic-bound-margin: sqrt(1e-4 x 8) = 0.028. + private const float RectBound = .028f; [Serializable] private sealed class GoldenCell { @@ -1168,44 +1388,129 @@ public static class InventoryGridParityCapture [Serializable] private sealed class Golden { public GoldenState[] states; } - private static readonly List GoldenStates = new List(); + private static Golden _golden; + + private static Dictionary LiveRecords(InventoryGrid grid) + { + var records = new Dictionary(); + for (var y = 0; y < grid.Height; y++) + for (var x = 0; x < grid.Width; x++) + if (grid.RecordAt(new int2(x, y)) is { Present: true } record) records[new int2(x, y)] = record; + return records; + } + + private static float[] PageRect(Rig rig, Vector3 a, Vector3 b) + { + var low = rig.Page.InverseTransformPoint(a); + var high = rig.Page.InverseTransformPoint(b); + return new[] { low.x, low.y, high.x - low.x, high.y - low.y }; + } private static float[] PageRect(Rig rig, RectTransform rect) { var corners = new Vector3[4]; rect.GetWorldCorners(corners); - var a = rig.Page.InverseTransformPoint(corners[0]); - var b = rig.Page.InverseTransformPoint(corners[2]); - return new[] { a.x, a.y, b.x - a.x, b.y - a.y }; + return PageRect(rig, corners[0], corners[2]); } private static uint Pack(Color32 c) => (uint) c.r << 24 | (uint) c.g << 16 | (uint) c.b << 8 | c.a; - private static void RecordGolden(Rig rig, string name, Dictionary records, Dictionary rects, RectTransform temperature) + private static float Worst(float[] a, float[] b) => a.Zip(b, (p, q) => Mathf.Abs(p - q)).Max(); + + // Every live record equals the golden's exactly (mask, present, item, conductivity, icon and background bytes), no other cell is + // present, and each cell rect and the temperature display's rect sit within RectBound. + private static void CompareGolden(Rig rig, HullState state, InventoryPanel panel, Dictionary records, int width) { - GoldenStates.Add(new GoldenState + if (_recordsIn == null) return; + _golden ??= JsonUtility.FromJson(File.ReadAllText(_recordsIn)); + var golden = _golden.states.FirstOrDefault(s => s.name == state.Name) ?? throw new InvalidOperationException("No golden state " + state.Name); + var grid = panel.Grid; + var expected = golden.cells.ToDictionary(c => new int2(c.x, c.y)); + var wrong = 0; + var worstRect = 0f; + foreach (var (v, cell) in expected) { - name = name, - cells = records.OrderBy(p => p.Key.y).ThenBy(p => p.Key.x).Select(p => new GoldenCell + var live = records.TryGetValue(v, out var found) ? found : default; + var same = records.ContainsKey(v) && live.Mask == cell.mask && live.Present == cell.present && live.Item == cell.item && + live.Conductivity == cell.conductivity && Pack(live.Icon) == cell.icon && Pack(live.Background) == cell.background; + if (!same && wrong++ < 6) Log($" golden {state.Name} cell {v.x},{v.y}: live mask {live.Mask} item {live.Item} cond {live.Conductivity} icon {Pack(live.Icon):x8} bg {Pack(live.Background):x8}, golden mask {cell.mask} item {cell.item} cond {cell.conductivity} icon {cell.icon:x8} bg {cell.background:x8}"); + var rect = grid.CellRect(v); + worstRect = Mathf.Max(worstRect, Worst(PageRect(rig, grid.rectTransform.TransformPoint(rect.min), grid.rectTransform.TransformPoint(rect.max)), cell.rect)); + } + var extra = records.Keys.Count(v => !expected.ContainsKey(v)); + var worstTemperature = 0f; + var temperature = "none"; + if (golden.temperature != null && golden.temperature.Length > 0) + { + if (!panel.TemperatureDisplay) { worstTemperature = float.PositiveInfinity; temperature = "missing"; } + else { - x = p.Key.x, y = p.Key.y, mask = p.Value.Mask, conductivity = p.Value.Conductivity, present = p.Value.Present, item = p.Value.Item, - icon = Pack(p.Value.Icon), background = Pack(p.Value.Background), rect = PageRect(rig, rects[p.Key]) - }).ToArray(), - temperature = temperature ? PageRect(rig, temperature) : null - }); + worstTemperature = Worst(PageRect(rig, panel.TemperatureDisplay.rectTransform), golden.temperature); + temperature = worstTemperature.ToString("F5"); + } + } + Log($"golden {state.Name} w={width} cells={records.Count}/{expected.Count} wrongRecords={wrong} extraCells={extra} worstRect={worstRect:F5} temperatureRect={temperature} (bound {RectBound})"); + if (wrong > 0 || extra > 0) Breaches.Add($"golden {state.Name} w={width}: {wrong} records differ, {extra} extra cells"); + if (worstRect > RectBound) Breaches.Add($"golden {state.Name} w={width}: cell rect {worstRect:F5} > {RectBound}"); + if (worstTemperature > RectBound) Breaches.Add($"golden {state.Name} w={width}: temperature rect {temperature} > {RectBound}"); } - private static void WriteGolden() + // The look mutants of the new path, applied to the live panel's grid; flip-ignored lays the enemy grid out unflipped. + private static void MutateLook(InventoryPanel panel, HullState state) { - Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(_recordsOut))!); - File.WriteAllText(_recordsOut, JsonUtility.ToJson(new Golden { states = GoldenStates.ToArray() }, true)); - Log($"golden written to {_recordsOut}: {GoldenStates.Count} states, {GoldenStates.Sum(s => s.cells.Length)} cells"); + var grid = panel.Grid; + switch (_mutant) + { + case "rule-inset-2": grid.RuleInset = 2f; break; + case "softness-1.25": grid.Softness = 1.25f; break; + case "fill-inset-2.5": grid.FillInset = 2.5f; break; + case "arms-0": grid.ArmTexels = 0f; break; + case "pipe-width-minus": grid.PipeHalfWidth -= .5f / 32f; break; + case "icon-multiplier-1": grid.IconTexel = InventoryGrid.TexelOf(66f, 1f); break; + case "flip-ignored" when state.Enemy: + grid.Resize(grid.Width, grid.Height, grid.CellSize, grid.Padding, GridOrientation.LowerLeft); + panel.RefreshCells(); + break; + } + } + + // The branches of RefreshCells the states reach: a hardpoint cell, an interior cell with an item, an empty interior cell, an exterior + // cell, a cell shown as the fake occupancy, a cell ignored as the drag's source. Each must be reached by some state. + private static readonly Dictionary Branches = new[] { "hardpoint", "interior with item", "interior empty", "exterior", "fake", "ignored" }.ToDictionary(n => n, _ => 0); + + private static void CountBranches(Fixture fixture, InventoryPanel panel, HullState state, Dictionary records) + { + var counts = Branches.Keys.ToDictionary(n => n, _ => 0); + void Count(string branch) { counts[branch]++; Branches[branch]++; } + foreach (var (v, record) in records) + { + if (state.Cargo) + { + Count(record.Item ? "interior with item" : "interior empty"); + } + else if (fixture.Ship.Hardpoints[v.x, v.y] != null) Count("hardpoint"); + else if (fixture.Hull.InteriorCells[v]) Count(record.Item ? "interior with item" : "interior empty"); + else Count("exterior"); + if (panel.FakeOccupancy?[v] ?? false) Count("fake"); + if (panel.IgnoreOccupancy?[v] ?? false) Count("ignored"); + } + Log($"branches {state.Name}: " + string.Join(", ", counts.Select(c => $"{c.Key} {c.Value}"))); + } + + private static void CheckBranchCounts() + { + foreach (var (branch, count) in Branches) + if (count == 0) Breaches.Add($"no state reached the {branch} branch of RefreshCells"); } // old | new | abs difference x 8, cropped to the region. private static void SaveSideBySide(string name, Rig rig, Color32[] old, Color32[] fresh, RectInt region) { if (_pngOut == null) return; + var x1 = Mathf.Min(rig.Width, region.x + region.width); + var y1 = Mathf.Min(rig.Height, region.y + region.height); + region = new RectInt(Mathf.Max(0, region.x), Mathf.Max(0, region.y), x1 - Mathf.Max(0, region.x), y1 - Mathf.Max(0, region.y)); + if (region.width <= 0 || region.height <= 0) throw new InvalidOperationException($"{name}: the region {region} lies outside the {rig.Width}x{rig.Height} frame."); var output = new Texture2D(region.width * 3, region.height, TextureFormat.RGBA32, false); var pixels = new Color32[region.width * 3 * region.height]; for (var y = 0; y < region.height; y++) diff --git a/Assets/Scripts/UI/Menu/InventoryMenu.cs b/Assets/Scripts/UI/Menu/InventoryMenu.cs index 623a649ee..bb8bfcb25 100644 --- a/Assets/Scripts/UI/Menu/InventoryMenu.cs +++ b/Assets/Scripts/UI/Menu/InventoryMenu.cs @@ -24,10 +24,8 @@ public class InventoryMenu : MonoBehaviour private int _currentPanel = -1; - private int2 _selectedPosition; private InventoryPanel _selectedPanel; private ItemInstance _selectedItem; - private ItemData _selectedItemData; private void OnEnable() { // Background.gameObject.SetActive(true); @@ -82,29 +80,11 @@ public class InventoryMenu : MonoBehaviour } else { - if (_selectedPanel != null) - { - if (_selectedPanel.CellInstances.ContainsKey(_selectedPosition)) - { - foreach (var v in _selectedItemData.Shape.Coordinates) - { - var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition; - _selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2); - } - } - } - _selectedPanel = panel; - _selectedPosition = cargoEvent.Position; + _selectedPanel?.SetHighlight(_selectedItem, false); PropertiesPanel.Inspect(item); _selectedPanel = panel; - _selectedPosition = cargoEvent.CargoBay.Cargo[item]; _selectedItem = item; - _selectedItemData = GameManager.ItemManager.GetData(item); - foreach (var v in _selectedItemData.Shape.Coordinates) - { - var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition; - _selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2, true); - } + panel.SetHighlight(item, true); // TODO: SFX: Success } } @@ -137,28 +117,11 @@ public class InventoryMenu : MonoBehaviour } else { - if (_selectedPanel != null) - { - if (_selectedPanel.CellInstances.ContainsKey(_selectedPosition)) - { - foreach (var v in _selectedItemData.Shape.Coordinates) - { - var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition; - _selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2); - } - } - } - + _selectedPanel?.SetHighlight(_selectedItem, false); PropertiesPanel.Inspect(item); _selectedPanel = panel; - _selectedPosition = item.Position; _selectedItem = item.EquippableItem; - _selectedItemData = GameManager.ItemManager.GetData(item.EquippableItem); - foreach (var v in _selectedItemData.Shape.Coordinates) - { - var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition; - _selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2, true); - } + panel.SetHighlight(_selectedItem, true); // TODO: SFX: Success } } diff --git a/Assets/Scripts/UI/Menu/InventoryPanel.cs b/Assets/Scripts/UI/Menu/InventoryPanel.cs index eaa6212ac..591fcdfa1 100644 --- a/Assets/Scripts/UI/Menu/InventoryPanel.cs +++ b/Assets/Scripts/UI/Menu/InventoryPanel.cs @@ -22,7 +22,6 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler { public ConfirmationDialog Dialog; public RectTransform DragParent; - public bool Flip; public GameSettings Settings; public ActionGameManager GameManager; public ContextMenu ContextMenu; @@ -34,7 +33,13 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler public Button EditName; public Button Current; public Button Thermal; - public GridLayoutGroup Grid; + // The grid on the panel's `Cells` object: it owns layout, pixels, point-to-cell and the hovered cell. Flip is its orientation. + public InventoryGrid Grid; + // Authored: whether the panel takes pointer input (the menu's panels do, the HUD and the enemy panel do not), and the grid that + // draws the item being dragged. + public bool Interactive; + public InventoryGrid DragGhost; + // The oracle of the parity harness until the sprite sheets go: the panel itself reads none of these four. public Sprite[] NodeBackgroundTextures; public Sprite[] NodeTextures; public Sprite[] ThermalTextures; @@ -49,6 +54,9 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler public Color ToggleEnabledColor; public Color ToggleDisabledColor; public Color CellBackgroundColor = new Color(0, 0, 0, .75f); + // The cargo bay's own background, which the cell prototype's colour gave it (the menu's cargo cells were never set to + // CellBackgroundColor): authored from that colour by the migration. + public Color CargoBackgroundColor = new Color(0, 0, 0, .85f); public float MinTempRange = 1; public float DoubleClickTime = .5f; public float HitDamageThreshold = 1; @@ -63,20 +71,23 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler private Entity _displayedEntity; private EquippedCargoBay _displayedCargo; private Texture2D _temperatureTexture; - private RectTransform _firstRect; public ItemInstance FakeItem; public Shape FakeOccupancy; public Shape IgnoreOccupancy; - public List EmptyCells = new List(); - public Dictionary CellInstances = new Dictionary(); + + public bool Flip => Grid.Orientation == GridOrientation.UpperRight; + + // The present cells of the shown shape, and the pulse's per-cell background override: RefreshCells reads both. + private int2[] _cells = Array.Empty(); + private readonly Dictionary _pulse = new Dictionary(); private List _subscriptions = new List(); private Dictionary _cellAnimationSequence = new Dictionary(); private int _hitSequence = 0; private bool _thermal = false; private int _clickCount; - private InventoryCell _clickCell; + private int2? _clickCell; private float _clickTime; private bool _hud; @@ -200,7 +211,7 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler } } _temperatureTexture.Apply(); - TemperatureDisplay.rectTransform.anchoredPosition = _firstRect.anchoredPosition - Vector2.one * Grid.cellSize * 1.5f; + TemperatureDisplay.rectTransform.position = Grid.rectTransform.TransformPoint(Grid.CellRect(int2(-1, -1)).min); } } @@ -215,14 +226,10 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler _displayedCargo = null; _displayedEntity = null; - foreach(var empty in EmptyCells) - Destroy(empty); - EmptyCells.Clear(); - - foreach(var node in CellInstances.Values) - node.GetComponent().ReturnToPool(); - CellInstances.Clear(); - + Grid.Clear(); + _cells = Array.Empty(); + _pulse.Clear(); + foreach(var s in _subscriptions) s.Dispose(); @@ -238,20 +245,77 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler Title.text = "None"; } + // The cell a pointer press began on: a press that began on the grid began on a present cell (the grid passes empty ones through). + private bool PressedCell(PointerEventData data, out int2 cell) => + Grid.CellAt(data.pressPosition, data.pressEventCamera, out cell, out _); + + // A click counts only when the release is on the cell the press began on. + private bool ClickedCell(PointerEventData data, out int2 cell) + { + cell = default; + return Grid.CellAt(data.pressPosition, data.pressEventCamera, out var pressed, out _) && + Grid.CellAt(data.position, data.pressEventCamera, out cell, out _) && cell.Equals(pressed); + } + + private void CountClick(int2 v) + { + if (!_clickCell.HasValue || !_clickCell.Value.Equals(v) || Time.time - _clickTime > DoubleClickTime) + _clickCount = 0; + _clickCell = v; + _clickTime = Time.time; + _clickCount++; + } + + // The drag ghost: a copy of what the item's cells draw (before the source cells are ignored), on the union of their rects, parented + // under DragParent. Half alpha is its vertex colour. + private void BeginGhost(Shape occupancy, PointerEventData data) + { + var cells = occupancy.Coordinates.ToArray(); + var min = int2(cells.Min(c => c.x), cells.Min(c => c.y)); + var max = int2(cells.Max(c => c.x), cells.Max(c => c.y)); + DragGhost.Resize(max.x - min.x + 1, max.y - min.y + 1, Grid.CellSize, new RectOffset(), Grid.Orientation); + var bounds = Grid.CellRect(cells[0]); + foreach (var v in cells) + { + DragGhost.SetCell(v - min, Grid.RecordAt(v)); + var r = Grid.CellRect(v); + bounds = Rect.MinMaxRect(Mathf.Min(bounds.xMin, r.xMin), Mathf.Min(bounds.yMin, r.yMin), Mathf.Max(bounds.xMax, r.xMax), Mathf.Max(bounds.yMax, r.yMax)); + } + var ghost = DragGhost.rectTransform; + ghost.SetParent(Grid.rectTransform, false); + ghost.anchorMin = ghost.anchorMax = Vector2.zero; + ghost.pivot = Vector2.zero; + ghost.localRotation = Quaternion.identity; + ghost.localScale = Vector3.one; + ghost.sizeDelta = bounds.size; + ghost.anchoredPosition = bounds.min - Grid.rectTransform.rect.min; + ghost.SetParent(DragParent, true); + DragGhost.gameObject.SetActive(true); + _dragOffset = (Vector2) ghost.position - data.position; + } + + private void MoveGhost(PointerEventData data) + { + if (!DragGhost.gameObject.activeSelf) return; + var ghost = DragGhost.rectTransform; + ghost.position = new Vector3(data.position.x + _dragOffset.x, data.position.y + _dragOffset.y, ghost.position.z); + } + + private void EndGhost() => DragGhost.gameObject.SetActive(false); + public void Display(Entity entity, bool hud = false, bool thermal = false) { Clear(); - + _subscriptions.Add(entity.Equipment.ObserveAdd().Subscribe(_ => RefreshCells())); _subscriptions.Add(entity.Equipment.ObserveRemove().Subscribe(_ => RefreshCells())); - + _thermal = thermal; _hud = hud; _displayedEntity = entity; _displayedCargo = null; - _firstRect = null; - + if (TemperatureRange) TemperatureRange.SetActive(true); @@ -264,14 +328,17 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler } var hullData = GameManager.ItemManager.GetData(entity.Hull) as HullData; - + + var cellSize = Grid.CellSize; if (FitToContent) { - var gridRect = Grid.GetComponent(); - var rect = gridRect.rect; - Grid.cellSize = Vector2.one * (int) min(rect.width / (hullData.Shape.Width + 1), rect.height / (hullData.Shape.Height + 1)); + var rect = Grid.rectTransform.rect; + cellSize = (int) min(rect.width / (hullData.Shape.Width + 1), rect.height / (hullData.Shape.Height + 1)); } - + Grid.Resize(hullData.Shape.Width, hullData.Shape.Height, cellSize, Grid.Padding, Grid.Orientation); + Grid.Thermal = thermal; + _cells = hullData.Shape.AllCoordinates.Where(v => hullData.Shape[v]).ToArray(); + if(TemperatureDisplay) { _temperatureTexture = new Texture2D( @@ -283,9 +350,9 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler TemperatureDisplay.gameObject.SetActive(true); TemperatureDisplay.texture = _temperatureTexture; var tempRect = TemperatureDisplay.rectTransform; - tempRect.sizeDelta = Grid.cellSize * new Vector2(hullData.Shape.Width + 2, hullData.Shape.Height + 2); + tempRect.sizeDelta = Grid.CellSize * new Vector2(hullData.Shape.Width + 2, hullData.Shape.Height + 2); } - + if (Current) { Current.gameObject.SetActive(true); @@ -296,184 +363,145 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler Thermal.gameObject.SetActive(true); Thermal.targetGraphic.color = thermal ? ToggleEnabledColor : ToggleDisabledColor; } - - Grid.constraintCount = hullData.Shape.Width; - foreach (var v in hullData.Shape.AllCoordinates) + + if (Interactive) { - if (!hullData.Shape[v]) + if (!thermal) { - var empty = new GameObject("Empty Node", typeof(RectTransform)); - empty.transform.SetParent(Grid.transform); - if (!_firstRect) - _firstRect = empty.GetComponent(); - EmptyCells.Add(empty); + _subscriptions.Add(Grid.OnPointerClickAsObservable() + .Subscribe(data => + { + if (!ClickedCell(data, out var v)) return; + CountClick(v); + _onClick?.OnNext((new InventoryEntityEventData(data, v, entity), _clickCount)); + })); + _subscriptions.Add(Grid.OnBeginDragAsObservable() + .Subscribe(data => + { + if (!PressedCell(data, out var v)) return; + //Debug.Log("Entity Drag Start"); + var item = entity.GearOccupancy[v.x, v.y]; + if (item != null) + { + var originalOccupancy = hullData.Shape.Inset(item.Data.Shape, item.Position, item.EquippableItem.Rotation); + BeginGhost(originalOccupancy, data); + IgnoreOccupancy = originalOccupancy; + RefreshCells(); + _originalRotation = item.EquippableItem.Rotation; + GameManager.BeginDrag(new EquippedItemDragObject(item, entity, item.Position - v)); + //AkSoundEngine.PostEvent("Pickup", gameObject); + // TODO: SFX: Pickup Item + } + })); + _subscriptions.Add(Grid.OnDragAsObservable().Subscribe(MoveGhost)); + _subscriptions.Add(Grid.OnEndDragAsObservable() + .Subscribe(data => + { + if (!PressedCell(data, out var v)) return; + //Debug.Log("Entity Drag End"); + IgnoreOccupancy = null; + if (!GameManager.EndDrag()) + entity.GearOccupancy[v.x, v.y].EquippableItem.Rotation = _originalRotation; + EndGhost(); + RefreshCells(); + })); + void Hover(int2? was, int2? now) + { + if (was.HasValue) + { + //Debug.Log("Entity Pointer Exit"); + if (GameManager.DragObject is ItemDragObject) + { + FakeItem = null; + FakeOccupancy = null; + RefreshCells(); + GameManager.UnregisterDragTarget(); + } + } + if (!now.HasValue) return; + var v = now.Value; + //Debug.Log("Entity Pointer Enter"); + if (!(GameManager.DragObject is ItemDragObject itemDragObject)) return; + var item = itemDragObject.Item; + var itemData = GameManager.ItemManager.GetData(item); + if (!(item is EquippableItem equippableItem)) return; + var placementPosition = v + itemDragObject.OriginCellOffset; + if (entity.ItemFits(equippableItem, placementPosition, out var seated)) + { + FakeItem = item; + FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, seated); + RefreshCells(); + GameManager.RegisterDragTarget(drag => + { + //Debug.Log("Entity Drag Callback"); + if (GameManager.DragObject is EquippedItemDragObject equippedItemDragObject) + { + if(equippedItemDragObject.OriginEntity.TryUnequip(equippedItemDragObject.EquippedItem) == null) + { + // AkSoundEngine.PostEvent("UI_Fail", gameObject); + // TODO: SFX: Fail + Dialog.Clear(); + Dialog.Title.text = "Unable to move item!"; + Dialog.AddProperty("Verify that cargo bays are empty before un-equipping them."); + Dialog.Show(); + Dialog.MoveToCursor(); + } + // else + // AkSoundEngine.PostEvent("Unequip", gameObject); + // TODO: SFX: Unequip + } + else if (GameManager.DragObject is ItemInstanceDragObject itemInstanceDragObject) + itemInstanceDragObject.OriginInventory.Remove(itemInstanceDragObject.Item); + + FakeOccupancy = null; + var success = entity.TryEquip(equippableItem, placementPosition); + RefreshCells(); + // TODO: SFX: Equip + return success; + }); + } + } + Grid.HoveredCellChanged += Hover; + _subscriptions.Add(Disposable.Create(() => Grid.HoveredCellChanged -= Hover)); } else { - var cell = NodePrototype.Instantiate(); - cell.Background.color = CellBackgroundColor; - if (!_firstRect) - _firstRect = cell.GetComponent(); - if (!thermal) + _subscriptions.Add(Grid.OnPointerClickAsObservable().Subscribe(data => { - if(cell.PointerClickTrigger) - { - cell.PointerClickTrigger.OnPointerClickAsObservable() - .Subscribe(data => - { - if (cell != _clickCell || Time.time - _clickTime > DoubleClickTime) - _clickCount = 0; - _clickCell = cell; - _clickTime = Time.time; - _clickCount++; - _onClick?.OnNext((new InventoryEntityEventData(data, v, entity), _clickCount)); - }); - cell.BeginDragTrigger.OnBeginDragAsObservable() - .Subscribe(data => - { - //Debug.Log("Entity Drag Start"); - var item = entity.GearOccupancy[v.x, v.y]; - if (item != null) - { - var originalOccupancy = hullData.Shape.Inset(item.Data.Shape, item.Position, item.EquippableItem.Rotation); - _dragCells = originalOccupancy.Coordinates - .Select(v1 => Instantiate(CellInstances[v1], DragParent, true).transform).ToArray(); - foreach(var dragCell in _dragCells) - { - DestroyImmediate(dragCell.GetComponent()); - foreach (var component in dragCell.GetComponentsInChildren()) - component.enabled = false; - foreach (var img in dragCell.GetComponentsInChildren()) - img.color = new Color(img.color.r, img.color.g, img.color.b, img.color.a * .5f); - dragCell.GetComponentInChildren().raycastTarget = false; - } - _dragOffsets = _dragCells.Select(x => (Vector2) x.position - data.position).ToArray(); - IgnoreOccupancy = originalOccupancy; - RefreshCells(); - _originalRotation = item.EquippableItem.Rotation; - GameManager.BeginDrag(new EquippedItemDragObject(item, entity, item.Position - v)); - //AkSoundEngine.PostEvent("Pickup", gameObject); - // TODO: SFX: Pickup Item - } - }); - cell.DragTrigger.OnDragAsObservable() - .Subscribe(data => - { - for (var i = 0; i < _dragCells.Length; i++) - _dragCells[i].position = new Vector3( - data.position.x + _dragOffsets[i].x, - data.position.y + _dragOffsets[i].y, - _dragCells[i].position.z); - }); - cell.EndDragTrigger.OnEndDragAsObservable() - .Subscribe(data => - { - //Debug.Log("Entity Drag End"); - IgnoreOccupancy = null; - if (!GameManager.EndDrag()) - entity.GearOccupancy[v.x, v.y].EquippableItem.Rotation = _originalRotation; - foreach(var dragObject in _dragCells) - Destroy(dragObject.gameObject); - _dragCells = null; - RefreshCells(); - }); - cell.PointerEnterTrigger.OnPointerEnterAsObservable() - .Subscribe(data => - { - //Debug.Log("Entity Pointer Enter"); - if (!(GameManager.DragObject is ItemDragObject itemDragObject)) return; - var item = itemDragObject.Item; - var itemData = GameManager.ItemManager.GetData(item); - if (!(item is EquippableItem equippableItem)) return; - var placementPosition = v + itemDragObject.OriginCellOffset; - if (entity.ItemFits(equippableItem, placementPosition, out var seated)) - { - //foreach (var cell in _dragCells) cell.gameObject.SetActive(false); - FakeItem = item; - FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, seated); - RefreshCells(); - GameManager.RegisterDragTarget(drag => - { - //Debug.Log("Entity Drag Callback"); - if (GameManager.DragObject is EquippedItemDragObject equippedItemDragObject) - { - if(equippedItemDragObject.OriginEntity.TryUnequip(equippedItemDragObject.EquippedItem) == null) - { - // AkSoundEngine.PostEvent("UI_Fail", gameObject); - // TODO: SFX: Fail - Dialog.Clear(); - Dialog.Title.text = "Unable to move item!"; - Dialog.AddProperty("Verify that cargo bays are empty before un-equipping them."); - Dialog.Show(); - Dialog.MoveToCursor(); - } - // else - // AkSoundEngine.PostEvent("Unequip", gameObject); - // TODO: SFX: Unequip - } - else if (GameManager.DragObject is ItemInstanceDragObject itemInstanceDragObject) - itemInstanceDragObject.OriginInventory.Remove(itemInstanceDragObject.Item); - - FakeOccupancy = null; - var success = entity.TryEquip(equippableItem, placementPosition); - RefreshCells(); - // TODO: SFX: Equip - return success; - }); - } - }); - cell.PointerExitTrigger.OnPointerExitAsObservable() - .Subscribe(data => - { - if (!(GameManager.DragObject is ItemDragObject)) return; - FakeItem = null; - FakeOccupancy = null; - RefreshCells(); - GameManager.UnregisterDragTarget(); - }); - } - } - else - { - cell.PointerClickTrigger.OnPointerClickAsObservable().Subscribe(data => - { - var rect = cell.GetComponent(); - var point = Rect.PointToNormalized(rect.rect, rect.InverseTransformPoint(data.position)); + if (!Grid.CellAt(data.position, data.pressEventCamera, out var v, out var point)) return; // Debug.Log($"Clicked at pos {data.position}, normalized {point}"); - if (hullData.Shape[int2(v.x - 1, v.y)] && point.x < ThermalToggleRegionSize) - { - entity.HullConductivity[v.x - 1, v.y].x = !entity.HullConductivity[v.x - 1, v.y].x; - RefreshCells(new []{v,int2(v.x - 1, v.y)}); - } - if (hullData.Shape[int2(v.x + 1, v.y)] && point.x > 1 - ThermalToggleRegionSize) - { - entity.HullConductivity[v.x, v.y].x = !entity.HullConductivity[v.x, v.y].x; - RefreshCells(new []{v,int2(v.x + 1, v.y)}); - } - if (hullData.Shape[int2(v.x, v.y - 1)] && point.y < ThermalToggleRegionSize) - { - entity.HullConductivity[v.x, v.y - 1].y = !entity.HullConductivity[v.x, v.y - 1].y; - RefreshCells(new []{v,int2(v.x, v.y - 1)}); - } - if (hullData.Shape[int2(v.x, v.y + 1)] && point.y > 1 - ThermalToggleRegionSize) - { - entity.HullConductivity[v.x, v.y].y = !entity.HullConductivity[v.x, v.y].y; - RefreshCells(new []{v,int2(v.x, v.y + 1)}); - } - }); - } - CellInstances.Add(v, cell); + if (hullData.Shape[int2(v.x - 1, v.y)] && point.x < ThermalToggleRegionSize) + { + entity.HullConductivity[v.x - 1, v.y].x = !entity.HullConductivity[v.x - 1, v.y].x; + RefreshCells(new []{v,int2(v.x - 1, v.y)}); + } + if (hullData.Shape[int2(v.x + 1, v.y)] && point.x > 1 - ThermalToggleRegionSize) + { + entity.HullConductivity[v.x, v.y].x = !entity.HullConductivity[v.x, v.y].x; + RefreshCells(new []{v,int2(v.x + 1, v.y)}); + } + if (hullData.Shape[int2(v.x, v.y - 1)] && point.y < ThermalToggleRegionSize) + { + entity.HullConductivity[v.x, v.y - 1].y = !entity.HullConductivity[v.x, v.y - 1].y; + RefreshCells(new []{v,int2(v.x, v.y - 1)}); + } + if (hullData.Shape[int2(v.x, v.y + 1)] && point.y > 1 - ThermalToggleRegionSize) + { + entity.HullConductivity[v.x, v.y].y = !entity.HullConductivity[v.x, v.y].y; + RefreshCells(new []{v,int2(v.x, v.y + 1)}); + } + })); } } - RefreshCells(CellInstances.Keys); - + RefreshCells(); + _subscriptions.Add(entity.ArmorDamage.Subscribe(hit => { var hitCells = new[] { hit.pos }; StartCoroutine(Pulse(hitCells, HitType.Armor, _hitSequence++)); RefreshCells(hitCells); })); - + _subscriptions.Add(entity.ItemDamage.Where(hit=>hit.damage > HitDamageThreshold).Subscribe(hit => { var hitCells = hit.item.InsetShape.Coordinates; @@ -499,178 +527,150 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler HitType.Gear => Settings.GearHitColor, _ => Color.white }; + // The cells this sequence still owns: a later hit on a cell takes it over. The pulse is a background override RefreshCells reads. + int2[] Owned() => cells.Where(cell => _cellAnimationSequence[cell] == sequence).ToArray(); float startTime = Time.time; while (Time.time - startTime < CellHitPulseTime) { var lerp = (Time.time - startTime) / CellHitPulseTime; - foreach(var cell in cells) - if(_cellAnimationSequence[cell] == sequence) - if(CellInstances.ContainsKey(cell)) - CellInstances[cell].Background.color = Color.Lerp(hitColor, CellBackgroundColor, lerp); + var owned = Owned(); + foreach (var cell in owned) + _pulse[cell] = Color.Lerp(hitColor, CellBackgroundColor, lerp); + RefreshCells(owned); yield return null; } - foreach (var cell in cells) - if(CellInstances.ContainsKey(cell)) - CellInstances[cell].Background.color = CellBackgroundColor; + var still = Owned(); + foreach (var cell in still) + _pulse.Remove(cell); + RefreshCells(still); } public void Display(EquippedCargoBay cargo) { Clear(); - + _subscriptions.Add(cargo.Cargo.ObserveAdd().Subscribe(_ => RefreshCells())); _subscriptions.Add(cargo.Cargo.ObserveRemove().Subscribe(_ => RefreshCells())); - + _displayedCargo = cargo; _displayedEntity = null; if(Title) Title.text = cargo.Name; - + // FakeOccupancy = new Shape(cargo.Data.InteriorShape.Width, cargo.Data.InteriorShape.Height); // IgnoreOccupancy = new Shape(cargo.Data.InteriorShape.Width, cargo.Data.InteriorShape.Height); - Grid.constraintCount = cargo.Data.InteriorShape.Width; - foreach (var v in cargo.Data.InteriorShape.AllCoordinates) + var interior = cargo.Data.InteriorShape; + Grid.Thermal = false; + Grid.Resize(interior.Width, interior.Height, Grid.CellSize, Grid.Padding, Grid.Orientation); + _cells = interior.AllCoordinates.Where(v => interior[v]).ToArray(); + if (Interactive) { - if (!cargo.Data.InteriorShape[v]) - { - var empty = new GameObject("Empty Node", typeof(RectTransform)); - empty.transform.SetParent(Grid.transform); - EmptyCells.Add(empty); - } - else - { - var cell = NodePrototype.Instantiate(); - cell.PointerClickTrigger.OnPointerClickAsObservable() - .Subscribe(data => + _subscriptions.Add(Grid.OnPointerClickAsObservable() + .Subscribe(data => + { + if (!ClickedCell(data, out var v)) return; + CountClick(v); + _onClick?.OnNext((new InventoryCargoEventData(data, v, cargo), _clickCount)); + })); + _subscriptions.Add(Grid.OnBeginDragAsObservable() + .Subscribe(data => + { + if (!PressedCell(data, out var v)) return; + //Debug.Log("Inventory Drag Start"); + var item = cargo.Occupancy[v.x, v.y]; + if (item != null) { - if (cell != _clickCell || Time.time - _clickTime > DoubleClickTime) - _clickCount = 0; - _clickCell = cell; - _clickTime = Time.time; - _clickCount++; - _onClick?.OnNext((new InventoryCargoEventData(data, v, cargo), _clickCount)); - }); - cell.BeginDragTrigger.OnBeginDragAsObservable() - .Subscribe(data => - { - //Debug.Log("Inventory Drag Start"); - var item = cargo.Occupancy[v.x, v.y]; - if (item != null) - { - var itemPosition = cargo.Cargo[item]; - var itemData = GameManager.ItemManager.GetData(item); - var originalOccupancy = cargo.Data.InteriorShape.Inset(itemData.Shape, itemPosition, item.Rotation); - _dragCells = originalOccupancy.Coordinates - .Select(v1 => Instantiate(CellInstances[v1], DragParent, true).transform).ToArray(); - foreach(var dragCell in _dragCells) - { - DestroyImmediate(dragCell.GetComponent()); - foreach (var component in dragCell.GetComponentsInChildren()) - component.enabled = false; - foreach (var img in dragCell.GetComponentsInChildren()) - img.color = new Color(img.color.r, img.color.g, img.color.b, img.color.a * .5f); - dragCell.GetComponentInChildren().raycastTarget = false; - } - _dragOffsets = _dragCells.Select(x => (Vector2) x.position - data.position).ToArray(); - IgnoreOccupancy = originalOccupancy; - RefreshCells(); - _originalRotation = item.Rotation; - GameManager.BeginDrag(new ItemInstanceDragObject(item, cargo, cargo.Cargo[item] - v)); - // TODO: SFX: Pickup - } - }); - cell.DragTrigger.OnDragAsObservable() - .Subscribe(data => - { - for (var i = 0; i < _dragCells.Length; i++) - _dragCells[i].position = new Vector3( - data.position.x + _dragOffsets[i].x, - data.position.y + _dragOffsets[i].y, - _dragCells[i].position.z); - }); - cell.EndDragTrigger.OnEndDragAsObservable() - .Subscribe(data => - { - //Debug.Log("Inventory Drag End"); - IgnoreOccupancy = null; - GameManager.EndDrag(); - foreach(var dragObject in _dragCells) - Destroy(dragObject.gameObject); - _dragCells = null; - RefreshCells(); - }); - cell.PointerEnterTrigger.OnPointerEnterAsObservable() - .Subscribe(data => - { - //Debug.Log("Inventory Pointer Enter"); - if (!(GameManager.DragObject is ItemDragObject itemDragObject)) return; - var item = itemDragObject.Item; + var itemPosition = cargo.Cargo[item]; var itemData = GameManager.ItemManager.GetData(item); - var placementPosition = v + itemDragObject.OriginCellOffset; - if (cargo.ItemFits(item, placementPosition)) - { - //foreach (var cell in _dragCells) cell.gameObject.SetActive(false); - FakeItem = item; - FakeOccupancy = cargo.Data.InteriorShape.Inset(itemData.Shape, placementPosition, item.Rotation); - RefreshCells(); - GameManager.RegisterDragTarget(drag => - { - //Debug.Log("Inventory Drag Callback"); - if (GameManager.DragObject is EquippedItemDragObject equippedItemDragObject) - { - if(equippedItemDragObject.OriginEntity.TryUnequip(equippedItemDragObject.EquippedItem) == null) - { - // TODO: SFX: Fail - Dialog.Clear(); - Dialog.Title.text = "Unable to move item!"; - Dialog.AddProperty("Verify that cargo bays are empty before un-equipping them."); - Dialog.Show(); - Dialog.MoveToCursor(); - } - //else - // TODO: SFX: Unequip - } - else if (GameManager.DragObject is ItemInstanceDragObject itemInstanceDragObject) - itemInstanceDragObject.OriginInventory.Remove(itemInstanceDragObject.Item); - cargo.TryStore(item, placementPosition); - FakeOccupancy = null; - // TODO: SFX: Drop - return true; - }); - } - }); - cell.PointerExitTrigger.OnPointerExitAsObservable() - .Subscribe(data => + var originalOccupancy = cargo.Data.InteriorShape.Inset(itemData.Shape, itemPosition, item.Rotation); + BeginGhost(originalOccupancy, data); + IgnoreOccupancy = originalOccupancy; + RefreshCells(); + _originalRotation = item.Rotation; + GameManager.BeginDrag(new ItemInstanceDragObject(item, cargo, cargo.Cargo[item] - v)); + // TODO: SFX: Pickup + } + })); + _subscriptions.Add(Grid.OnDragAsObservable().Subscribe(MoveGhost)); + _subscriptions.Add(Grid.OnEndDragAsObservable() + .Subscribe(data => + { + //Debug.Log("Inventory Drag End"); + IgnoreOccupancy = null; + GameManager.EndDrag(); + EndGhost(); + RefreshCells(); + })); + void Hover(int2? was, int2? now) + { + if (was.HasValue) + { + if (GameManager.DragObject is ItemDragObject) { - if (!(GameManager.DragObject is ItemDragObject)) return; FakeItem = null; FakeOccupancy = null; RefreshCells(); GameManager.UnregisterDragTarget(); + } + } + if (!now.HasValue) return; + var v = now.Value; + //Debug.Log("Inventory Pointer Enter"); + if (!(GameManager.DragObject is ItemDragObject itemDragObject)) return; + var item = itemDragObject.Item; + var itemData = GameManager.ItemManager.GetData(item); + var placementPosition = v + itemDragObject.OriginCellOffset; + if (cargo.ItemFits(item, placementPosition)) + { + FakeItem = item; + FakeOccupancy = cargo.Data.InteriorShape.Inset(itemData.Shape, placementPosition, item.Rotation); + RefreshCells(); + GameManager.RegisterDragTarget(drag => + { + //Debug.Log("Inventory Drag Callback"); + if (GameManager.DragObject is EquippedItemDragObject equippedItemDragObject) + { + if(equippedItemDragObject.OriginEntity.TryUnequip(equippedItemDragObject.EquippedItem) == null) + { + // TODO: SFX: Fail + Dialog.Clear(); + Dialog.Title.text = "Unable to move item!"; + Dialog.AddProperty("Verify that cargo bays are empty before un-equipping them."); + Dialog.Show(); + Dialog.MoveToCursor(); + } + //else + // TODO: SFX: Unequip + } + else if (GameManager.DragObject is ItemInstanceDragObject itemInstanceDragObject) + itemInstanceDragObject.OriginInventory.Remove(itemInstanceDragObject.Item); + cargo.TryStore(item, placementPosition); + FakeOccupancy = null; + // TODO: SFX: Drop + return true; }); - - CellInstances.Add(v, cell); + } } + Grid.HoveredCellChanged += Hover; + _subscriptions.Add(Disposable.Create(() => Grid.HoveredCellChanged -= Hover)); } RefreshCells(); } - public void RefreshCells() - { - RefreshCells(CellInstances.Keys); - } + public void RefreshCells() => RefreshCells(_cells); - public void RefreshCells(IEnumerable cells) + // The one place a cell's record is composed: the match rules, GetColor (with the selection highlight, which the next refresh clears), + // the pulse's background override. The grid draws it. + public void RefreshCells(IEnumerable cells, bool highlight = false) { if (_displayedEntity != null) { + var hullData = GameManager.ItemManager.GetData(_displayedEntity.Hull) as HullData; foreach (var v in cells) { - if(!CellInstances.ContainsKey(v)) continue; - - var hullData = GameManager.ItemManager.GetData(_displayedEntity.Hull) as HullData; - + if (!hullData.Shape[v]) continue; + var spriteIndex = 0; var interior = hullData.InteriorCells[v]; var item = FakeOccupancy?[v]??false ? FakeItem : IgnoreOccupancy?[v]??false ? null : _displayedEntity.GearOccupancy[v.x, v.y]?.EquippableItem; @@ -737,17 +737,21 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler spriteIndex += 1 << i; } - CellInstances[v].Background.sprite = NodeBackgroundTextures[bgSpriteIndex]; - CellInstances[v].Icon.sprite = _thermal ? ThermalTextures[spriteIndex] : NodeTextures[spriteIndex]; - CellInstances[v].Icon.color = GetColor(v); + Grid.SetCell(v, new CellRecord + { + Mask = (byte) bgSpriteIndex, Present = true, Item = !_thermal && item != null, + Conductivity = (byte) (_thermal ? spriteIndex : 0), Icon = GetColor(v, highlight), + Background = _pulse.TryGetValue(v, out var pulse) ? pulse : CellBackgroundColor + }); } } else if(_displayedCargo != null) { + var interior = _displayedCargo.Data.InteriorShape; foreach (var v in cells) { - if(!CellInstances.ContainsKey(v)) continue; - + if (!interior[v]) continue; + var spriteIndex = 0; var item = FakeOccupancy?[v]??false ? FakeItem : IgnoreOccupancy?[v]??false ? null : _displayedCargo.Occupancy[v.x, v.y]; @@ -767,13 +771,23 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler if (item != null) spriteIndex += 1 << 8; - CellInstances[v].Background.sprite = NodeBackgroundTextures[bgSpriteIndex]; - CellInstances[v].Icon.sprite = NodeTextures[spriteIndex]; - CellInstances[v].Icon.color = GetColor(v); + Grid.SetCell(v, new CellRecord + { + Mask = (byte) bgSpriteIndex, Present = true, Item = item != null, Icon = GetColor(v, highlight), + Background = CargoBackgroundColor + }); } } } + // Refreshes the cells the item really occupies with the highlight colour; the next refresh of them clears it. + public void SetHighlight(ItemInstance item, bool on) + { + if (item == null) return; + ItemInstance Occupant(int2 v) => _displayedEntity != null ? _displayedEntity.GearOccupancy[v.x, v.y]?.EquippableItem : _displayedCargo?.Occupancy[v.x, v.y]; + RefreshCells(_cells.Where(v => Occupant(v) == item).ToArray(), on); + } + public Color GetColor(int2 position, bool highlight = false) { if (_displayedEntity != null) @@ -865,8 +879,7 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler } public Subject OnBackgroundClick = new Subject(); - private Transform[] _dragCells; - private Vector2[] _dragOffsets; + private Vector2 _dragOffset; private ItemRotation _originalRotation; public Subject<(InventoryEventData data, int clickCount)> OnClickAsObservable() => _onClick ?? (_onClick = new Subject<(InventoryEventData data, int clickCount)>());