From e060d6eb052550731f5900b1570f3f7da18c062c Mon Sep 17 00:00:00 2001 From: Sieds Aalberts Date: Thu, 30 Jun 2022 12:27:55 +0200 Subject: [PATCH] CellLayer TryGetValue. Return a value if within cell layer bounds. --- OpenRA.Game/Map/CellLayer.cs | 22 ++++++++++++++++++++++ OpenRA.Game/Map/Map.cs | 17 ++++++----------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/OpenRA.Game/Map/CellLayer.cs b/OpenRA.Game/Map/CellLayer.cs index 33602faf3c..5f61df39c1 100644 --- a/OpenRA.Game/Map/CellLayer.cs +++ b/OpenRA.Game/Map/CellLayer.cs @@ -98,6 +98,28 @@ namespace OpenRA } } + public bool TryGetValue(CPos cell, out T value) + { + // .ToMPos() returns the same result if the X and Y coordinates + // are switched. X < Y is invalid in the RectangularIsometric coordinate system, + // so we pre-filter these to avoid returning the wrong result + if (GridType == MapGridType.RectangularIsometric && cell.X < cell.Y) + { + value = default(T); + return false; + } + + var uv = cell.ToMPos(GridType); + if (Bounds.Contains(uv.U, uv.V)) + { + value = Entries[Index(uv)]; + return true; + } + + value = default(T); + return false; + } + public bool Contains(CPos cell) { // .ToMPos() returns the same result if the X and Y coordinates diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs index 80ab1b1e29..013e9d1471 100644 --- a/OpenRA.Game/Map/Map.cs +++ b/OpenRA.Game/Map/Map.cs @@ -879,7 +879,7 @@ namespace OpenRA // (c) u, v coordinates run diagonally to the cell axes, and we define // 1024 as the length projected onto the primary cell axis // - 512 * sqrt(2) = 724 - var z = Height.Contains(cell) ? 724 * Height[cell] + Grid.Ramps[Ramp[cell]].CenterHeightOffset : 0; + var z = Height.TryGetValue(cell, out var height) ? 724 * height + Grid.Ramps[Ramp[cell]].CenterHeightOffset : 0; return new WPos(724 * (cell.X - cell.Y + 1), 724 * (cell.X + cell.Y + 1), z); } @@ -890,8 +890,7 @@ namespace OpenRA { var center = CenterOfCell(cell); var offset = Grid.SubCellOffsets[index]; - var ramp = Ramp.Contains(cell) ? Ramp[cell] : 0; - if (ramp != 0) + if (Ramp.TryGetValue(cell, out var ramp) && ramp != 0) { var r = Grid.Ramps[ramp]; offset += new WVec(0, 0, r.HeightOffset(offset.X, offset.Y) - r.CenterHeightOffset); @@ -912,11 +911,7 @@ namespace OpenRA var cell = CellContaining(pos); var offset = pos - CenterOfCell(cell); - if (!Ramp.Contains(cell)) - return new WDist(offset.Z); - - var ramp = Ramp[cell]; - if (ramp != 0) + if (Ramp.TryGetValue(cell, out var ramp) && ramp != 0) { var r = Grid.Ramps[ramp]; return new WDist(offset.Z + r.CenterHeightOffset - r.HeightOffset(offset.X, offset.Y)); @@ -927,10 +922,10 @@ namespace OpenRA public WRot TerrainOrientation(CPos cell) { - if (!Ramp.Contains(cell)) - return WRot.None; + if (Ramp.TryGetValue(cell, out var ramp)) + return Grid.Ramps[ramp].Orientation; - return Grid.Ramps[Ramp[cell]].Orientation; + return WRot.None; } public WVec Offset(CVec delta, int dz)