From 405398834c9e3e3d67dfe1df195a7f07c209f886 Mon Sep 17 00:00:00 2001 From: jjanzen Date: Sun, 26 Jan 2025 16:06:15 -0600 Subject: start sdl impl --- src/frontend/sdl.zig | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/frontend/sdl.zig (limited to 'src/frontend') diff --git a/src/frontend/sdl.zig b/src/frontend/sdl.zig new file mode 100644 index 0000000..c9a4bf2 --- /dev/null +++ b/src/frontend/sdl.zig @@ -0,0 +1,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); + } +}; -- cgit v1.2.3