aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/sdl.zig
blob: c9a4bf2dac82bf7ae0b9c11f0c3aed982630fa6b (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
const std = @import("std");
const sdl = @cImport({
    @cInclude("SDL.h");
});
const Action = @import("../actions.zig").Action;
const IOInterface = @import("io_interface.zig").IOInterface;

pub const IO = struct {
    allocator: std.mem.Allocator,
    screen: ?*sdl.SDL_Window,
    sprites: std.ArrayList([*c]sdl.SDL_Surface),

    fn loadSprite(self: *IO) !void {
        const sprite = sdl.SDL_LoadBMP("assets/image.bmp");
        if (sprite == null) return error.FailedToLoadSprite;
        try self.sprites.append(sprite);
    }

    pub fn displayMessage(self: *IO, str: []const u8) anyerror!void {
        _ = self;
        _ = str;

        // TODO
    }

    pub fn waitForTick(self: *IO) anyerror!Action {
        _ = self;

        var quit = false;
        var event: sdl.SDL_Event = undefined;
        while (!quit) {
            _ = sdl.SDL_WaitEvent(&event);
            switch (event.type) {
                sdl.SDL_QUIT => quit = true,
                else => {},
            }
        }

        return Action.exit;
    }

    pub fn init(allocator: std.mem.Allocator) !IOInterface {
        var io = try allocator.create(IO);
        io.allocator = allocator;
        io.sprites = std.ArrayList([*c]sdl.SDL_Surface).init(allocator);

        if (sdl.SDL_Init(sdl.SDL_INIT_VIDEO) < 0) return error.SDL_Failed;

        io.screen = sdl.SDL_CreateWindow(
            "urlg",
            sdl.SDL_WINDOWPOS_UNDEFINED,
            sdl.SDL_WINDOWPOS_UNDEFINED,
            640,
            480,
            0,
        );

        io.loadSprite() catch |err| {
            io.deinit();
            return err;
        };
        const screen_surface = sdl.SDL_GetWindowSurface(io.screen);
        _ = sdl.SDL_BlitSurface(io.sprites.items[0], null, screen_surface, null);
        _ = sdl.SDL_UpdateWindowSurface(io.screen);

        return IOInterface.init(io);
    }

    pub fn deinit(self: *IO) void {
        for (self.sprites.items) |sprite| {
            _ = sdl.SDL_FreeSurface(sprite);
        }
        self.sprites.deinit();

        _ = sdl.SDL_DestroyWindow(self.screen);

        _ = sdl.SDL_Quit();
        self.allocator.destroy(self);
    }
};