summaryrefslogtreecommitdiff
path: root/Extensions.cs
blob: 80a8e2f0eb435874e177b13d6868bb4b8ebcaeb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.Numerics;
using Raylib_cs;

namespace OnekoOnline;

static class MathExt
{
    public static Vector2 LimitLength(this Vector2 toLimit, float lengthLimit)
    {
        float length = toLimit.Length();
        if (toLimit == Vector2.Zero) return Vector2.Zero;
        return Vector2.Normalize(toLimit) * MathF.Min(length, lengthLimit);
    }

    public static Vector2 Round(this Vector2 toRound)
    {
        return new(MathF.Round(toRound.X), MathF.Round(toRound.Y));
    }
}

static class StringExt
{
    public static string LimitLength(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? value : value[..maxLength]; 
    }
}

static class RaylibExt
{
    public static int TextureLength(int width, int height, PixelFormat format, int mipmaps)
    {
        int size = 0;

        for (int i = 0; i < mipmaps; i++) {
            size += Raylib.GetPixelDataSize(width, height, format);

            //Max is a security check for NPOT textures
            width = Math.Max(width/2, 1);
            height = Math.Max(height/2, 1);
        }

        return size;
    }

    public static int DataLength(this Image img) => TextureLength(img.Width, img.Height, img.Format, img.Mipmaps);

    public static int DataLength(this Texture2D tex) => TextureLength(tex.Width, tex.Height, tex.Format, tex.Mipmaps);

    public unsafe static Span<byte> DataSpan(this Image img) => new(img.Data, img.DataLength());
}

public static class Directions
{
    public static readonly Vector2 Up = new(0,-1);
    public static readonly Vector2 Down = new(0,1);
    public static readonly Vector2 Left = new(-1,0);
    public static readonly Vector2 Right = new(1,0);

    public static readonly Vector2 UpLeft = Vector2.Normalize(Up+Left);
    public static readonly Vector2 UpRight = Vector2.Normalize(Up+Right);
    public static readonly Vector2 DownLeft = Vector2.Normalize(Down+Left);
    public static readonly Vector2 DownRight = Vector2.Normalize(Down+Right);
}