Files
TierMakerGodot/Extensions.cs

110 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Godot;
using Godot.NativeInterop;
public static class ExtensionHelper
{
// public static Card GetCardWithId(this SceneTree tree, string id)
// {
// const string CardGroup = "Card";
// var cards = tree.GetNodesInGroup(CardGroup);
// foreach (var card in cards)
// {
// if (card is Card c)
// {
// if (c.Id == id)
// return c;
// }
// else
// throw new System.Exception($"Node in group {CardGroup} is not of type {nameof(Card)}");
// }
// return null;
// }
// public static Row GetRowWithId(this SceneTree tree, string id)
// {
// const string RowGroup = "Card";
// var rows = tree.GetNodesInGroup(RowGroup);
// foreach (var row in rows)
// {
// if (row is Row r)
// {
// if (r.Id == id)
// return r;
// }
// else
// throw new System.Exception($"Node in group {RowGroup} is not of type {nameof(Row)}");
// }
// return null;
// }
public static IEnumerable<Node> GetAllDescendents(this Node node, bool includeInternal = false)
{
foreach (Node n in node.GetChildren(includeInternal))
{
yield return n;
foreach (Node c in n.GetAllDescendents())
yield return c;
}
}
// gets all descendents of a given type (in undefined order)
public static IEnumerable<T> GetAllDescendents<T>(this Node node,
bool includeInternal = false)
{
foreach (var n in node.GetAllDescendents(includeInternal))
if (n is T t)
yield return t;
}
public static string GetUnusedRowId(this SceneTree tree)
{
var ids = tree.GetNodesInGroup("RowGroup").OfType<row>().Select(r => r.RowId).ToArray();
int i = 1;
while (true)
{
if (!ids.Contains(i.ToString()))
return i.ToString();
i++;
}
}
public static string GetUnusedCardId(this SceneTree tree, params string[] otherIds)
{
//use hashset because there are (probably) more cards than rows
var ids = tree.GetNodesInGroup("CardGroup").OfType<card>().Select(c => c.CardId)
.Concat(otherIds).ToHashSet();
int i = 1;
while (true)
{
if (!ids.Contains(i.ToString()))
return i.ToString();
i++;
}
}
public static TNode GetParentOfType<TNode>(this Node node) where TNode : Node
{
var par = node.GetParent();
if (par is null)
return null;
else if (par is TNode as_tnode)
return as_tnode;
else
return par.GetParentOfType<TNode>();
}
public static Vector2 Union(this Vector2 vect, Vector2 other)
=> new(Math.Max(vect.X, other.X), Math.Max(vect.Y, other.Y));
public static Vector2I Union(this Vector2I vect, Vector2 other)
=> new((int)Math.Max(vect.X, other.X), (int)Math.Max(vect.Y, other.Y));
public static System.Drawing.Color ToSystemColor(this Godot.Color color)
=> System.Drawing.Color.FromArgb(
(int)(color.R * 255),
(int)(color.G * 255),
(int)(color.B * 255)
);
public static Godot.Color ToGodotColor(this System.Drawing.Color color)
=> new Godot.Color(
color.R / 255.0f,
color.G / 255.0f,
color.B / 255.0f,
1
);
}