extends Node
class_name HexGrid

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	pass

var Size : float = 0.0
var HexWidth : float = 0.0
var HexHalfHeight : float = 0.0
var GridWidth : float = 0.0
var GridHeight : float = 0.0

func _init(_size : float = 1.0) -> void:
	SetGridSize(_size)

func SetGridSize(_size : float) -> void:
	Size = _size 
	HexWidth = Size * 0.86602540378
	HexHalfHeight = Size * 0.5
	GridWidth = HexWidth
	GridHeight = HexHalfHeight * 1.5

func AxialCoordinateFromWorldPosition(wp : Vector2) -> AxialCoordinate:
	# https://www.redblobgames.com/grids/hexagons/#pixel-to-hex
	# sqrt(3)/3 * x  -  1./3 * y
	var q : float = (0.577350269189 * wp.x - 0.3333333333 * wp.y) / HexHalfHeight
	var r : float = (0.6666666666 * wp.y) / HexHalfHeight

	return AxialCoordinate.round_to_nearest(q, r)

func WorldPositionFromAxialPosition(ac : AxialCoordinate) -> Vector2:
	var oc : OffsetCoordinate = OffsetCoordinate.new(0, 0)
	oc.FromAxial(ac)

	return Vector2(
		GridWidth * oc.col + (oc.row & 1) * GridWidth * 0.5,
		GridHeight * oc.row
	)

#     private int NumValidCollidersAtAxialPositionQuery = 0;
#     private Collider[] CollidersAtLastAxialPositionQueried = new Collider[20];
#     public bool QueryForCollidersAtAxialPosition(AxialCoordinate ac, int layerMask)
#     {
#         NumValidCollidersAtAxialPositionQuery = Physics.OverlapSphereNonAlloc(WorldPositionFromAxialPosition(ac), 0.0f, CollidersAtLastAxialPositionQueried, layerMask);
#         return NumValidCollidersAtAxialPositionQuery > 0;
#     }
#     public int GetQueriedColliderCount()
#     {
#         return NumValidCollidersAtAxialPositionQuery;
#     }
#     public IEnumerable<Collider> IterateQueriedColliders()
#     {
#         for (int i = 0; i < NumValidCollidersAtAxialPositionQuery; i++)
#         {
#             yield return CollidersAtLastAxialPositionQueried[i];
#         }
#     }

#     public T GetAnyComponentAtAxialPosition<T>(AxialCoordinate ac, int layerMask)
#     {

#         QueryForCollidersAtAxialPosition(ac, layerMask);
#         foreach (Collider c in IterateQueriedColliders())
#         {
#             T retval = c.GetComponent<T>();
#             if (!EqualityComparer<T>.Default.Equals(retval, default(T)))
#                 return retval;
#         }
#         return default(T);
#     }

#     public IEnumerable<T> GetAllComponentsAtAxialPosition<T>(AxialCoordinate ac, int layerMask)
#     {
#         QueryForCollidersAtAxialPosition(ac, layerMask);
#         foreach (Collider c in IterateQueriedColliders())
#         {
#             T retval = c.GetComponent<T>();
#             if (!EqualityComparer<T>.Default.Equals(retval, default(T)))
#                 yield return retval;
#         }
#     }
# }
