From 8a827b37e60639e58cd7cd2500f77528ae490fb8 Mon Sep 17 00:00:00 2001 From: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> Date: Fri, 10 Mar 2023 09:03:29 +1100 Subject: [PATCH] Add enumerator for box2i edges (#3834) Will write a test later don't @ me. --- Robust.Shared.Maths/Box2i.cs | 60 ++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/Robust.Shared.Maths/Box2i.cs b/Robust.Shared.Maths/Box2i.cs index 38eff5a11..604cd4f79 100644 --- a/Robust.Shared.Maths/Box2i.cs +++ b/Robust.Shared.Maths/Box2i.cs @@ -167,4 +167,64 @@ namespace Robust.Shared.Maths Top * scalar); } } + + /// + /// Iterates neighbouring tiles to a box2i. + /// + public struct Box2iEdgeEnumerator + { + private readonly bool _corners; + private readonly Box2i _box; + private readonly int _offset; + private int _x; + private int _y; + + public Box2iEdgeEnumerator(Box2i box, bool corners, int offset = 1) + { + _box = box; + _corners = corners; + _x = _box.Left - offset; + _y = _box.Bottom - offset; + _offset = offset; + } + + public bool MoveNext(out Vector2i index) + { + for (var x = _x; x < _box.Right + _offset; x++) + { + for (var y = _y; y < _box.Top + _offset; y++) + { + if (x != _box.Left - _offset && + x != _box.Right + (_offset - 1) && + y != _box.Bottom - _offset && + y != _box.Top + (_offset - 1)) + { + continue; + } + + if (!_corners && + (x == _box.Left - _offset && (y == _box.Bottom - _offset || y == _box.Top + (_offset - 1)) || + x == _box.Right && (y == _box.Bottom - _offset || y == _box.Top + (_offset - 1)))) + { + continue; + } + + _x = x; + _y = y + 1; + + if (_y == _box.Top + _offset) + { + _x++; + _y = _box.Bottom - _offset; + } + + index = new Vector2i(x, y); + return true; + } + } + + index = default; + return false; + } + } }