summaryrefslogtreecommitdiff
path: root/src/sdl.zig
blob: f8925a1d4c93b5140dfdccae3c756e4f53508c5d (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const std = @import("std");
const sdl = @cImport(@cInclude("SDL2/SDL.h"));
const Point = @import("main.zig").Point;

pub const instance = struct {
    renderer: ?*sdl.SDL_Renderer,
    window: ?*sdl.SDL_Window,
};

pub fn init() instance {
    _ = sdl.SDL_Init(sdl.SDL_INIT_VIDEO);
    var window = sdl.SDL_CreateWindow(
        "main",
        sdl.SDL_WINDOWPOS_UNDEFINED,
        sdl.SDL_WINDOWPOS_UNDEFINED,
        500,
        500,
        sdl.SDL_WINDOW_SHOWN,
    );

    var renderer = sdl.SDL_CreateRenderer(
        window,
        -1,
        sdl.SDL_RENDERER_ACCELERATED,
    );

    return instance{
        .window = window,
        .renderer = renderer,
    };
}

pub fn draw_line(i: instance, p1: Point, p2: Point) void {
    _ = sdl.SDL_RenderDrawLineF(i.renderer, p1.x, p1.y, p2.x, p2.y);
}

pub fn delay(t: u32) void {
    sdl.SDL_Delay(t);
}

pub fn draw_color(i: instance, r: u8, g: u8, b: u8, a: u8) void {
    _ = sdl.SDL_SetRenderDrawColor(i.renderer, r, g, b, a);
}

pub fn clear(i: instance) void {
    _ = sdl.SDL_RenderClear(i.renderer);
}

pub fn present(i: instance) void {
    sdl.SDL_RenderPresent(i.renderer);
}

pub fn get_event() event {
    var e: sdl.SDL_Event = undefined;
    _ = sdl.SDL_PollEvent(&e);

    var key = keys.none;
    if (std.meta.intToEnum(keys, e.key.keysym.sym)) |val| {
        key = val;
    } else |_| {}
    var mode = modes.mouse;
    if (std.meta.intToEnum(modes, e.type)) |val| {
        mode = val;
    } else |_| {}

    var r: event = event{
        .key = key,
        .mode = mode,
    };
    return r;
}

const event = struct {
    key: keys,
    mode: modes,
};

pub const modes = enum(u32) {
    mouse = sdl.SDL_MOUSEMOTION,
    window = sdl.SDL_WINDOWEVENT,
    quit = sdl.SDL_QUIT,
    key = sdl.SDL_KEYDOWN,
};

pub fn quit(i: instance) void {
    sdl.SDL_DestroyRenderer(i.renderer);
    sdl.SDL_DestroyWindow(i.window);
    sdl.SDL_Quit();
}

pub const keys = enum(i32) {
    none = sdl.SDLK_UNKNOWN,
    w = sdl.SDLK_w,
    s = sdl.SDLK_s,
    q = sdl.SDLK_q,
    up = sdl.SDLK_UP,
    down = sdl.SDLK_DOWN,
    left = sdl.SDLK_LEFT,
    right = sdl.SDLK_RIGHT,
};