sdl3 hello world gpu working

This commit is contained in:
Peter Li 2025-04-11 13:57:04 -07:00
parent 6eb7036182
commit 3b65cdb8f5
9 changed files with 1749 additions and 808 deletions

View File

@ -1,141 +1,141 @@
pub const core = @import("core");
pub const platform = @import("platform");
pub const assets = @import("assets");
pub const audio = @import("audio");
pub const graphics = @import("graphics");
pub const vkImgui = @import("vkImgui");
pub const ui = @import("ui");
pub const papyrus = @import("papyrus");
pub const physics = @import("physics");
const modulelist = @import("modulelist.zig").list;
const std = @import("std");
pub const NwArgs = struct {
useGPA: bool = true, // slower zig based memory allocator, provides detailed tracking of leaks and memory violations
vulkanValidation: bool = true,
fastTest: bool = false,
dmt: bool = false, // detailed memory tracking, implements a timeline for tracking all memory allocations
fatDump: bool = false, // takes a full fat minidump on crash, very large files are produced
};
pub fn getArgs() !NwArgs {
const a = try core.ParseArgs(NwArgs);
return a;
}
// entry function for a backlog program
// when this function is called it will use the settings specified by the program spec
// to conditionally start up feature modules within the engine
var shutdownList: std.ArrayListUnmanaged(*const fn (std.mem.Allocator) void) = .{};
pub fn start_modules(comptime programSpec: anytype, maybeArgs: ?NwArgs, allocator: std.mem.Allocator) !void {
const Backlog = @This();
inline for (modulelist) |feature| {
if (@hasDecl(Backlog, feature)) {
const Struct = @field(Backlog, feature);
if (comptime core.isModuleEnabled(Struct.Module, programSpec)) {
if (maybeArgs) |args| {
try Struct.start_module(programSpec, args, allocator);
} else {
try Struct.start_module(programSpec, NwArgs{}, allocator);
}
try shutdownList.append(allocator, Struct.shutdown_module);
core.engine_logs("module started >>>> " ++ feature ++ " <<<<");
}
}
}
}
pub fn shutdown_modules(allocator: std.mem.Allocator) void {
var i: isize = @intCast(shutdownList.items.len - 1);
while (i >= 0) : (i -= 1) {
shutdownList.items[@intCast(i)](allocator);
}
shutdownList.deinit(allocator);
}
pub fn start_everything(comptime spec: anytype, allocator: std.mem.Allocator, maybeArgs: ?NwArgs) !void {
if (maybeArgs) |args| {
if (args.vulkanValidation)
graphics.setStartupSettings("vulkanValidation", true);
}
try start_modules(spec, maybeArgs, allocator);
}
pub fn shutdown_everything(allocator: std.mem.Allocator) void {
shutdown_modules(allocator);
}
pub fn run_everything(comptime GameContext: type) !void {
var canTick: bool = false;
if (@hasDecl(GameContext, "tick")) {
canTick = true;
}
var gameContext = try core.createObject(GameContext, .{ .can_tick = canTick });
if (@hasDecl(GameContext, "prepare_game")) {
gameContext.prepare_game() catch @panic("Unable to run base level prepare script");
} else if (@hasDecl(GameContext, "prepare")) {
gameContext.prepare() catch @panic("Unable to run base level prepare script");
}
try core.gEngine.run();
while (!core.gEngine.exitFinished()) {
const z = core.tracy.ZoneN(@src(), "shutdown poll");
platform.getInstance().pollEvents();
z.End();
}
}
pub fn initializeAndRunStandardProgram(comptime GameContext: type, comptime spec: anytype) !void {
const args = try getArgs();
var backingAllocator: std.mem.Allocator = std.heap.c_allocator;
var gpa: std.heap.GeneralPurposeAllocator(.{
.stack_trace_frames = 20,
}) = .{};
defer {
const cleanupStatus = gpa.deinit();
if (cleanupStatus == .leak) {
std.debug.print("gpa cleanup leaked memory\n", .{});
}
}
if (args.useGPA) {
backingAllocator = gpa.allocator();
}
const memory = core.MemoryTracker;
memory.MTSetup(backingAllocator, .{ .timeline = args.dmt });
defer memory.MTShutdown();
var tracker = memory.MTGet().?;
const allocator = tracker.allocator();
if (args.vulkanValidation) {
core.engine_logs("Using vulkan validation");
}
graphics.setStartupSettings("vulkanValidation", args.vulkanValidation);
if (@hasField(@TypeOf(spec), "windowName")) {
platform.setWindowSettings(.{ .windowName = spec.windowName });
} else {
platform.setWindowSettings(.{ .windowName = spec.name });
}
try start_everything(spec, allocator, args);
defer shutdown_everything(allocator);
try run_everything(GameContext);
}
pub const core = @import("core");
pub const platform = @import("platform");
pub const assets = @import("assets");
pub const audio = @import("audio");
pub const graphics = @import("graphics");
pub const vkImgui = @import("vkImgui");
pub const ui = @import("ui");
pub const papyrus = @import("papyrus");
pub const physics = @import("physics");
const modulelist = @import("modulelist.zig").list;
const std = @import("std");
pub const NwArgs = struct {
useGPA: bool = true, // slower zig based memory allocator, provides detailed tracking of leaks and memory violations
vulkanValidation: bool = true,
fastTest: bool = false,
dmt: bool = false, // detailed memory tracking, implements a timeline for tracking all memory allocations
fatDump: bool = false, // takes a full fat minidump on crash, very large files are produced
};
pub fn getArgs() !NwArgs {
const a = try core.ParseArgs(NwArgs);
return a;
}
// entry function for a backlog program
// when this function is called it will use the settings specified by the program spec
// to conditionally start up feature modules within the engine
var shutdownList: std.ArrayListUnmanaged(*const fn (std.mem.Allocator) void) = .{};
pub fn start_modules(comptime programSpec: anytype, maybeArgs: ?NwArgs, allocator: std.mem.Allocator) !void {
const Backlog = @This();
inline for (modulelist) |feature| {
if (@hasDecl(Backlog, feature)) {
const Struct = @field(Backlog, feature);
if (comptime core.isModuleEnabled(Struct.Module, programSpec)) {
if (maybeArgs) |args| {
try Struct.start_module(programSpec, args, allocator);
} else {
try Struct.start_module(programSpec, NwArgs{}, allocator);
}
try shutdownList.append(allocator, Struct.shutdown_module);
core.engine_logs("module started >>>> " ++ feature ++ " <<<<");
}
}
}
}
pub fn shutdown_modules(allocator: std.mem.Allocator) void {
var i: isize = @intCast(shutdownList.items.len - 1);
while (i >= 0) : (i -= 1) {
shutdownList.items[@intCast(i)](allocator);
}
shutdownList.deinit(allocator);
}
pub fn start_everything(comptime spec: anytype, allocator: std.mem.Allocator, maybeArgs: ?NwArgs) !void {
if (maybeArgs) |args| {
if (args.vulkanValidation)
graphics.setStartupSettings("vulkanValidation", true);
}
try start_modules(spec, maybeArgs, allocator);
}
pub fn shutdown_everything(allocator: std.mem.Allocator) void {
shutdown_modules(allocator);
}
pub fn run_everything(comptime GameContext: type) !void {
var canTick: bool = false;
if (@hasDecl(GameContext, "tick")) {
canTick = true;
}
var gameContext = try core.createObject(GameContext, .{ .can_tick = canTick });
if (@hasDecl(GameContext, "prepare_game")) {
gameContext.prepare_game() catch @panic("Unable to run base level prepare script");
} else if (@hasDecl(GameContext, "prepare")) {
gameContext.prepare() catch @panic("Unable to run base level prepare script");
}
try core.gEngine.run();
while (!core.gEngine.exitFinished()) {
const z = core.tracy.ZoneN(@src(), "shutdown poll");
platform.getInstance().pollEvents();
z.End();
}
}
pub fn initializeAndRunStandardProgram(comptime GameContext: type, comptime spec: anytype) !void {
const args = try getArgs();
var backingAllocator: std.mem.Allocator = std.heap.c_allocator;
var gpa: std.heap.GeneralPurposeAllocator(.{
.stack_trace_frames = 20,
}) = .{};
defer {
const cleanupStatus = gpa.deinit();
if (cleanupStatus == .leak) {
std.debug.print("gpa cleanup leaked memory\n", .{});
}
}
if (args.useGPA) {
backingAllocator = gpa.allocator();
}
const memory = core.MemoryTracker;
memory.MTSetup(backingAllocator, .{ .timeline = args.dmt });
defer memory.MTShutdown();
var tracker = memory.MTGet().?;
const allocator = tracker.allocator();
if (args.vulkanValidation) {
core.engine_logs("Using vulkan validation");
}
graphics.setStartupSettings("vulkanValidation", args.vulkanValidation);
if (@hasField(@TypeOf(spec), "windowName")) {
platform.setWindowSettings(.{ .windowName = spec.windowName });
} else {
platform.setWindowSettings(.{ .windowName = spec.name });
}
try start_everything(spec, allocator, args);
defer shutdown_everything(allocator);
try run_everything(GameContext);
}

View File

@ -2231,7 +2231,7 @@ extern SDL_DECLSPEC const char * SDLCALL SDL_GetGPUDriver(int index);
/**
* Returns the name of the backend used to create this GPU context.
*
* \param device a GPU context to query.
* \returns the name of the device's driver, or NULL on error.
*

118
lib/sdl3/src/events.zig vendored Normal file
View File

@ -0,0 +1,118 @@
pub const first: u32 = 0;
pub const quit: u32 = 256;
pub const terminating: u32 = 257;
pub const low_memory: u32 = 258;
pub const will_enter_background: u32 = 259;
pub const did_enter_background: u32 = 260;
pub const will_enter_foreground: u32 = 261;
pub const did_enter_foreground: u32 = 262;
pub const locale_changed: u32 = 263;
pub const system_theme_changed: u32 = 264;
pub const display_orientation: u32 = 337;
pub const display_added: u32 = 338;
pub const display_removed: u32 = 339;
pub const display_moved: u32 = 340;
pub const display_desktop_mode_changed: u32 = 341;
pub const display_current_mode_changed: u32 = 342;
pub const display_content_scale_changed: u32 = 343;
pub const display_first: u32 = 337;
pub const display_last: u32 = 343;
pub const window_shown: u32 = 514;
pub const window_hidden: u32 = 515;
pub const window_exposed: u32 = 516;
pub const window_moved: u32 = 517;
pub const window_resized: u32 = 518;
pub const window_pixel_size_changed: u32 = 519;
pub const window_metal_view_resized: u32 = 520;
pub const window_minimized: u32 = 521;
pub const window_maximized: u32 = 522;
pub const window_restored: u32 = 523;
pub const window_mouse_enter: u32 = 524;
pub const window_mouse_leave: u32 = 525;
pub const window_focus_gained: u32 = 526;
pub const window_focus_lost: u32 = 527;
pub const window_close_requested: u32 = 528;
pub const window_hit_test: u32 = 529;
pub const window_iccprof_changed: u32 = 530;
pub const window_display_changed: u32 = 531;
pub const window_display_scale_changed: u32 = 532;
pub const window_safe_area_changed: u32 = 533;
pub const window_occluded: u32 = 534;
pub const window_enter_fullscreen: u32 = 535;
pub const window_leave_fullscreen: u32 = 536;
pub const window_destroyed: u32 = 537;
pub const window_hdr_state_changed: u32 = 538;
pub const window_first: u32 = 514;
pub const window_last: u32 = 538;
pub const key_down: u32 = 768;
pub const key_up: u32 = 769;
pub const text_editing: u32 = 770;
pub const text_input: u32 = 771;
pub const keymap_changed: u32 = 772;
pub const keyboard_added: u32 = 773;
pub const keyboard_removed: u32 = 774;
pub const text_editing_candidates: u32 = 775;
pub const mouse_motion: u32 = 1024;
pub const mouse_button_down: u32 = 1025;
pub const mouse_button_up: u32 = 1026;
pub const mouse_wheel: u32 = 1027;
pub const mouse_added: u32 = 1028;
pub const mouse_removed: u32 = 1029;
pub const joystick_axis_motion: u32 = 1536;
pub const joystick_ball_motion: u32 = 1537;
pub const joystick_hat_motion: u32 = 1538;
pub const joystick_button_down: u32 = 1539;
pub const joystick_button_up: u32 = 1540;
pub const joystick_added: u32 = 1541;
pub const joystick_removed: u32 = 1542;
pub const joystick_battery_updated: u32 = 1543;
pub const joystick_update_complete: u32 = 1544;
pub const gamepad_axis_motion: u32 = 1616;
pub const gamepad_button_down: u32 = 1617;
pub const gamepad_button_up: u32 = 1618;
pub const gamepad_added: u32 = 1619;
pub const gamepad_removed: u32 = 1620;
pub const gamepad_remapped: u32 = 1621;
pub const gamepad_touchpad_down: u32 = 1622;
pub const gamepad_touchpad_motion: u32 = 1623;
pub const gamepad_touchpad_up: u32 = 1624;
pub const gamepad_sensor_update: u32 = 1625;
pub const gamepad_update_complete: u32 = 1626;
pub const gamepad_steam_handle_updated: u32 = 1627;
pub const finger_down: u32 = 1792;
pub const finger_up: u32 = 1793;
pub const finger_motion: u32 = 1794;
pub const finger_canceled: u32 = 1795;
pub const clipboard_update: u32 = 2304;
pub const drop_file: u32 = 4096;
pub const drop_text: u32 = 4097;
pub const drop_begin: u32 = 4098;
pub const drop_complete: u32 = 4099;
pub const drop_position: u32 = 4100;
pub const audio_device_added: u32 = 4352;
pub const audio_device_removed: u32 = 4353;
pub const audio_device_format_changed: u32 = 4354;
pub const sensor_update: u32 = 4608;
pub const pen_proximity_in: u32 = 4864;
pub const pen_proximity_out: u32 = 4865;
pub const pen_down: u32 = 4866;
pub const pen_up: u32 = 4867;
pub const pen_button_down: u32 = 4868;
pub const pen_button_up: u32 = 4869;
pub const pen_motion: u32 = 4870;
pub const pen_axis: u32 = 4871;
pub const camera_device_added: u32 = 5120;
pub const camera_device_removed: u32 = 5121;
pub const camera_device_approved: u32 = 5122;
pub const camera_device_denied: u32 = 5123;
pub const render_targets_reset: u32 = 8192;
pub const render_device_reset: u32 = 8193;
pub const render_device_lost: u32 = 8194;
pub const private0: u32 = 16384;
pub const private1: u32 = 16385;
pub const private2: u32 = 16386;
pub const private3: u32 = 16387;
pub const poll_sentinel: u32 = 32512;
pub const user: u32 = 32768;
pub const last: u32 = 65535;
pub const enum_padding: u32 = 2147483647;

View File

@ -1,4 +1,5 @@
import os
import sys
from pprint import pprint
import math
@ -23,29 +24,47 @@ def convertCase(x):
origDir = os.path.abspath(os.path.dirname(__file__))
os.chdir(origDir)
gpufile = "../../SDL/include/SDL3/SDL_gpu.h"
infile = "../../SDL/include/SDL3/SDL_gpu.h"
ofile = os.path.abspath(os.path.join(origDir, '../gpu.zig'))
mode_default = 0
mode_collecting = 1
SDL_files = [
'SDL_gpu.h',
]
typedefs_pod = []
typedefs_opaque = []
typedefs_enum = []
typedefs_struct = []
typedefs_unknown = []
functions = []
typeMap = {
'Uint32': 'u32', 'float': 'f32', 'Sint32': 'i32', 'bool': 'bool', 'Uint8': 'u8', 'SDL_PropertiesID': 'PropertiesID','char': 'u8',
'void': 'void',
'int': 'c_int',
'size_t': 'usize',
'SDL_Window': 'Window',
}
defines = []
typeMap_r = {}
lastList = None
def generateAll(infile, ofile):
with open(gpufile) as rf:
mode = mode_default
braceCount = 0
f = rf.readlines()
mode_default = 0
mode_collecting = 1
x = [ y + '\n' for y in """
typedefs_pod = []
typedefs_opaque = []
typedefs_enum = []
typedefs_struct = []
typedefs_unknown = []
functions = []
defines = []
lastList = None
with open(infile) as rf:
mode = mode_default
braceCount = 0
f = rf.readlines()
x = [ y + '\n' for y in """
typedef struct SDL_FColor {
float r;
@ -54,342 +73,527 @@ typedef struct SDL_FColor {
float a;
} SDL_FColor;
typedef struct SDL_Rect
{
int x;
int y;
int w;
int h;
} SDL_Rect;
typedef enum SDL_FlipMode {
SDL_FLIP_NONE, /**< Do not flip */
SDL_FLIP_HORIZONTAL, /**< flip horizontally */
SDL_FLIP_VERTICAL /**< flip vertically */
} SDL_FlipMode;
""".split('\n')]
""".split('\n')]
f += x
f += x
for l in f:
dropped = True
line = l.strip()
if mode == mode_default:
if line.startswith('typedef'):
if ";" in line and 'struct' in line:
typedefs_opaque.append(line)
for l in f:
dropped = True
line = l.strip()
if mode == mode_default:
if line.startswith('typedef'):
if ";" in line and 'struct' in line:
typedefs_opaque.append(line)
dropped = False
elif ';' in line:
typedefs_pod.append(line)
dropped = False
elif 'enum' in line:
lastList = typedefs_enum
typedefs_enum.append(line)
dropped = False
elif 'struct' in line:
lastList = typedefs_struct
typedefs_struct.append(line)
dropped = False
else:
lastList = typedefs_unknown
dropped = False
typedefs_unknown.append(line)
elif line.startswith('extern SDL_DECLSPEC'):
lastList = functions
dropped = False
elif ';' in line:
typedefs_pod.append(line)
dropped = False
elif 'enum' in line:
lastList = typedefs_enum
typedefs_enum.append(line)
dropped = False
elif 'struct' in line:
lastList = typedefs_struct
typedefs_struct.append(line)
dropped = False
else:
lastList = typedefs_unknown
dropped = False
typedefs_unknown.append(line)
functions.append(line)
elif line.startswith('extern SDL_DECLSPEC'):
lastList = functions
dropped = False
functions.append(line)
elif line.startswith('#define '):
lastList = defines
defines.append(line)
elif line.startswith('#define '):
lastList = defines
defines.append(line)
if ';' not in line and not dropped:
mode = mode_collecting
if "{" in l:
braceCount = 1
if ';' not in line and not dropped:
mode = mode_collecting
if "{" in l:
braceCount = 1
elif mode == mode_collecting:
lastList[-1] += l.replace('\n', '\n')
elif mode == mode_collecting:
lastList[-1] += l.replace('\n', '\n')
if "{" in line:
braceCount += 1
if "{" in line:
braceCount += 1
if "}" in line:
braceCount -= 1
if "}" in line:
braceCount -= 1
if ';' in line and braceCount == 0:
mode = mode_default
if ';' in line and braceCount == 0:
mode = mode_default
print_types = False
print_functions = False
print_defines= False
print_types = False
print_functions = False
print_defines= False
def plos(l):
for s in l:
print('> ', s, " < ")
def plos(l):
for s in l:
print('> ', s, " < ")
print('struct')
print('struct')
# plos(typedefs_struct)
print('pod')
plos(typedefs_pod)
if print_types:
print('opaque')
plos(typedefs_opaque)
print('pod')
plos(typedefs_pod)
print('enum')
plos(typedefs_enum)
print('unknown')
plos(typedefs_unknown)
if print_types:
print('opaque')
plos(typedefs_opaque)
print('pod')
plos(typedefs_pod)
print('enum')
plos(typedefs_enum)
print('unknown')
plos(typedefs_unknown)
if print_functions:
print('functions')
plos(functions)
if print_functions:
print('functions')
plos(functions)
if print_defines:
print('defines')
plos(defines)
if print_defines:
print('defines')
plos(defines)
print(f"\nfunctions: {len(functions)}, structs:{len(typedefs_struct)}, enums:{len(typedefs_enum)}\n")
print(f"\nfunctions: {len(functions)}, structs:{len(typedefs_struct)}, enums:{len(typedefs_enum)}\n")
ostring = 'pub const c = @import("c.zig").c;\n\npub const PropertiesID = u32;'
ostring = 'pub const c = @import("c.zig").c;\n\npub const PropertiesID = u32;\n pub const Window = c.SDL_Window;'
# time to generate types...
# first the opaques
ostring += '\n'
ostring += '\n'
typeMap = {
'Uint32': 'u32', 'float': 'f32', 'Sint32': 'i32', 'bool': 'bool', 'Uint8': 'u8', 'SDL_PropertiesID': 'PropertiesID','char': 'i8',
'size_t': 'usize',
'SDL_FColor': 'FColor',
'SDL_FlipMode': 'FlipMode'
}
opaques = {'Window': ''}
enums = {}
typeMap_r = {}
opaqueOrder = []
for t in typedefs_pod:
c_typename = t.strip().strip(';').split(' ')[-1]
typename = c_typename
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
# todo generate packed flags for each one
for t in typedefs_opaque:
c_typename = t.strip().strip(';').split(' ')[3]
typename = c_typename
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
brackets = "{}"
definition = f"pub const {typename} = opaque {{\n"
# ostring += definition
opaques[typename] = definition
opaqueOrder.append(typename)
for t in typedefs_pod:
c_typename = t.strip().strip(';').split(' ')[-1]
typename = c_typename
ostring += '\n'
if typename.startswith("SDL_"):
typename = typename[4:]
packedFlags = [
('SDL_GPUTextureUsageFlags', 'Uint32', [
('SDL_GPU_TEXTUREUSAGE_SAMPLER', 1 << 0),
('SDL_GPU_TEXTUREUSAGE_COLOR_TARGET', 1 << 1),
('SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET', 1 << 2),
('SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ', 1 << 3),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ', 1 << 4),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE', 1 << 5),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE', 1 << 6),
('rsvd', 1 << 31)
]),
('SDL_GPUBufferUsageFlags', 'Uint32', [
('SDL_GPU_BUFFERUSAGE_VERTEX', (1 << 0)),
('SDL_GPU_BUFFERUSAGE_INDEX', (1 << 1)),
('SDL_GPU_BUFFERUSAGE_INDIRECT', (1 << 2)),
('SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ', (1 << 3)),
('SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ', (1 << 4)),
('SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE', (1 << 5)),
('rsvd', 1 << 31)
]),
('SDL_GPUColorComponentFlags', 'Uint8', [
('SDL_GPU_COLORCOMPONENT_R', (1 << 0)),
('SDL_GPU_COLORCOMPONENT_G', (1 << 1)),
('SDL_GPU_COLORCOMPONENT_B', (1 << 2)),
('SDL_GPU_COLORCOMPONENT_A', (1 << 3)),
('rsvd', 1 << 7)
]),
('SDL_GPUShaderFormat', 'Uint32', [
('SDL_GPU_SHADERFORMAT_PRIVATE', (1 << 0)),
('SDL_GPU_SHADERFORMAT_SPIRV', (1 << 1)),
('SDL_GPU_SHADERFORMAT_DXBC', (1 << 2)),
('SDL_GPU_SHADERFORMAT_DXIL', (1 << 3)),
('SDL_GPU_SHADERFORMAT_MSL', (1 << 4)),
('SDL_GPU_SHADERFORMAT_METALLIB', (1 << 5)),
('rsvd', 1 << 31)
], [('Invalid', '.{}')]),
]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
# todo generate packed flags for each one
def makePackedFlags(typename, backingtype, flagList, constants=None):
global typeMap
global typeMap_r
for t in typedefs_opaque:
c_typename = t.strip().strip(';').split(' ')[3]
typename = c_typename
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
rv = 'pub const ' + typename + ' = packed struct(' + typeMap[backingtype] + ') {\n'
brackets = "{}"
definition = f"pub const {typename} = opaque{brackets};\n"
ostring += definition
offset = 0
padcount = 0
for flag in flagList:
name = flag[0]
targetOffset = math.log2(flag[1])
ostring += '\n'
if 'SDL_GPU_' in name:
name = name[8:]
name = convertCase(name)
packedFlags = [
('SDL_GPUTextureUsageFlags', 'Uint32', [
('SDL_GPU_TEXTUREUSAGE_SAMPLER', 1 << 0),
('SDL_GPU_TEXTUREUSAGE_COLOR_TARGET', 1 << 1),
('SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET', 1 << 2),
('SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ', 1 << 3),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ', 1 << 4),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE', 1 << 5),
('SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE', 1 << 6),
]),
('SDL_GPUBufferUsageFlags', 'Uint32', [
('SDL_GPU_BUFFERUSAGE_VERTEX', (1 << 0)),
('SDL_GPU_BUFFERUSAGE_INDEX', (1 << 1)),
('SDL_GPU_BUFFERUSAGE_INDIRECT', (1 << 2)),
('SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ', (1 << 3)),
('SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ', (1 << 4)),
('SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE', (1 << 5)),
]),
('SDL_GPUColorComponentFlags', 'Uint8', [
('SDL_GPU_COLORCOMPONENT_R', (1 << 0)),
('SDL_GPU_COLORCOMPONENT_G', (1 << 1)),
('SDL_GPU_COLORCOMPONENT_B', (1 << 2)),
('SDL_GPU_COLORCOMPONENT_A', (1 << 3)),
]),
('SDL_GPUShaderFormat', 'Uint32', [
('SDL_GPU_SHADERFORMAT_PRIVATE', (1 << 0)),
('SDL_GPU_SHADERFORMAT_SPIRV', (1 << 1)),
('SDL_GPU_SHADERFORMAT_DXBC', (1 << 2)),
('SDL_GPU_SHADERFORMAT_DXIL', (1 << 3)),
('SDL_GPU_SHADERFORMAT_MSL', (1 << 4)),
('SDL_GPU_SHADERFORMAT_METALLIB', (1 << 5)),
], [('Invalid', '.{}')]),
]
if targetOffset != offset:
diff = int(targetOffset - offset)
rv += ' ' + 'pad' + str(padcount) + ': u' + str(diff) + ' = 0,\n'
padcount += 1
offset = targetOffset
def makePackedFlags(typename, backingtype, flagList, constants=None):
global typeMap
global typeMap_r
rv += ' ' + name + ': bool = false,\n'
offset += 1
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
if constants is not None:
for constant in constants:
rv += f' pub const {constant[0]}: @This() = {constant[1]};\n'
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
rv += '};\n'
rv = 'pub const ' + typename + ' = packed struct(' + typeMap[backingtype] + ') {\n'
return rv
offset = 0
padcount = 0
for flag in flagList:
name = flag[0]
targetOffset = math.log2(flag[1])
ostring += '\n'
if 'SDL_GPU_' in name:
name = name[8:]
name = convertCase(name)
for p in packedFlags:
ostring += makePackedFlags(*p)
if targetOffset != offset:
diff = int(targetOffset - offset)
rv += ' ' + 'pad' + str(padcount) + ': u' + str(diff) + ' = 0,\n'
padcount += 1
offset = targetOffset
for t in typedefs_enum:
typename = t.split("}")[1].strip('\n ;')
#print("E", typename, t)
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
rv += ' ' + name + ': bool = false,\n'
offset += 1
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
enums[typename] = ""
if constants is not None:
for constant in constants:
rv += f' pub const {constant[0]}: @This() = {constant[1]};\n'
# print(t)
rv += '};\n'
inners = t.strip().split('\n')[1:-1]
e = []
return rv
ostring += '\n'
for p in packedFlags:
ostring += makePackedFlags(*p)
for t in typedefs_enum:
typename = t.split("}")[1].strip('\n ;')
#print("E", typename, t)
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
# print(t)
inners = t.strip().split('\n')[1:-1]
e = []
for i in range(0, len(inners)):
line = inners[i]
if ',' in line or line == inners[-1]:
e.append(line.strip())
for i in range(0, len(inners)):
line = inners[i]
if ',' in line or line == inners[-1]:
e.append(line.strip())
for i in range(0, len(e)):
e[i] = e[i].replace('/*', '//')
e[i] = e[i].replace('SDL_GPU_', '')
for i in range(0, len(e)):
e[i] = e[i].replace('/*', '//')
e[i] = e[i].replace('SDL_GPU_', '')
if ',' not in e[i]:
count = 0
for x in e[i]:
if x == ' ':
break
count += 1
if ',' not in e[i]:
count = 0
for x in e[i]:
if x == ' ':
break
count += 1
e[i] = e[i][:count] + ',' + e[i][count:]
e[i] = e[i][:count] + ',' + e[i][count:]
r = e[i].split(',')
r = e[i].split(',')
r[0] = convertCase(r[0])
r[0] = convertCase(r[0])
e[i] = r[0] + ',' + r[1]
common = os.path.commonprefix(e)
#print(common)
#plos(e)
e[i] = r[0] + ',' + r[1]
common = os.path.commonprefix(e)
#print(common)
#plos(e)
ostring += 'pub const ' + typename + ' = ' + 'enum {\n'
for i in e:
ostring += ' ' + i + '\n'
ostring += '};\n\n'
ostring += 'pub const ' + typename + ' = ' + 'enum(c_int) {\n'
for i in e:
ostring += ' ' + i + '\n'
ostring += '};\n\n'
for t in typedefs_struct:
typename = t.split("}")[1].strip('\n ;')
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
for t in typedefs_struct:
typename = t.split("}")[1].strip('\n ;')
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
for t in typedefs_struct:
for t in typedefs_struct:
typename = t.split("}")[1].strip('\n ;')
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
typename = t.split("}")[1].strip('\n ;')
c_typename = typename
if typename.startswith("SDL_"):
typename = typename[4:]
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
typeMap[c_typename] = typename
typeMap_r[typename] = c_typename
inner = t.strip("\n ").split('\n')[1:-1]
inner = t.strip("\n ").split('\n')[1:-1]
# print("----", typename)
for i in range(0, len(inner)):
inner[i] = inner[i].replace('/*', "//")
inner[i] = inner[i].replace('*<', "")
inner[i] = inner[i].replace('*/', "")
# print("----", typename)
for i in range(0, len(inner)):
inner[i] = inner[i].replace('/*', "//")
inner[i] = inner[i].replace('*<', "")
inner[i] = inner[i].replace('*/', "")
fields = []
fields = []
for txt in inner:
s = txt.split(';')
decl = s[0].strip()
comment = ""
if len(s) > 1:
comment = s[1].strip()
for txt in inner:
s = txt.split(';')
decl = s[0].strip()
comment = ""
if len(s) > 1:
comment = s[1].strip()
fieldType = " ".join(decl.split(' ')[:-1])
name = decl.split(' ')[-1]
const = False
pointer = False
fieldType = " ".join(decl.split(' ')[:-1])
name = decl.split(' ')[-1]
const = False
pointer = False
if fieldType.startswith('const'):
fieldType = fieldType[5:].strip()
const = True
if fieldType.startswith('const'):
fieldType = fieldType[5:].strip()
const = True
if name.startswith('*'):
pointer = True;
name = name.strip('*')
if name.startswith('*'):
pointer = True;
name = name.strip('*')
if fieldType != '' and name != '':
fields.append((fieldType, name, const, comment, pointer))
# not implemented
if '[' in name:
assert False
if fieldType != '' and name != '':
fields.append((fieldType, name, const, comment, pointer))
if '[' in fieldType:
assert False
# not implemented
if '[' in name:
assert False
tstr = "pub const " + typename + " = extern struct {\n"
if '[' in fieldType:
assert False
for field in fields:
tstr += ' ' + field[1] + ': ' + ('*' if field[4] else '') + ('const ' if field[2] else '') + typeMap[field[0]] + ', ' + field[3] + ' \n'
tstr = "pub const " + typename + " = extern struct {\n"
tstr += '};\n'
for field in fields:
typestring = typeMap[field[0]]
ptr = '[*c]'
if typestring in opaques:
ptr = '*'
tstr += ' ' + field[1] + ': ' + (ptr if field[4] else '') + ('const ' if field[2] else '') + typestring + ', ' + field[3] + ' \n'
ostring += tstr + "\n"
tstr += '};\n'
for t in functions:
print(t)
ostring += tstr + "\n"
# print (ostring)
for t in functions:
funcname = None
with open(os.path.abspath(os.path.join(origDir, '../gpu.zig')), 'w') as f:
f.write(ostring)
s = t[len("extern SDL_DECLSPEC "):].split('(')
label = s[0]
args = s[1].replace('\n', '')
def findTypeFromLabel(label):
pointerCount = label.count('*')
label = label.split(' ')
typeStr = None
isConst = False
if label[0] == 'const':
isConst = True
if isConst:
typeStr = 'const ' + typeMap[label[1]]
else:
typeStr = typeMap[label[0]]
for i in range(0, pointerCount):
if typeStr.split(' ')[-1] in opaques:
typeStr = '*' + typeStr
else:
typeStr = '[*c]' + typeStr
if typeStr == '*void':
typeStr = '*anyopaque'
if typeStr == '*const u8':
return '[*c]const u8'
return typeStr
def getArgsListFromArgs(t, args):
rv = []
if args.strip(' );') == 'void':
return rv
l = args.replace(')', '')
l = l.replace(';', '')
l = l.split(',')
l2 = []
for x in l:
l2.append(x.strip())
print(l2)
for i in l2:
x = findTypeFromLabel(i)
print("type: ", i, '>', x, '<')
y = i.split(' ')[-1].replace('*', '')
if y == 'type':
y = '_type'
v = (x, y)
rv.append(v)
print(v)
return rv
def findFuncFromLabel(label):
rv = ''
rv = label.split(' ')[-1]
if rv.startswith('SDL_'):
rv = rv[4:]
if rv.startswith('GPU'):
rv = 'gpu' + rv[3:]
if rv.startswith('GDK'):
rv = 'gdk' + rv[3:]
rv = rv[0].lower() + rv[1:]
return rv
argsList = getArgsListFromArgs(t, args)
rtype = findTypeFromLabel(label)
funcLabel = findFuncFromLabel(label)
funcargs = ''
first = True
body = ''
for arg in argsList:
if first:
first = False
else:
funcargs += ', '
funcargs += arg[1] + ': ' + arg[0]
# body += ' _ = ' + arg[1] + ';\n'
cfunc = label.split(' ')[-1].strip()
funcstring = '// ' + label.split(' ')[-1] + '\n'
funcstring += 'pub inline fn ' + funcLabel + '('+ funcargs + ') ' + rtype + ' {\n'
bitCastRtype = False
ptrCastRtype = False
enumCastRtype = False
if rtype is not None and rtype != 'void':
funcstring += ' return '
if rtype == '[*c]const u8' or rtype.strip('*') in opaques:
ptrCastRtype = True
elif rtype in enums:
enumCastRtype = True
elif rtype != 'bool' and rtype != 'void':
print('rtype === ', rtype)
bitCastRtype = True
else:
funcstring += ' '
if ptrCastRtype:
funcstring += '@ptrCast('
if bitCastRtype:
funcstring += '@bitCast('
if enumCastRtype:
funcstring += '@enumFromInt('
funcstring += 'c.' + cfunc + '('
first = True
selfArg = None
for arg in argsList:
argType = arg[0]
argName = arg[1]
if first:
first = False
if argType.strip('*') in opaques:
selfArg = argType.strip('*')
else:
funcstring += ', '
if argType == 'bool' or argType == '[*c]const u8':
funcstring += argName
elif '*' in argType:
funcstring += '@ptrCast(' + argName + ')'
else:
funcstring += '@bitCast(' + argName + ')'
if bitCastRtype or ptrCastRtype or enumCastRtype:
funcstring += ')'
funcstring += ');\n'
funcstring += body
funcstring += '}\n\n'
if selfArg is not None:
opaques[selfArg] += funcstring
else:
ostring += funcstring
for opaque in opaques:
opaques[opaque] += '};\n\n'
for opaque in opaqueOrder:
ostring += opaques[opaque]
with open(ofile, 'w') as f:
f.write(ostring)
subprocess.run(['zig', 'fmt', ofile])
generateAll(infile, ofile)

0
lib/sdl3/src/generators/shared.py vendored Normal file
View File

1183
lib/sdl3/src/gpu.zig vendored

File diff suppressed because it is too large Load Diff

39
lib/sdl3/src/init.zig vendored
View File

@ -1,39 +0,0 @@
pub const c = @cImport({ // todo, should not be constant
@cInclude("SDL3/SDL.h");
});
pub const InitOptions = packed struct(c_int) {
pad0: u4 = 0, // 0 - 3
audio: bool = false, // 4
video: bool = false, // 5
pad1: u2 = 0, // 6-7
pad2: u1 = 0, // 8
joystick: bool = false, // 9
pad3: u2 = 0, // 10-11
haptic: bool = false, // 12
gamepad: bool = false,
events: bool = false,
sensor: bool = false,
camera: bool = false,
pad4: u3 = 0,
pad5: u12 = 0,
};
pub const AppResult = enum{
app_continue,
app_success,
app_failure,
};
pub const Window = opaque {};
pub fn createWindow() !*Window {
return @ptrCast();
}
pub fn init(options: InitOptions) !void {
if (!c.SDL_Init(@bitCast(options))) {
return error.InitFailed;
}
}

View File

@ -4,9 +4,17 @@ timer: std.time.Timer,
// fillPipeline: *sdl3.GpuGraphicsPipeline = undefined,
// linePipeline: *sdl3.GpuGraphicsPipeline = undefined,
// viewport: sdl3.GpuViewport = undefined,
// scissor: sdl3.Rect = undefined,
scissor: gpu.Rect = .{ .x = 0, .y = 0, .w = 640, .h = 480 },
running: bool = true,
window: *sdl3.Window = undefined,
device: *gpu.GPUDevice = undefined,
shaderpath: []const u8 = undefined,
shadersuffix: []const u8 = undefined,
fragment: *gpu.GPUShader = undefined,
vertex: *gpu.GPUShader = undefined,
pipeline: *gpu.GPUGraphicsPipeline = undefined,
shaderformat: gpu.GPUShaderFormat = undefined,
pub fn create(allocator: std.mem.Allocator) !*@This() {
const self = try allocator.create(@This());
@ -24,10 +32,92 @@ pub fn startContext(self: *@This()) !void {
.gamepad = true,
});
const window = sdl3.c.SDL_CreateWindow("lmao your mom", 640, 480, 0);
_ = window;
self.window = sdl3.c.SDL_CreateWindow("hello-world", 640, 480, 0).?;
self.device = gpu.createGPUDevice(.{
.shaderformatSpirv = true,
.shaderformatDxil = true,
.shaderformatMsl = true,
}, false, null);
_ = self;
if (!self.device.claimWindowForGPUDevice(self.window))
return error.UnableToClaimGpu;
const formats = self.device.getGPUShaderFormats();
std.debug.print("SDL Context Loaded: {}\n", .{formats});
if (formats.shaderformatSpirv) {
self.shaderpath = "./content/_cooked/spv"; // shaderformatSpirv
self.shadersuffix = ".spv";
self.shaderformat = .{ .shaderformatSpirv = true };
} else if (formats.shaderformatMsl) {
self.shaderpath = "./content/_cooked/msl"; // shaderformatSpirv
self.shadersuffix = ".msl";
self.shaderformat = .{ .shaderformatMsl = true };
} else if (formats.shaderformatDxil) {
self.shaderpath = "./content/_cooked/dxil"; // shaderformatSpirv
self.shadersuffix = ".dxil";
self.shaderformat = .{ .shaderformatDxil = true };
}
self.fragment = try self.loadShader("hello-triangle.frag", .shaderstageFragment, 0, 0, 0, 0);
self.vertex = try self.loadShader("hello-triangle.vert", .shaderstageVertex, 0, 0, 0, 0);
var pci = std.mem.zeroes(gpu.GPUGraphicsPipelineCreateInfo);
pci.fragment_shader = self.fragment;
pci.vertex_shader = self.vertex;
pci.target_info.num_color_targets = 1;
pci.target_info.color_target_descriptions = &[_]gpu.GPUColorTargetDescription{
.{
.format = self.device.getGPUSwapchainTextureFormat(self.window),
.blend_state = std.mem.zeroes(gpu.GPUColorTargetBlendState),
},
};
pci.rasterizer_state.fill_mode = .fillmodeFill;
self.pipeline = self.device.createGPUGraphicsPipeline(&pci);
}
pub fn loadFileAlloc(filename: []const u8, comptime alignment: usize, allocator: std.mem.Allocator) ![]u8 {
var file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
const filesize = (try file.stat()).size + 1; // add null byte
const buffer: []align(alignment) u8 = try allocator.alignedAlloc(u8, alignment, filesize);
errdefer allocator.free(buffer);
try file.reader().readNoEof(buffer[0 .. buffer.len - 1]);
buffer[buffer.len - 1] = 0;
return buffer;
}
pub fn loadShader(
self: *@This(),
shaderName: []const u8,
stage: gpu.GPUShaderStage,
num_samplers: u32, // The number of samplers defined in the shader.
num_storage_textures: u32, // The number of storage textures defined in the shader.
num_storage_buffers: u32, // The number of storage buffers defined in the shader.
num_uniform_buffers: u32, // The number of uniform buffers defined in the shader.
) !*gpu.GPUShader {
const spath = try std.fmt.allocPrintZ(self.allocator, "{s}/{s}{s}", .{ self.shaderpath, shaderName, self.shadersuffix });
defer self.allocator.free(spath);
std.debug.print("loading shader {s}\n", .{spath});
const fileContents = try loadFileAlloc(spath, 8, self.allocator);
defer self.allocator.free(fileContents);
const sci = gpu.GPUShaderCreateInfo{
.code = @ptrCast(fileContents.ptr),
.entrypoint = "main",
.format = self.shaderformat,
.code_size = fileContents.len - 1,
.stage = stage,
.num_samplers = num_samplers,
.num_storage_textures = num_storage_textures, // The number of storage textures defined in the shader.
.num_storage_buffers = num_storage_buffers, // The number of storage buffers defined in the shader.
.num_uniform_buffers = num_uniform_buffers, // The number of uniform buffers defined in the shader.
.props = 0,
};
return self.device.createGPUShader(&sci);
}
pub fn loop(self: *@This()) !void {
@ -40,25 +130,53 @@ pub fn loop(self: *@This()) !void {
}
fn update(self: *@This(), dt: f64) void {
_ = dt;
while (sdl3.pollEvent()) |event| {
_ = event;
// std.debug.print("{any} \n", .{event});
switch (event.type) {
sdl_event.quit => {
self.running = false;
},
else => {},
}
self.draw(dt);
}
self.running = true;
}
pub fn draw(self: *@This(), dt: f64) void {
_ = dt;
const cmd = self.device.acquireGPUCommandBuffer();
var swapchain_texture: *gpu.GPUTexture = undefined;
if (cmd.waitAndAcquireGPUSwapchainTexture(self.window, &swapchain_texture, null, null)) {
var targetInfo: gpu.GPUColorTargetInfo = std.mem.zeroes(gpu.GPUColorTargetInfo);
targetInfo.texture = swapchain_texture;
targetInfo.clear_color = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 1.0 };
targetInfo.load_op = .loadopClear;
targetInfo.store_op = .storeopStore;
const renderpass = cmd.beginGPURenderPass(&targetInfo, 1, null);
renderpass.bindGPUGraphicsPipeline(self.pipeline);
renderpass.setGPUScissor(&self.scissor);
renderpass.drawGPUPrimitives(3, 1, 0, 0);
renderpass.endGPURenderPass();
}
_ = cmd.submitGPUCommandBuffer();
}
pub fn destroy(self: *@This()) void {
sdl3.c.SDL_DestroyWindow(self.window);
self.device.releaseWindowFromGPUDevice(self.window);
self.allocator.destroy(self);
}
pub fn main() !void {
std.debug.print("creating context", .{});
std.debug.print("hello world... n", .{});
const app = try create(std.heap.c_allocator);
try app.loop();
defer app.destroy();
}
const sdl3 = @import("sdl3");
const gpu = sdl3.gpu;
const sdl_event = sdl3.events;
const std = @import("std");

47
lib/sdl3/src/sdl3.zig vendored
View File

@ -1,4 +1,47 @@
const c = @import("c.zig").c;
pub const c = @import("c.zig").c;
pub const events = @import("events.zig");
pub const InitOptions = packed struct(c_int) {
pad0: u4 = 0, // 0 - 3
audio: bool = false, // 4
video: bool = false, // 5
pad1: u2 = 0, // 6-7
pad2: u1 = 0, // 8
joystick: bool = false, // 9
pad3: u2 = 0, // 10-11
haptic: bool = false, // 12
gamepad: bool = false,
events: bool = false,
sensor: bool = false,
camera: bool = false,
pad4: u3 = 0,
pad5: u12 = 0,
};
pub const AppResult = enum {
app_continue,
app_success,
app_failure,
};
pub const Window = c.SDL_Window;
pub const Event = c.SDL_Event;
pub const Rect = c.SDL_Rect;
pub fn init(options: InitOptions) !void {
if (!c.SDL_Init(@bitCast(options))) {
return error.InitFailed;
}
}
pub const EventType = events;
var gLastEvent: Event = undefined;
pub fn pollEvent() ?*Event {
if (c.SDL_PollEvent(&gLastEvent)) {
return &gLastEvent;
}
return null;
}
pub const gpu = @import("gpu.zig");
pub const init = @import("init.zig");