const ext = @cImport({ @cInclude("SDL2/SDL.h"); }); const io = @import("./io.zig"); const math = @import("./math.zig"); const mem = @import("./mem.zig"); const meta = @import("./meta.zig"); const oar = @import("./oar.zig"); const stack = @import("./stack.zig"); const std = @import("std"); /// /// A thread-safe platform abstraction over multiplexing system I/O processing and event handling. /// pub const AppContext = opaque { /// /// Linked list of asynchronous messages chained together to be processed by the work processor. /// const Message = struct { next: ?*Message = null, kind: union(enum) { quit, task: struct { data: *anyopaque, action: fn (*anyopaque) void, frame: anyframe, }, }, }; /// /// Internal state of the event loop hidden from the API consumer. /// const Implementation = struct { data_file_system: FileSystem, user_file_system: FileSystem, message_semaphore: *ext.SDL_sem, message_mutex: *ext.SDL_mutex, message_thread: ?*ext.SDL_Thread, messages: ?*Message = null, /// /// [StartError.OutOfSemaphores] indicates that the process has no more semaphores available /// to it for use, meaning an [Implementation] may not be initialized at this time. /// /// [StartError.OutOfMutexes] indicates that the process has no more mutexes available to it /// for use, meaning an [Implementation] may not be initialized at this time. /// /// [StartError.OutOfMemory] indicates that the process has no more memory available to it /// for use, meaning an [Implementation] may not be initialized at this time. /// const InitError = error { OutOfSemaphores, OutOfMutexes, OutOfMemory, }; /// /// [StartError.OutOfThreads] indicates that the process has no more threads available to it /// to use, meaning that no asynchronous work may be started on an [Implementation] at this /// time. /// /// [StartError.AlreadyStarted] is occurs when a request to start work processing happens on /// an [Implementation] that is already processing work. /// const StartError = error { OutOfThreads, AlreadyStarted, }; /// /// Casts `app_context` to a [Implementation] reference. /// /// *Note* that if `app_context` does not have the same alignment as [Implementation], safety- /// checked undefined behavior will occur. /// fn cast(app_context: *AppContext) *Implementation { return @ptrCast(*Implementation, @alignCast(@alignOf(Implementation), app_context)); } /// /// Deinitializes the `implementation`, requesting any running asynchronous workload /// processes quit and waits for them to do so before freeing any resources. /// fn deinit(implementation: *Implementation) void { var message = Message{.kind = .quit}; implementation.enqueue(&message); { var status = @as(c_int, 0); // SDL2 defines waiting on a null thread reference as a no-op. See // https://wiki.libsdl.org/SDL_WaitThread for more information ext.SDL_WaitThread(implementation.message_thread, &status); if (status != 0) { // TODO: Error check this. } } ext.SDL_DestroyMutex(implementation.message_mutex); ext.SDL_DestroySemaphore(implementation.message_semaphore); } /// /// Enqueues `message` to the message processor of `implementation` to be processed at a /// later, non-deterministic point in time. /// fn enqueue(implementation: *Implementation, message: *Message) void { { // TODO: Error check these. _ = ext.SDL_LockMutex(implementation.message_mutex); defer _ = ext.SDL_UnlockMutex(implementation.message_mutex); if (implementation.messages) |messages| { messages.next = message; } else { implementation.messages = message; } } // TODO: Error check this. _ = ext.SDL_SemPost(implementation.message_semaphore); } /// /// Initializes a new [Implemenation] with `data_archive_path` as the read-only data archive /// to read from and `user_path_prefix` as the native writable user data directory. /// /// Returns the created [Implementation] value on success or [InitError] on failure. /// fn init(data_archive_path: []const u8, user_path_prefix: []const u8) InitError!Implementation { return Implementation{ .message_semaphore = ext.SDL_CreateSemaphore(0) orelse return error.OutOfSemaphores, .message_mutex = ext.SDL_CreateMutex() orelse return error.OutOfMutexes, .data_file_system = .{.archive = data_archive_path}, .user_file_system = .{.native = user_path_prefix}, .message_thread = null, }; } /// /// [FileSystemMessage] processing function used by a dedicated worker thread, where `data` /// is a type-erased reference to a [EventLoop]. /// /// The processor returns `0` if it exited normally or any other value if an erroneous exit /// occured. /// fn processTasks(userdata: ?*anyopaque) callconv(.C) c_int { const implementation = Implementation.cast( @ptrCast(*AppContext, userdata orelse unreachable)); while (true) { // TODO: Error check these. _ = ext.SDL_SemWait(implementation.message_semaphore); _ = ext.SDL_LockMutex(implementation.message_mutex); defer _ = ext.SDL_UnlockMutex(implementation.message_mutex); while (implementation.messages) |messages| { switch (messages.kind) { .quit => { return 0; }, .task => |task| { task.action(task.data); resume task.frame; }, } implementation.messages = messages.next; } } } /// /// Attempts to start the asynchronous worker thread of `implementation` if it hasn't been /// already. /// /// [StartError] is returned on failure. /// fn start(implementation: *Implementation) StartError!void { if (implementation.message_thread != null) return error.AlreadyStarted; implementation.message_thread = ext.SDL_CreateThread(processTasks, "File System Worker", implementation) orelse { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to create file-system work processor"); return error.OutOfThreads; }; } }; /// /// Returns a reference to the currently loaded data file-system. /// pub fn data(app_context: *AppContext) *const FileSystem { return &Implementation.cast(app_context).data_file_system; } /// /// /// pub fn schedule(app_context: *AppContext, procedure: anytype, arguments: anytype) meta.FnReturn(@TypeOf(procedure)) { const Task = struct { procedure: @TypeOf(procedure), arguments: *@TypeOf(arguments), result: meta.FnReturn(@TypeOf(procedure)), const Task = @This(); fn process(userdata: *anyopaque) void { const task = @ptrCast(*Task, @alignCast(@alignOf(Task), userdata)); task.result = @call(.{}, task.procedure, task.arguments.*); } }; var task = Task{ .procedure = procedure, .arguments = &arguments, }; var message = AppContext.Message{ .kind = .{.task = .{ .data = &task, .action = Task.process, .frame = @frame(), }}, }; suspend Implementation.cast(app_context).enqueue(&message); } /// /// Returns a reference to the currently loaded user file-system. /// pub fn user(app_context: *AppContext) *const FileSystem { return &Implementation.cast(app_context).user_file_system; } }; /// /// File-system agnostic abstraction for manipulating a file. /// pub const FileAccess = opaque { /// /// [Error.FileInaccessible] is a generic catch-all for a [FileAccess] reference no longer /// pointing to a file or the file becomming invalid for whatever reason. /// pub const Error = error { FileInaccessible, }; /// /// Returns `file_access` casted to a [ext.SDL_RWops]. /// fn asRwOps(file_access: *FileAccess) *ext.SDL_RWops { return @ptrCast(*ext.SDL_RWops, @alignCast(@alignOf(ext.SDL_RWops), file_access)); } /// /// Close the file referenced by `file_access` on the main thread, invalidating the reference to /// it and releasing any associated resources. /// /// Freeing an invalid `file_access` has no effect on the file and logs a warning over the /// wasted effort. /// pub fn close(file_access: *FileAccess) void { if (ext.SDL_RWclose(file_access.asRwOps()) != 0) ext.SDL_LogWarn(ext.SDL_LOG_CATEGORY_APPLICATION, "Closed an invalid file reference"); } /// /// Attempts to query the current cursor position for the file referenced by `file_access`. /// /// Returns the number of bytes into the file that the cursor is relative to its beginning or a /// [Error] on failure. /// pub fn queryCursor(file_access: *FileAccess) Error!u64 { ext.SDL_ClearError(); const sought = ext.SDL_RWtell(file_access.asRwOps()); if (sought < 0) return error.FileInaccessible; return @intCast(u64, sought); } /// /// Attempts to query the current length for the file referenced by `file_access`. /// /// Returns the current length of the file at the time of the operation or a [Error] if the file /// failed to be queried. /// pub fn queryLength(file_access: *FileAccess) Error!u64 { ext.SDL_ClearError(); const sought = ext.SDL_RWsize(file_access.asRwOps()); if (sought < 0) return error.FileInaccessible; return @intCast(u64, sought); } /// /// Attempts to read `file_access` from the its current position into `buffer`. /// /// Returns the number of bytes that were available to be read, otherwise an [Error] on failure. /// pub fn read(file_access: *FileAccess, buffer: []u8) Error!usize { ext.SDL_ClearError(); const buffer_read = ext.SDL_RWread(file_access.asRwOps(), buffer.ptr, @sizeOf(u8), buffer.len); if ((buffer_read == 0) and (ext.SDL_GetError() != null)) return error.FileInaccessible; return buffer_read; } /// /// Attempts to seek `file_access` from the beginning of the file to `cursor` bytes. /// /// Returns [Error] on failure. /// pub fn seek(file_access: *FileAccess, cursor: u64) Error!void { var to_seek = cursor; while (to_seek != 0) { const sought = @intCast(i64, std.math.min(to_seek, std.math.maxInt(i64))); ext.SDL_ClearError(); if (ext.SDL_RWseek(file_access.asRwOps(), sought, ext.RW_SEEK_CUR) < 0) return error.FileInaccessible; // Cannot be less than zero because it is derived from `read`. to_seek -= @intCast(u64, sought); } } /// /// Attempts to seek `file_access` to the end of the file while using `app_context` as the execution /// context. /// /// Returns [Error] on failure. /// pub fn seekToEnd(file_access: *FileAccess) Error!void { ext.SDL_ClearError(); if (ext.SDL_RWseek(file_access.asRwOps(), 0, ext.RW_SEEK_END) < 0) return error.FileInaccessible; } }; /// /// Platform-agnostic mechanism for working with an abstraction of the underlying file-system(s) /// available to the application in a sandboxed environment. /// pub const FileSystem = union(enum) { native: []const u8, archive: []const u8, /// /// Platform-agnostic mechanism for referencing files and directories on a [FileSystem]. /// pub const Path = struct { file_system: *const FileSystem, length: u8, buffer: [max]u8, /// /// With files typically being backed by a block device, they can produce a variety of /// errors - from physical to virtual errors - these are all encapsulated by the API as /// general [OpenError.FileNotFound] errors. /// /// When a given [FileSystem] does not support a specified [OpenMode], /// [OpenError.ModeUnsupported] is used to inform the consuming code that another [OpenMode] /// should be tried or, if no mode other is suitable, that the resource is effectively /// unavailable. /// pub const OpenError = error { FileNotFound, ModeUnsupported, }; /// /// [OpenMode.readonly] indicates that an existing file is opened in a read-only state, /// disallowing write access. /// /// [OpenMode.overwrite] indicates that an empty file has been created or an existing file /// has been completely overwritten into. /// /// [OpenMode.append] indicates that an existing file that has been opened for reading from /// and writing to on the end of existing data. /// pub const OpenMode = enum { readonly, overwrite, append, }; /// /// Returns `true` if the length of `path` is empty, otherwise `false`. /// pub fn isEmpty(path: Path) bool { return (path.length == 0); } /// /// Returns `true` if `this` is equal to `that`, otherwise `false`. /// pub fn equals(this: Path, that: Path) bool { return (this.file_system == that.file_system) and std.mem.eql(u8, this.buffer[0 .. this.length], that.buffer[0 .. that.length]); } /// /// The maximum possible byte-length of a [Path]. /// /// Note that paths are encoded using UTF-8, meaning that a character may be bigger than one /// byte. Because of this, it is not safe to asume that a path may hold [max] individual /// characters. /// pub const max = 255; /// /// Attempts to open the file identified by `path` with `mode` as the mode for opening the /// file. /// /// Returns a [FileAccess] reference that provides access to the file referenced by `path` /// or a [OpenError] if it failed. /// pub fn open(path: Path, mode: OpenMode) OpenError!*FileAccess { switch (path.file_system.*) { .archive => |archive| { if (archive.len == 0) return error.FileNotFound; if (mode != .readonly) return error.ModeUnsupported; var path_buffer = std.mem.zeroes([4096]u8); if (archive.len >= path_buffer.len) return error.FileNotFound; std.mem.copy(u8, path_buffer[0 ..], archive); const file_access = @ptrCast(*FileAccess, ext.SDL_RWFromFile( &path_buffer, "rb") orelse return error.FileNotFound); while (oar.Entry.read(file_access) catch return error.FileNotFound) |entry| { if (!entry.isValid()) break; if (std.mem.eql(u8, entry.name_buffer[0 .. entry.name_length], path.buffer[0 .. path.length])) return file_access; file_access.seek(entry.file_size) catch break; } return error.FileNotFound; }, .native => |native| { if (native.len == 0) return error.FileNotFound; var path_buffer = std.mem.zeroes([4096]u8); const seperator = '/'; const seperator_length = @boolToInt(native[native.len - 1] != seperator); if ((native.len + seperator_length + path.length) >= path_buffer.len) return error.FileNotFound; std.mem.copy(u8, path_buffer[0 ..], native); if (seperator_length != 0) path_buffer[native.len] = seperator; std.mem.copy(u8, path_buffer[native.len .. path_buffer.len], path.buffer[0 .. path.length]); ext.SDL_ClearError(); return @ptrCast(*FileAccess, ext.SDL_RWFromFile(&path_buffer, switch (mode) { .readonly => "rb", .overwrite => "wb", .append => "ab", }) orelse return error.FileNotFound); }, } } }; /// /// [PathError.TooLong] occurs when creating a path that is greater than the maximum size **in /// bytes**. /// pub const PathError = error { TooLong, }; /// /// Attempts to create a [Path] with `file_system` as the file-system root and the path /// components in `sequences` as a fully qualified path from the root. /// /// A [Path] value is returned containing the fully qualified path from the file-system root or /// a [PathError] if it could not be created. /// pub fn joinedPath(file_system: *const FileSystem, sequences: []const []const u8) PathError!Path { var path = Path{ .file_system = file_system, .buffer = std.mem.zeroes([Path.max]u8), .length = 0, }; if (sequences.len != 0) { const last_sequence_index = sequences.len - 1; for (sequences) |sequence, index| if (sequence.len != 0) { var components = mem.Spliterator(u8){ .source = sequence, .delimiter = "/", }; while (components.next()) |component| if (component.len != 0) { for (component) |byte| { if (path.length == Path.max) return error.TooLong; path.buffer[path.length] = byte; path.length += 1; } if (components.hasNext()) { if (path.length == Path.max) return error.TooLong; path.buffer[path.length] = '/'; path.length += 1; } }; if (index < last_sequence_index) { if (path.length == Path.max) return error.TooLong; path.buffer[path.length] = '/'; path.length += 1; } }; } return path; } }; /// /// /// pub const GraphicsContext = opaque { /// /// /// pub const Event = struct { keys_up: Keys = std.mem.zeroes(Keys), keys_down: Keys = std.mem.zeroes(Keys), keys_held: Keys = std.mem.zeroes(Keys), const Keys = [256]bool; }; /// /// /// const Implementation = struct { event: Event, }; /// /// /// pub fn poll(graphics_context: *GraphicsContext) ?*const Event { _ = graphics_context; return null; } /// /// /// pub fn present(graphics_context: *GraphicsContext) void { // TODO: Implement; _ = graphics_context; } }; /// /// Returns a graphics runner that uses `Errors` as its error set. /// pub fn GraphicsRunner(comptime Errors: type) type { return fn (*AppContext, *GraphicsContext) callconv(.Async) Errors!void; } /// /// [Log.info] represents a log message which is purely informative and does not indicate any kind /// of issue. /// /// [Log.debug] represents a log message which is purely for debugging purposes and will only occurs /// in debug builds. /// /// [Log.warning] represents a log message which is a warning about a issue that does not break /// anything important but is not ideal. /// pub const Log = enum(u32) { info = ext.SDL_LOG_PRIORITY_INFO, debug = ext.SDL_LOG_PRIORITY_DEBUG, warning = ext.SDL_LOG_PRIORITY_WARN, /// /// Writes `utf8_message` as the log kind identified by `log`. /// pub fn write(log: Log, utf8_message: []const u8) void { ext.SDL_LogMessage(ext.SDL_LOG_CATEGORY_APPLICATION, @enumToInt(log), "%.*s", utf8_message.len, utf8_message.ptr); } }; /// /// [RunError.InitFailure] occurs if a necessary resource fails to be acquired or allocated. /// /// [RunError.AlreadyRunning] occurs if a runner has already been started. /// pub const RunError = error { InitFailure, AlreadyRunning, }; /// /// Runs a graphical application referenced by `run` with `error` as its error set and `allocator` /// as the underlying memory allocation strategy for its graphical runtime. /// /// Should an error from `run` occur, an `Error` is returned, otherwise a [RunError] is returned if /// the underlying runtime fails and is logged. /// pub fn runGraphics(comptime Error: anytype, comptime run: GraphicsRunner(Error)) (RunError || Error)!void { if (ext.SDL_Init(ext.SDL_INIT_EVERYTHING) != 0) { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize runtime"); return error.InitFailure; } defer ext.SDL_Quit(); const window = create_window: { const pos = ext.SDL_WINDOWPOS_UNDEFINED; var flags = @as(u32, 0); break: create_window ext.SDL_CreateWindow("Ona", pos, pos, 640, 480, flags) orelse { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to create window"); return error.InitFailure; }; }; defer ext.SDL_DestroyWindow(window); const renderer = create_renderer: { var flags = @as(u32, 0); break: create_renderer ext.SDL_CreateRenderer(window, -1, flags) orelse { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to create renderer"); return error.InitFailure; }; }; defer ext.SDL_DestroyRenderer(renderer); const user_path_prefix = ext.SDL_GetPrefPath("ona", "ona") orelse { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to load user path"); return error.InitFailure; }; defer ext.SDL_free(user_path_prefix); var app_context = AppContext.Implementation.init("./data.oar", user_path_prefix [0 .. std.mem.len(user_path_prefix)]) catch |err| { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, switch (err) { error.OutOfMemory => "Failed to allocate necessary memory", error.OutOfMutexes => "Failed to create file-system work lock", error.OutOfSemaphores => "Failed to create file-system work scheduler", }); return error.InitFailure; }; defer app_context.deinit(); app_context.start() catch |err| { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, switch (err) { // Not possible for it to have already been started. error.AlreadyStarted => unreachable, error.OutOfThreads => "Failed to start file-system work processor", }); return error.InitFailure; }; var graphics_context = GraphicsContext.Implementation{ .event = .{ }, }; return run(@ptrCast(*AppContext, &app_context), @ptrCast(*GraphicsContext, &graphics_context)); }