From e5a79621799f0e1c159c5ddac1bc560adc059460 Mon Sep 17 00:00:00 2001 From: m349pmma Date: Tue, 5 Sep 2023 20:10:32 +0200 Subject: [PATCH 01/50] Fixes VulkanWrapperModule not compilen as in #142 --- build.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.zig b/build.zig index e5a0317..6ff7550 100644 --- a/build.zig +++ b/build.zig @@ -206,6 +206,10 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { return sdk.build.createModule(.{ .source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, .dependencies = &.{ + .{ + .name = sdk.build.dupe("sdl-native"), + .module = sdk.getNativeModuleVulkan(vulkan), + }, .{ .name = sdk.build.dupe("vulkan"), .module = vulkan, From 3783d95386b906e6b7dba9fa136cef7d4791c494 Mon Sep 17 00:00:00 2001 From: jack Date: Sun, 8 Oct 2023 23:08:05 +0800 Subject: [PATCH 02/50] update to zig 0.12.0-dev.799+d68f39b54 --- src/wrapper/sdl.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index cfab407..68598ea 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -1390,7 +1390,7 @@ pub const JoyAxisEvent = struct { @floatFromInt(c.SDL_JOYSTICK_AXIS_MAX) else @floatFromInt(c.SDL_JOYSTICK_AXIS_MIN); - return @as(FloatType, @floatFromInt(self.value)) / @fabs(denominator); + return @as(FloatType, @floatFromInt(self.value)) / @abs(denominator); } }; @@ -1497,7 +1497,7 @@ pub const ControllerAxisEvent = struct { @floatFromInt(c.SDL_JOYSTICK_AXIS_MAX) else @floatFromInt(c.SDL_JOYSTICK_AXIS_MIN); - return @as(FloatType, @floatFromInt(self.value)) / @fabs(denominator); + return @as(FloatType, @floatFromInt(self.value)) / @abs(denominator); } }; From c6253b90d616af75122cd3e6f79222a314dc734b Mon Sep 17 00:00:00 2001 From: jack Date: Tue, 21 Nov 2023 23:01:24 +0800 Subject: [PATCH 03/50] update to zig 0.12.0-dev.1664+8ca4a5240 --- build.zig | 2 +- examples/native.zig | 4 ++-- src/binding/sdl.zig | 10 +++++----- src/wrapper/sdl.zig | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/build.zig b/build.zig index e5a0317..7cd45ff 100644 --- a/build.zig +++ b/build.zig @@ -457,7 +457,7 @@ fn getPaths(sdk: *Sdk, target_local: std.Target) error{ MissingTarget, FileNotFo else => |e| @panic(@errorName(e)), }; - var parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch return error.InvalidJson; + const parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch return error.InvalidJson; var root_node = parsed.value.object; var config_iterator = root_node.iterator(); while (config_iterator.next()) |entry| { diff --git a/examples/native.zig b/examples/native.zig index b197b75..915182c 100644 --- a/examples/native.zig +++ b/examples/native.zig @@ -7,7 +7,7 @@ pub fn main() !void { sdlPanic(); defer SDL.SDL_Quit(); - var window = SDL.SDL_CreateWindow( + const window = SDL.SDL_CreateWindow( "SDL.zig Basic Demo", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, @@ -17,7 +17,7 @@ pub fn main() !void { ) orelse sdlPanic(); defer _ = SDL.SDL_DestroyWindow(window); - var renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic(); + const renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic(); defer _ = SDL.SDL_DestroyRenderer(renderer); const vertices = [_]SDL.SDL_Vertex{ diff --git a/src/binding/sdl.zig b/src/binding/sdl.zig index 628ac3f..505290c 100644 --- a/src/binding/sdl.zig +++ b/src/binding/sdl.zig @@ -103,19 +103,19 @@ pub const SDL_FRect = extern struct { }; pub fn SDL_PointInRect(arg_p: [*c]const SDL_Point, arg_r: [*c]const SDL_Rect) SDL_bool { - var p = arg_p; - var r = arg_r; + const p = arg_p; + const r = arg_r; return if ((((p.*.x >= r.*.x) and (p.*.x < (r.*.x + r.*.w))) and (p.*.y >= r.*.y)) and (p.*.y < (r.*.y + r.*.h))) @as(c_int, 1) else @as(c_int, 0); } pub fn SDL_RectEmpty(arg_r: [*c]const SDL_Rect) SDL_bool { - var r = arg_r; + const r = arg_r; return if ((!(r != null) or (r.*.w <= @as(c_int, 0))) or (r.*.h <= @as(c_int, 0))) @as(c_int, 1) else @as(c_int, 0); } pub fn SDL_RectEquals(arg_a: [*c]const SDL_Rect, arg_b: [*c]const SDL_Rect) SDL_bool { - var a = arg_a; - var b = arg_b; + const a = arg_a; + const b = arg_b; return if ((((((a != null) and (b != null)) and (a.*.x == b.*.x)) and (a.*.y == b.*.y)) and (a.*.w == b.*.w)) and (a.*.h == b.*.h)) @as(c_int, 1) else @as(c_int, 0); } pub extern fn SDL_HasIntersection(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect) SDL_bool; diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 68598ea..c4c6e8f 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -365,7 +365,7 @@ pub const Window = struct { } pub fn getSurface(w: Window) !Surface { - var surface_ptr = c.SDL_GetWindowSurface(w.ptr) orelse return makeError(); + const surface_ptr = c.SDL_GetWindowSurface(w.ptr) orelse return makeError(); return Surface{ .ptr = surface_ptr }; } @@ -832,7 +832,7 @@ pub const Renderer = struct { } pub fn readPixels(ren: Renderer, rect: ?Rectangle, format: ?PixelFormatEnum, pixels: [*]u8, pitch: u32) !void { - var region = rect; + const region = rect; if (c.SDL_RenderReadPixels( ren.ptr, if (region) |r| r.getConstSdlPtr() else null, @@ -984,7 +984,7 @@ pub const Texture = struct { } pub fn getScaleMode(tex: Texture) !ScaleMode { - var scale_mode: c.SDL_ScaleMode = undefined; + const scale_mode: c.SDL_ScaleMode = undefined; if (c.SDL_GetTextureScaleMode(tex.ptr, @intFromEnum(scale_mode)) < 0) return makeError(); return @enumFromInt(scale_mode); @@ -2771,7 +2771,7 @@ pub fn newAudioStream( dst_channels: u8, dst_rate: i32, ) !AudioStream { - var stream = c.SDL_NewAudioStream( + const stream = c.SDL_NewAudioStream( src_format.toNative(), src_channels, @intCast(src_rate), From 120667e5de18402fea6f7944b5f0c911e235bf3a Mon Sep 17 00:00:00 2001 From: jack Date: Mon, 27 Nov 2023 22:40:43 +0800 Subject: [PATCH 04/50] update to zig 0.12.0-dev.1744+f29302f91 --- src/binding/sdl.zig | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/binding/sdl.zig b/src/binding/sdl.zig index 505290c..42c3e38 100644 --- a/src/binding/sdl.zig +++ b/src/binding/sdl.zig @@ -2407,18 +2407,18 @@ pub inline fn SDL_AUDIO_ISUNSIGNED(x: anytype) @TypeOf(!(SDL_AUDIO_ISSIGNED(x) ! return !(SDL_AUDIO_ISSIGNED(x) != 0); } pub const AUDIO_U8 = @as(c_int, 0x0008); -pub const AUDIO_S8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8008, .hexadecimal); +pub const AUDIO_S8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8008, .hex); pub const AUDIO_U16LSB = @as(c_int, 0x0010); -pub const AUDIO_S16LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8010, .hexadecimal); +pub const AUDIO_S16LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8010, .hex); pub const AUDIO_U16MSB = @as(c_int, 0x1010); -pub const AUDIO_S16MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9010, .hexadecimal); +pub const AUDIO_S16MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9010, .hex); pub const AUDIO_U16 = AUDIO_U16LSB; pub const AUDIO_S16 = AUDIO_S16LSB; -pub const AUDIO_S32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8020, .hexadecimal); -pub const AUDIO_S32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9020, .hexadecimal); +pub const AUDIO_S32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8020, .hex); +pub const AUDIO_S32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9020, .hex); pub const AUDIO_S32 = AUDIO_S32LSB; -pub const AUDIO_F32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8120, .hexadecimal); -pub const AUDIO_F32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9120, .hexadecimal); +pub const AUDIO_F32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8120, .hex); +pub const AUDIO_F32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9120, .hex); pub const AUDIO_F32 = AUDIO_F32LSB; pub const AUDIO_U16SYS = AUDIO_U16LSB; pub const AUDIO_S16SYS = AUDIO_S16LSB; @@ -2434,21 +2434,21 @@ pub inline fn SDL_LoadWAV(file: anytype, spec: anytype, audio_buf: anytype, audi return SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1), spec, audio_buf, audio_len); } pub const SDL_MIX_MAXVOLUME = @as(c_int, 128); -pub const SDL_WINDOWPOS_UNDEFINED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x1FFF0000, .hexadecimal); +pub const SDL_WINDOWPOS_UNDEFINED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x1FFF0000, .hex); pub inline fn SDL_WINDOWPOS_UNDEFINED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_UNDEFINED_MASK | X) { return SDL_WINDOWPOS_UNDEFINED_MASK | X; } pub const SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(@as(c_int, 0)); -pub inline fn SDL_WINDOWPOS_ISUNDEFINED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK) { - return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK; +pub inline fn SDL_WINDOWPOS_ISUNDEFINED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hex)) == SDL_WINDOWPOS_UNDEFINED_MASK) { + return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hex)) == SDL_WINDOWPOS_UNDEFINED_MASK; } -pub const SDL_WINDOWPOS_CENTERED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x2FFF0000, .hexadecimal); +pub const SDL_WINDOWPOS_CENTERED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x2FFF0000, .hex); pub inline fn SDL_WINDOWPOS_CENTERED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_CENTERED_MASK | X) { return SDL_WINDOWPOS_CENTERED_MASK | X; } pub const SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(@as(c_int, 0)); -pub inline fn SDL_WINDOWPOS_ISCENTERED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK) { - return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK; +pub inline fn SDL_WINDOWPOS_ISCENTERED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hex)) == SDL_WINDOWPOS_CENTERED_MASK) { + return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hex)) == SDL_WINDOWPOS_CENTERED_MASK; } pub const SDL_TOUCH_MOUSEID = @import("std").zig.c_translation.cast(u32, -@as(c_int, 1)); pub const SDL_MOUSE_TOUCHID = @import("std").zig.c_translation.cast(i64, -@as(c_int, 1)); From 14932f6f62e2b4baab3884b10ac7ea1c692de970 Mon Sep 17 00:00:00 2001 From: jack Date: Thu, 11 Jan 2024 00:03:06 +0800 Subject: [PATCH 05/50] update to zig 0.12.0-dev.2127+fcc0c5ddc --- build.zig | 113 +++++++++++++++++++++++------------------------------- 1 file changed, 48 insertions(+), 65 deletions(-) diff --git a/build.zig b/build.zig index 11ced0e..9d31d05 100644 --- a/build.zig +++ b/build.zig @@ -5,28 +5,30 @@ //! const std = @import("std"); +const builtin = @import("builtin"); -const Builder = std.Build.Builder; - -pub fn build(b: *Builder) !void { +pub fn build(b: *std.Build) !void { const sdk = Sdk.init(b, null); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const sdl_linkage = b.option(std.Build.LibExeObjStep.Linkage, "link", "Defines how to link SDL2 when building with mingw32") orelse .dynamic; + const sdl_linkage = b.option(std.Build.Step.Compile.Linkage, "link", "Defines how to link SDL2 when building with mingw32") orelse .dynamic; const skip_tests = b.option(bool, "skip-test", "When set, skips the test suite to be run. This is required for cross-builds") orelse false; if (!skip_tests) { const lib_test = b.addTest(.{ .root_source_file = .{ .path = "src/wrapper/sdl.zig" }, - .target = .{ .abi = if (target.isWindows()) target.abi else null }, + .target = if (target.result.os.tag == .windows) + b.resolveTargetQuery(.{ .abi = target.result.abi }) + else + null, }); - lib_test.addModule("sdl-native", sdk.getNativeModule()); + lib_test.root_module.addImport("sdl-native", sdk.getNativeModule()); lib_test.linkSystemLibrary("sdl2_image"); lib_test.linkSystemLibrary("sdl2_ttf"); - if (lib_test.target.isDarwin()) { + if (lib_test.rootModuleTarget().isDarwin()) { // SDL_TTF lib_test.linkSystemLibrary("freetype"); lib_test.linkSystemLibrary("harfbuzz"); @@ -54,7 +56,7 @@ pub fn build(b: *Builder) !void { .optimize = optimize, }); sdk.link(demo_wrapper, sdl_linkage); - demo_wrapper.addModule("sdl2", sdk.getWrapperModule()); + demo_wrapper.root_module.addImport("sdl2", sdk.getWrapperModule()); b.installArtifact(demo_wrapper); const demo_wrapper_image = b.addExecutable(.{ @@ -64,14 +66,14 @@ pub fn build(b: *Builder) !void { .optimize = optimize, }); sdk.link(demo_wrapper_image, sdl_linkage); - demo_wrapper_image.addModule("sdl2", sdk.getWrapperModule()); + demo_wrapper_image.root_module.addImport("sdl2", sdk.getWrapperModule()); demo_wrapper_image.linkSystemLibrary("sdl2_image"); demo_wrapper_image.linkSystemLibrary("jpeg"); demo_wrapper_image.linkSystemLibrary("libpng"); demo_wrapper_image.linkSystemLibrary("tiff"); demo_wrapper_image.linkSystemLibrary("webp"); - if (target.isNative() and target.isLinux()) { + if (target.query.isNative() and target.result.os.tag == .linux) { b.installArtifact(demo_wrapper_image); } @@ -82,7 +84,7 @@ pub fn build(b: *Builder) !void { .optimize = optimize, }); sdk.link(demo_native, sdl_linkage); - demo_native.addModule("sdl2", sdk.getNativeModule()); + demo_native.root_module.addImport("sdl2", sdk.getNativeModule()); b.installArtifact(demo_native); const run_demo_wrappr = b.addRunArtifact(demo_wrapper); @@ -107,7 +109,7 @@ const Build = std.Build; const Step = Build.Step; const LazyPath = Build.LazyPath; const GeneratedFile = Build.GeneratedFile; -const LibExeObjStep = Build.LibExeObjStep; +const Compile = Build.Step.Compile; const Sdk = @This(); @@ -155,8 +157,8 @@ pub fn getNativeModule(sdk: *Sdk) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", false); return sdk.build.createModule(.{ - .source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, - .dependencies = &.{ + .root_source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, + .imports = &.{ .{ .name = sdk.build.dupe("build_options"), .module = build_options.createModule(), @@ -173,8 +175,8 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", true); return sdk.build.createModule(.{ - .source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, - .dependencies = &.{ + .root_source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, + .imports = &.{ .{ .name = sdk.build.dupe("build_options"), .module = build_options.createModule(), @@ -190,8 +192,8 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { /// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on. pub fn getWrapperModule(sdk: *Sdk) *Build.Module { return sdk.build.createModule(.{ - .source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, - .dependencies = &.{ + .root_source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, + .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), .module = sdk.getNativeModule(), @@ -204,8 +206,8 @@ pub fn getWrapperModule(sdk: *Sdk) *Build.Module { /// provided as an argument. pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { return sdk.build.createModule(.{ - .source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, - .dependencies = &.{ + .root_source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, + .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), .module = sdk.getNativeModuleVulkan(vulkan), @@ -218,7 +220,7 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { }); } -pub fn linkTtf(_: *Sdk, exe: *LibExeObjStep) void { +pub fn linkTtf(_: *Sdk, exe: *Compile) void { const target = (std.zig.system.NativeTargetInfo.detect(exe.target) catch @panic("failed to detect native target info!")).target; // This is required on all platforms @@ -247,25 +249,25 @@ pub fn linkTtf(_: *Sdk, exe: *LibExeObjStep) void { /// Links SDL2 to the given exe and adds required installs if necessary. /// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void { +pub fn link(sdk: *Sdk, exe: *Compile, linkage: Compile.Linkage) void { // TODO: Implement const b = sdk.build; - const target = (std.zig.system.NativeTargetInfo.detect(exe.target) catch @panic("failed to detect native target info!")).target; - const is_native = exe.target.isNative(); + const target = exe.root_module.resolved_target.?; + const is_native = target.query.isNative(); // This is required on all platforms exe.linkLibC(); - if (target.os.tag == .linux and !is_native) { + if (target.result.os.tag == .linux and !is_native) { // for cross-compilation to Linux, we use a magic trick: // we compile a stub .so file we will link against an SDL2.so even if that file // doesn't exist on our system const build_linux_sdl_stub = b.addSharedLibrary(.{ .name = "SDL2", - .target = exe.target, - .optimize = exe.optimize, + .target = exe.root_module.resolved_target.?, + .optimize = exe.root_module.optimize.?, }); build_linux_sdl_stub.addAssemblyFile(sdk.prepare_sources.getStubFile()); @@ -274,29 +276,11 @@ pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void // link against the output of our stub exe.linkLibrary(build_linux_sdl_stub); - } else if (target.os.tag == .linux) { + } else if (target.result.os.tag == .linux) { // on linux with compilation for native target, // we should rely on the system libraries to "just work" exe.linkSystemLibrary("sdl2"); - } else if (target.os.tag == .windows) { - // try linking with vcpkg - // TODO: Implement proper vcpkg support - exe.addVcpkgPaths(linkage) catch {}; - if (exe.vcpkg_bin_path) |path| { - - // we found SDL2 in vcpkg, just install and use this variant - const src_path = std.fs.path.join(b.allocator, &.{ path, "SDL2.dll" }) catch @panic("out of memory"); - - if (std.fs.cwd().access(src_path, .{})) { - // we found SDL2.dll, so just link via vcpkg: - exe.linkSystemLibrary("sdl2"); - b.installBinFile(src_path, "SDL2.dll"); - return; - } else |_| { - // - } - } - + } else if (target.result.os.tag == .windows) { const sdk_paths = sdk.getPaths(target) catch |err| { const writer = std.io.getStdErr().writer(); @@ -358,11 +342,11 @@ pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void // linking on windows is sadly not as trivial as on linux: // we have to respect 6 different configurations {x86,x64}-{msvc,mingw}-{dynamic,static} - if (target.abi == .msvc and linkage != .dynamic) + if (target.result.abi == .msvc and linkage != .dynamic) @panic("SDL cannot be linked statically for MSVC"); // These will be added for C-Imports or C files. - if (target.abi != .msvc) { + if (target.result.abi != .msvc) { // SDL2 (mingw) ships the SDL include files under `include/SDL2/` which is very inconsitent with // all other platforms, so we just remove this prefix here const include_path = std.fs.path.join(b.allocator, &[_][]const u8{ @@ -375,10 +359,10 @@ pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void } // link the right libraries - if (target.abi == .msvc) { + if (target.result.abi == .msvc) { // and links those as normal libraries exe.addLibraryPath(.{ .path = sdk_paths.libs }); - exe.linkSystemLibraryName("SDL2"); + exe.linkSystemLibrary2("SDL2", .{ .use_pkg_config = .no }); } else { const file_name = switch (linkage) { .static => "libSDL2.a", @@ -420,7 +404,7 @@ pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void }) catch @panic("out of memory"); sdk.build.installBinFile(sdl2_dll_path, "SDL2.dll"); } - } else if (target.isDarwin()) { + } else if (target.result.isDarwin()) { // TODO: Implement cross-compilaton to macOS via system root provisioning if (!host_system.os.tag.isDarwin()) @panic("Cannot cross-compile to macOS yet."); @@ -441,7 +425,7 @@ pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: LibExeObjStep.Linkage) void exe.linkFramework("CoreHaptics"); exe.linkSystemLibrary("iconv"); } else { - const triple_string = target.zigTriple(b.allocator) catch "unkown-unkown-unkown"; + const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown"; std.log.warn("Linking SDL2 for {s} is not tested, linking might fail!", .{triple_string}); // on all other platforms, just try the system way: @@ -455,7 +439,7 @@ const Paths = struct { bin: []const u8, }; -fn getPaths(sdk: *Sdk, target_local: std.Target) error{ MissingTarget, FileNotFound, InvalidJson, InvalidTarget }!Paths { +fn getPaths(sdk: *Sdk, target_local: std.Build.ResolvedTarget) error{ MissingTarget, FileNotFound, InvalidJson, InvalidTarget }!Paths { const json_data = std.fs.cwd().readFileAlloc(sdk.build.allocator, sdk.config_path, 1 << 20) catch |err| switch (err) { error.FileNotFound => return error.FileNotFound, else => |e| @panic(@errorName(e)), @@ -465,16 +449,15 @@ fn getPaths(sdk: *Sdk, target_local: std.Target) error{ MissingTarget, FileNotFo var root_node = parsed.value.object; var config_iterator = root_node.iterator(); while (config_iterator.next()) |entry| { - const config_cross_target = std.zig.CrossTarget.parse(.{ - .arch_os_abi = entry.key_ptr.*, - }) catch return error.InvalidTarget; - const config_target = (std.zig.system.NativeTargetInfo.detect(config_cross_target) catch @panic("out of memory")).target; + const config_target = sdk.build.resolveTargetQuery( + std.Target.Query.parse(.{ .arch_os_abi = entry.key_ptr.* }) catch return error.InvalidTarget, + ); - if (target_local.cpu.arch != config_target.cpu.arch) + if (target_local.result.cpu.arch != config_target.result.cpu.arch) continue; - if (target_local.os.tag != config_target.os.tag) + if (target_local.result.os.tag != config_target.result.os.tag) continue; - if (target_local.abi != config_target.abi) + if (target_local.result.abi != config_target.result.abi) continue; // load paths @@ -555,10 +538,10 @@ const PrepareStubSourceStep = struct { } }; -fn tripleName(allocator: std.mem.Allocator, target_local: std.Target) ![]u8 { - const arch_name = @tagName(target_local.cpu.arch); - const os_name = @tagName(target_local.os.tag); - const abi_name = @tagName(target_local.abi); +fn tripleName(allocator: std.mem.Allocator, target_local: std.Build.ResolvedTarget) ![]u8 { + const arch_name = @tagName(target_local.result.cpu.arch); + const os_name = @tagName(target_local.result.os.tag); + const abi_name = @tagName(target_local.result.abi); return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ arch_name, os_name, abi_name }); } From ea8658e324ac8c270fcd4dd35eeca428d4eb38a0 Mon Sep 17 00:00:00 2001 From: Blue <69832658+bluesillybeard@users.noreply.github.com> Date: Sun, 14 Jan 2024 20:09:18 -0700 Subject: [PATCH 06/50] Update README.md to reflect new usage of zig modules --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7a89eb3..c5bd4d0 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ pub fn build(b: *std.Build.Builder) !void { sdk.link(demo_basic, .dynamic); // link SDL2 as a shared library // Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow) - demo_basic.addModule("sdl2", sdk.getNativeModule()); + demo_basic.root_module.addImport("sdl2", sdk.getNativeModule()); // Install the executable into the prefix when invoking "zig build" b.installArtifact(demo_basic); @@ -87,7 +87,7 @@ This package also exposes the SDL2 API with a more Zig-style API. Use this if yo ```zig const std = @import("std"); -const SDL = @import("sdl2"); // Created in build.zig by using exe.addModule("sdl2", sdk.getWrapperModule()); +const SDL = @import("sdl2"); // Created in build.zig by using exe.root_module.addImport("sdl2", sdk.getWrapperModule()); pub fn main() !void { try SDL.init(.{ From c81ab3c36b88b74fca4e285b0c7476a5b7fb3fdf Mon Sep 17 00:00:00 2001 From: tecanec Date: Fri, 19 Jan 2024 16:03:27 +0100 Subject: [PATCH 07/50] Primitive Vulkan wrapper functions --- src/binding/vulkan.zig | 4 ++-- src/wrapper/sdl.zig | 9 +++++++ src/wrapper/vulkan.zig | 54 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 src/wrapper/vulkan.zig diff --git a/src/binding/vulkan.zig b/src/binding/vulkan.zig index 58da037..d71e5f4 100644 --- a/src/binding/vulkan.zig +++ b/src/binding/vulkan.zig @@ -4,9 +4,9 @@ const vk = @import("vulkan"); pub const SDL_vulkanInstance = vk.Instance; pub const SDL_vulkanSurface = vk.SurfaceKHR; -pub extern fn SDL_Vulkan_LoadLibrary(path: [*:0]const u8) c_int; +pub extern fn SDL_Vulkan_LoadLibrary(path: ?[*:0]const u8) c_int; pub extern fn SDL_Vulkan_GetVkGetInstanceProcAddr() ?vk.PfnGetInstanceProcAddr; pub extern fn SDL_Vulkan_UnloadLibrary() void; -pub extern fn SDL_Vulkan_GetInstanceExtensions(window: *sdl.SDL_Window, pCount: *c_uint, pNames: ?[*][*:0]const u8) sdl.SDL_bool; +pub extern fn SDL_Vulkan_GetInstanceExtensions(window: ?*sdl.SDL_Window, pCount: *c_uint, pNames: ?[*][*:0]const u8) sdl.SDL_bool; pub extern fn SDL_Vulkan_CreateSurface(window: *sdl.SDL_Window, instance: vk.Instance, surface: *vk.SurfaceKHR) sdl.SDL_bool; pub extern fn SDL_Vulkan_GetDrawableSize(window: *sdl.SDL_Window, w: ?*c_int, h: ?*c_int) void; diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index c4c6e8f..1b9b0fd 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -9,6 +9,7 @@ pub const c = @import("sdl-native"); pub const image = @import("image.zig"); pub const ttf = @import("ttf.zig"); pub const gl = @import("gl.zig"); +pub const vulkan = @import("vulkan.zig"); pub const Error = error{SdlError}; @@ -354,6 +355,14 @@ pub const Window = struct { null; } + pub fn getID(w: Window) !u32 { + const id = c.SDL_GetWindowID(w.ptr); + if (id == 0) { + return makeError(); + } + return id; + } + pub fn destroy(w: Window) void { c.SDL_DestroyWindow(w.ptr); } diff --git a/src/wrapper/vulkan.zig b/src/wrapper/vulkan.zig new file mode 100644 index 0000000..31207b6 --- /dev/null +++ b/src/wrapper/vulkan.zig @@ -0,0 +1,54 @@ +const sdl = @import("sdl.zig"); +const std = @import("std"); +const vk = @import("vulkan"); + +pub fn loadLibrary(path: ?[*:0]const u8) !void { + const result = sdl.c.SDL_Vulkan_LoadLibrary(path); + if (result != 0) return sdl.makeError(); +} + +pub const unloadLibrary = sdl.c.SDL_Vulkan_UnloadLibrary; + +pub fn getVkGetInstanceProcAddr() !vk.PfnGetInstanceProcAddr { + return sdl.c.SDL_Vulkan_GetVkGetInstanceProcAddr() orelse return sdl.makeError(); +} + +pub fn getInstanceExtensionsCount(window: ?sdl.Window) c_uint { + const window_ptr = if (window) |window_v| window_v.ptr else null; + var count: c_uint = 0; + // The wiki isn't quite clear on whether this function returns true or false if pNames is null. Even if it was, it still isn't + // quite up-to-date on whether window is allowed to be null (which it is, but the wiki still says "might be in the future"). + // I just hope ignoring the returned value is safe... + _ = sdl.c.SDL_Vulkan_GetInstanceExtensions(window_ptr, &count, null); + return count; +} + +pub fn getInstanceExtensions(window: ?sdl.Window, dest: [][*:0]const u8) !c_uint { + const window_ptr = if (window) |window_v| window_v.ptr else null; + var count: c_uint = @intCast(dest.len); + const result = sdl.c.SDL_Vulkan_GetInstanceExtensions(window_ptr, &count, dest.ptr); + if (result == 0) return sdl.makeError(); + return count; +} + +pub fn getInstanceExtensionsAlloc(window: ?sdl.Window, allocator: std.mem.Allocator) ![][*:0]const u8 { + const count = getInstanceExtensionsCount(window); + const slice = try allocator.alloc([*:0]const u8, count); + errdefer allocator.free(slice); + const actual_count = try getInstanceExtensions(window, slice); + std.debug.assert(count == actual_count); + return slice; +} + +pub fn createSurface(window: sdl.Window, instance: vk.Instance) !vk.SurfaceKHR { + var out: vk.SurfaceKHR = undefined; + const result = sdl.c.SDL_Vulkan_CreateSurface(window.ptr, instance, &out); + if (result == 0) return sdl.makeError(); + return out; +} + +pub fn getDrawableSize(window: *sdl.Window) sdl.Size { + var out: sdl.Size = undefined; + sdl.c.SDL_Vulkan_GetDrawableSize(window.ptr, &out.width, &out.height); + return out; +} From 76691bd8a20727f380454246c539d876b6df7c86 Mon Sep 17 00:00:00 2001 From: jack Date: Mon, 22 Jan 2024 22:35:03 +0800 Subject: [PATCH 08/50] add method getTarget to renderer --- src/wrapper/sdl.zig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index c4c6e8f..33e2921 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -826,6 +826,13 @@ pub const Renderer = struct { return makeError(); } + pub fn getTarget(ren: Renderer) ?Texture { + if (c.SDL_GetRenderTarget(ren.ptr)) |ptr| { + return Texture{ .ptr = ptr }; + } + return null; + } + pub fn setTarget(ren: Renderer, tex: ?Texture) !void { if (c.SDL_SetRenderTarget(ren.ptr, if (tex) |t| t.ptr else null) < 0) return makeError(); From c8ccd6eabecf5b121785d50019d138d3d804df2a Mon Sep 17 00:00:00 2001 From: stringflow Date: Sat, 27 Jan 2024 22:24:24 +0100 Subject: [PATCH 09/50] Add audio queue methods to AudioDevice --- src/wrapper/sdl.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 2603eb1..afce0b5 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -2436,6 +2436,21 @@ pub const AudioDevice = struct { pub fn unlock(self: AudioDevice) void { c.SDL_UnlockAudioDevice(self.id); } + + pub fn queueAudio(self: AudioDevice, data: []const u8) !void { + if (c.SDL_QueueAudio(self.id, data.ptr, @truncate(data.len)) != 0) { + return makeError(); + } + } + + pub fn clearQueuedAudio(self: AudioDevice) void { + c.SDL_ClearQueuedAudio(self.id); + } + + pub fn getQueuedAudioSize(self: AudioDevice) usize { + const res = c.SDL_GetQueuedAudioSize(self.id); + return @intCast(res); + } }; const is_little_endian = @import("builtin").target.cpu.arch.endian() == .Little; From 5117a7dc6987d6cc8fcc20cfe45c1cb9706786bd Mon Sep 17 00:00:00 2001 From: kdx Date: Fri, 23 Feb 2024 18:08:01 +0100 Subject: [PATCH 10/50] wrapper/sdl: default to 0 for x/y fields of Rectangle --- src/wrapper/sdl.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index afce0b5..37557e8 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -30,8 +30,8 @@ pub fn makeError() error{SdlError} { } pub const Rectangle = extern struct { - x: c_int, - y: c_int, + x: c_int = 0, + y: c_int = 0, width: c_int, height: c_int, From cd902129b7ab571693892c72bbf4e2fb58658730 Mon Sep 17 00:00:00 2001 From: paoda Date: Wed, 6 Mar 2024 17:46:17 -0600 Subject: [PATCH 11/50] fix: only use sdl2 sub when cross-compiling isNative() will return false if CPU isn't native e.g. Dcpu=baseline, even when building a linux executable on a linux distro like ubuntu --- build.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 9d31d05..1949d4a 100644 --- a/build.zig +++ b/build.zig @@ -254,7 +254,7 @@ pub fn link(sdk: *Sdk, exe: *Compile, linkage: Compile.Linkage) void { const b = sdk.build; const target = exe.root_module.resolved_target.?; - const is_native = target.query.isNative(); + const is_native = target.query.isNativeOs(); // This is required on all platforms exe.linkLibC(); From 7c53574b39827d3b56d3dfd9c531c60ca64bac61 Mon Sep 17 00:00:00 2001 From: jack Date: Wed, 13 Mar 2024 21:48:05 +0800 Subject: [PATCH 12/50] update to zig 0.12.0-dev.3282+da5b16f9e --- build.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.zig b/build.zig index 1949d4a..9cabfa4 100644 --- a/build.zig +++ b/build.zig @@ -13,7 +13,7 @@ pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const sdl_linkage = b.option(std.Build.Step.Compile.Linkage, "link", "Defines how to link SDL2 when building with mingw32") orelse .dynamic; + const sdl_linkage = b.option(std.builtin.LinkMode, "link", "Defines how to link SDL2 when building with mingw32") orelse .dynamic; const skip_tests = b.option(bool, "skip-test", "When set, skips the test suite to be run. This is required for cross-builds") orelse false; @@ -249,7 +249,7 @@ pub fn linkTtf(_: *Sdk, exe: *Compile) void { /// Links SDL2 to the given exe and adds required installs if necessary. /// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn link(sdk: *Sdk, exe: *Compile, linkage: Compile.Linkage) void { +pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { // TODO: Implement const b = sdk.build; From 711c308b0a72c6ce5b61911ec329062dfdd17d09 Mon Sep 17 00:00:00 2001 From: paoda Date: Fri, 22 Mar 2024 11:59:39 -0500 Subject: [PATCH 13/50] fix: paths to SDL files in .build_config should be .cwd_relative --- build.zig | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.zig b/build.zig index 9cabfa4..8993696 100644 --- a/build.zig +++ b/build.zig @@ -353,15 +353,15 @@ pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { sdk_paths.include, "SDL2", }) catch @panic("out of memory"); - exe.addIncludePath(.{ .path = include_path }); + exe.addIncludePath(.{ .cwd_relative = include_path }); } else { - exe.addIncludePath(.{ .path = sdk_paths.include }); + exe.addIncludePath(.{ .cwd_relative = sdk_paths.include }); } // link the right libraries if (target.result.abi == .msvc) { // and links those as normal libraries - exe.addLibraryPath(.{ .path = sdk_paths.libs }); + exe.addLibraryPath(.{ .cwd_relative = sdk_paths.libs }); exe.linkSystemLibrary2("SDL2", .{ .use_pkg_config = .no }); } else { const file_name = switch (linkage) { @@ -374,7 +374,7 @@ pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { file_name, }) catch @panic("out of memory"); - exe.addObjectFile(.{ .path = lib_path }); + exe.addObjectFile(.{ .cwd_relative = lib_path }); if (linkage == .static) { // link all system libraries required for SDL2: From 3622f5eef0c3f3a20fe9899eb8c5906874211fe1 Mon Sep 17 00:00:00 2001 From: paoda Date: Fri, 22 Mar 2024 12:32:35 -0500 Subject: [PATCH 14/50] chore: std.os.exit() was renamed --- build.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 8993696..1989d4b 100644 --- a/build.zig +++ b/build.zig @@ -336,7 +336,7 @@ pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { }, } - std.os.exit(1); + std.process.exit(1); }; // linking on windows is sadly not as trivial as on linux: From 4267dca24abe1ac62693e8da8f141b50d69dcc0f Mon Sep 17 00:00:00 2001 From: jack Date: Sun, 24 Mar 2024 00:26:21 +0800 Subject: [PATCH 15/50] update to zig 0.12.0-dev.3429+13a9d94a8 --- build.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 9cabfa4..9340b84 100644 --- a/build.zig +++ b/build.zig @@ -336,7 +336,7 @@ pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { }, } - std.os.exit(1); + std.process.exit(1); }; // linking on windows is sadly not as trivial as on linux: From 6dd2bd3c5ce7e3cd34d6f49a7bcc05179cc20fc5 Mon Sep 17 00:00:00 2001 From: jack Date: Tue, 2 Apr 2024 20:30:47 +0800 Subject: [PATCH 16/50] update to zig 0.12.0-dev.3518+d2be725e4 --- build.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 1989d4b..a1bbc7c 100644 --- a/build.zig +++ b/build.zig @@ -505,7 +505,7 @@ const PrepareStubSourceStep = struct { fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; - const self = @fieldParentPtr(Self, "step", step); + const self: *Self = @fieldParentPtr("step", step); var cache = CacheBuilder.init(self.sdk.build, "sdl"); From 653673d536940dabc8d01eb33b0020611e48dd0d Mon Sep 17 00:00:00 2001 From: jack Date: Wed, 15 May 2024 21:38:04 +0800 Subject: [PATCH 17/50] update to zig 0.13.0-dev.211+6a65561e3 --- build.zig | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/build.zig b/build.zig index a1bbc7c..e3664e2 100644 --- a/build.zig +++ b/build.zig @@ -19,7 +19,7 @@ pub fn build(b: *std.Build) !void { if (!skip_tests) { const lib_test = b.addTest(.{ - .root_source_file = .{ .path = "src/wrapper/sdl.zig" }, + .root_source_file = .{ .cwd_relative = "src/wrapper/sdl.zig" }, .target = if (target.result.os.tag == .windows) b.resolveTargetQuery(.{ .abi = target.result.abi }) else @@ -51,7 +51,7 @@ pub fn build(b: *std.Build) !void { const demo_wrapper = b.addExecutable(.{ .name = "demo-wrapper", - .root_source_file = .{ .path = "examples/wrapper.zig" }, + .root_source_file = .{ .cwd_relative = "examples/wrapper.zig" }, .target = target, .optimize = optimize, }); @@ -61,7 +61,7 @@ pub fn build(b: *std.Build) !void { const demo_wrapper_image = b.addExecutable(.{ .name = "demo-wrapper-image", - .root_source_file = .{ .path = "examples/wrapper-image.zig" }, + .root_source_file = .{ .cwd_relative = "examples/wrapper-image.zig" }, .target = target, .optimize = optimize, }); @@ -79,7 +79,7 @@ pub fn build(b: *std.Build) !void { const demo_native = b.addExecutable(.{ .name = "demo-native", - .root_source_file = .{ .path = "examples/native.zig" }, + .root_source_file = .{ .cwd_relative = "examples/native.zig" }, .target = target, .optimize = optimize, }); @@ -157,7 +157,7 @@ pub fn getNativeModule(sdk: *Sdk) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", false); return sdk.build.createModule(.{ - .root_source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, + .root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") }, .imports = &.{ .{ .name = sdk.build.dupe("build_options"), @@ -175,7 +175,7 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", true); return sdk.build.createModule(.{ - .root_source_file = .{ .path = sdkPath("/src/binding/sdl.zig") }, + .root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") }, .imports = &.{ .{ .name = sdk.build.dupe("build_options"), @@ -192,7 +192,7 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { /// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on. pub fn getWrapperModule(sdk: *Sdk) *Build.Module { return sdk.build.createModule(.{ - .root_source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, + .root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") }, .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), @@ -206,7 +206,7 @@ pub fn getWrapperModule(sdk: *Sdk) *Build.Module { /// provided as an argument. pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { return sdk.build.createModule(.{ - .root_source_file = .{ .path = sdkPath("/src/wrapper/sdl.zig") }, + .root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") }, .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), @@ -500,7 +500,7 @@ const PrepareStubSourceStep = struct { } pub fn getStubFile(self: *Self) LazyPath { - return .{ .generated = &self.assembly_source }; + return .{ .generated = .{ .file = &self.assembly_source } }; } fn make(step: *Step, prog_node: *std.Progress.Node) !void { From 0d528cb73e5cd138895558ea987f9bb5e15ac3d5 Mon Sep 17 00:00:00 2001 From: Sivecano Date: Mon, 20 May 2024 15:56:40 +0200 Subject: [PATCH 18/50] add multi-draw functions to wrapper --- examples/wrapper.zig | 10 ++++++++++ src/wrapper/sdl.zig | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/examples/wrapper.zig b/examples/wrapper.zig index 7e13b9d..828167c 100644 --- a/examples/wrapper.zig +++ b/examples/wrapper.zig @@ -23,6 +23,9 @@ pub fn main() !void { var renderer = try SDL.createRenderer(window, null, .{ .accelerated = true }); defer renderer.destroy(); + const p = [_]SDL.Point{ .{.x = 0, .y = 0 }, .{ .x = 200, .y = 10 }, + .{ .x = 100, .y = 300 }, .{ .x = 400, .y = 400 }}; + mainLoop: while (true) { while (SDL.pollEvent()) |ev| { switch (ev) { @@ -51,6 +54,13 @@ pub fn main() !void { .height = 50, }); + try renderer.setColor(SDL.Color.parse("#22A41D") catch unreachable); + try renderer.drawLines(&p); + + try renderer.setColor(SDL.Color.parse("#FF0000") catch unreachable); + try renderer.drawPoints(&p); + + if (target_os.tag != .linux) { // Ubuntu CI doesn't have this function available yet try renderer.drawGeometry( diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 37557e8..07ec27a 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -697,41 +697,81 @@ pub const Renderer = struct { return makeError(); } + pub fn drawLines(ren: Renderer, points: [] const Point) !void { + if (c.SDL_RenderDrawLines(ren.ptr, @ptrCast(points.ptr), @intCast(points.len)) < 0) + return makeError(); + } + pub fn drawLineF(ren: Renderer, x0: f32, y0: f32, x1: f32, y1: f32) !void { if (c.SDL_RenderDrawLineF(ren.ptr, x0, y0, x1, y1) < 0) return makeError(); } + pub fn drawLinesF(ren: Renderer, points: [] const PointF) !void { + if (c.SDL_RenderDrawLinesF(ren.ptr, @ptrCast(points.ptr), @intCast(points.len)) < 0) + return makeError(); + } + pub fn drawPoint(ren: Renderer, x: i32, y: i32) !void { if (c.SDL_RenderDrawPoint(ren.ptr, x, y) < 0) return makeError(); } + pub fn drawPoints(ren: Renderer, points: [] const Point) !void { + if (c.SDL_RenderDrawPoints(ren.ptr, @ptrCast(points.ptr), @intCast(points.len)) < 0) + return makeError(); + } + pub fn drawPointF(ren: Renderer, x: f32, y: f32) !void { if (c.SDL_RenderDrawPointF(ren.ptr, x, y) < 0) return makeError(); } + pub fn drawPointsF(ren: Renderer, points: [] const PointF) !void { + if (c.SDL_RenderDrawPointsF(ren.ptr, @ptrCast(points.ptr), @intCast(points.len)) < 0) + return makeError(); + } + pub fn fillRect(ren: Renderer, rect: Rectangle) !void { if (c.SDL_RenderFillRect(ren.ptr, rect.getConstSdlPtr()) < 0) return makeError(); } + pub fn fillRects(ren: Renderer, rects: [] const Rectangle) !void { + if (c.SDL_RenderFillRects(ren, @ptrCast(rects.ptr), @intCast(rects.len)) < 0) + return makeError(); + } + pub fn fillRectF(ren: Renderer, rect: RectangleF) !void { if (c.SDL_RenderFillRectF(ren.ptr, rect.getConstSdlPtr()) < 0) return makeError(); } + pub fn fillRectsF(ren: Renderer, rects: [] const RectangleF) !void { + if (c.SDL_RenderFillRectsF(ren, @ptrCast(rects.ptr), @intCast(rects.len)) < 0) + return makeError(); + } + pub fn drawRect(ren: Renderer, rect: Rectangle) !void { if (c.SDL_RenderDrawRect(ren.ptr, rect.getConstSdlPtr()) < 0) return makeError(); } + pub fn drawRects(ren: Renderer, rects: [] const Rectangle) !void { + if (c.SDL_RenderDrawRects(ren, @ptrCast(rects.ptr), @intCast(rects.len)) < 0) + return makeError(); + } + pub fn drawRectF(ren: Renderer, rect: RectangleF) !void { if (c.SDL_RenderDrawRectF(ren.ptr, rect.getConstSdlPtr()) < 0) return makeError(); } + pub fn drawRectsF(ren: Renderer, rects: [] const RectangleF) !void { + if (c.SDL_RenderDrawRectsF(ren, @ptrCast(rects.ptr), @intCast(rects.len)) < 0) + return makeError(); + } + pub fn drawGeometry(ren: Renderer, tex: ?Texture, vertices: []const Vertex, indices: ?[]const u32) !void { if (c.SDL_RenderGeometry( ren.ptr, From 676bfe080b683fdb9fb15e6e19a80b162b5ae3ca Mon Sep 17 00:00:00 2001 From: jack Date: Thu, 30 May 2024 20:26:47 +0800 Subject: [PATCH 19/50] update to zig 0.13.0-dev.343+2008d0f7c --- .gitignore | 4 ++-- build.zig | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 0706733..e6c5a58 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ -zig-cache +.zig-cache zig-out deps.zig gyro.lock -.build_config \ No newline at end of file +.build_config diff --git a/build.zig b/build.zig index e3664e2..f58d007 100644 --- a/build.zig +++ b/build.zig @@ -503,7 +503,7 @@ const PrepareStubSourceStep = struct { return .{ .generated = .{ .file = &self.assembly_source } }; } - fn make(step: *Step, prog_node: *std.Progress.Node) !void { + fn make(step: *Step, prog_node: std.Progress.Node) !void { _ = prog_node; const self: *Self = @fieldParentPtr("step", step); From 327665a84fa550b37e6d74283a89effdf21c52f5 Mon Sep 17 00:00:00 2001 From: Borja Clemente Date: Fri, 31 May 2024 17:56:55 +0200 Subject: [PATCH 20/50] Add wrapper method to set font size Add support for https://wiki.libsdl.org/SDL2_ttf/TTF_SetFontSize Signed-off-by: Borja Clemente --- src/binding/sdl_ttf.zig | 1 + src/wrapper/ttf.zig | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/src/binding/sdl_ttf.zig b/src/binding/sdl_ttf.zig index c0b9d38..c0a3d43 100644 --- a/src/binding/sdl_ttf.zig +++ b/src/binding/sdl_ttf.zig @@ -20,6 +20,7 @@ pub extern fn TTF_CloseFont(font: *TTF_Font) void; pub extern fn TTF_GetFontStyle(font: *TTF_Font) c_int; pub extern fn TTF_SetFontStyle(font: *TTF_Font, style: c_int) void; +pub extern fn TTF_SetFontSize(font: *TTF_Font, point_size: c_int) void; pub extern fn TTF_FontHeight(font: *TTF_Font) c_int; pub extern fn TTF_SizeText(font: *TTF_Font, text: [*c]const u8, width: ?*c_int, height: ?*c_int) c_int; diff --git a/src/wrapper/ttf.zig b/src/wrapper/ttf.zig index 76faf6e..a0051a9 100644 --- a/src/wrapper/ttf.zig +++ b/src/wrapper/ttf.zig @@ -42,6 +42,10 @@ pub const Font = struct { sdl.c.TTF_SetFontStyle(self.ptr, value); } + pub fn setSize(self: Font, point_size: c_int) void { + sdl.c.TTF_SetFontSize(self.ptr, point_size); + } + pub fn height(self: Font) c_int { return sdl.c.TTF_FontHeight(self.ptr); } From 9d18b804dbf0bafd5191c5309110c4f479a35998 Mon Sep 17 00:00:00 2001 From: Asherah Connor Date: Fri, 7 Jun 2024 19:25:29 +0300 Subject: [PATCH 21/50] wrapper: add Window.setTitle. --- src/wrapper/sdl.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 07ec27a..2ef3d02 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -422,6 +422,10 @@ pub const Window = struct { } return info; } + + pub fn setTitle(w: Window, title: [:0]const u8) void { + c.SDL_SetWindowTitle(w.ptr, title); + } }; pub const WindowPosition = union(enum) { From ca9fec6558cc94091774fade9f1dd25191a59ebb Mon Sep 17 00:00:00 2001 From: Charlie Date: Mon, 10 Jun 2024 22:03:56 +0100 Subject: [PATCH 22/50] Add default colour alpha argument --- src/wrapper/sdl.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 07ec27a..d87fb02 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -144,7 +144,7 @@ pub const Color = extern struct { r: u8, g: u8, b: u8, - a: u8, + a: u8 = 255, /// returns a initialized color struct with alpha = 255 pub fn rgb(r: u8, g: u8, b: u8) Color { From f042fdb70bf9fb347066529430488486d01a5fed Mon Sep 17 00:00:00 2001 From: Charlie Date: Sat, 15 Jun 2024 15:46:22 +0100 Subject: [PATCH 23/50] remove redundant alpha --- examples/native.zig | 6 +++--- src/wrapper/sdl.zig | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/native.zig b/examples/native.zig index 915182c..9b1978f 100644 --- a/examples/native.zig +++ b/examples/native.zig @@ -23,15 +23,15 @@ pub fn main() !void { const vertices = [_]SDL.SDL_Vertex{ .{ .position = .{ .x = 400, .y = 150 }, - .color = .{ .r = 255, .g = 0, .b = 0, .a = 255 }, + .color = .{ .r = 255, .g = 0, .b = 0 }, }, .{ .position = .{ .x = 350, .y = 200 }, - .color = .{ .r = 0, .g = 0, .b = 255, .a = 255 }, + .color = .{ .r = 0, .g = 0, .b = 255 }, }, .{ .position = .{ .x = 450, .y = 200 }, - .color = .{ .r = 0, .g = 255, .b = 0, .a = 255 }, + .color = .{ .r = 0, .g = 255, .b = 0 }, }, }; diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index d87fb02..ef65265 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -148,7 +148,7 @@ pub const Color = extern struct { /// returns a initialized color struct with alpha = 255 pub fn rgb(r: u8, g: u8, b: u8) Color { - return Color{ .r = r, .g = g, .b = b, .a = 255 }; + return Color{ .r = r, .g = g, .b = b }; } /// returns a initialized color struct From a4b2ca813e6ee4945326216c3a2cc04f39a24038 Mon Sep 17 00:00:00 2001 From: Charlie Date: Sat, 15 Jun 2024 21:29:19 +0100 Subject: [PATCH 24/50] remove references to Sdk.zig in README --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c5bd4d0..70acffd 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ This is an example `build.zig` that will link the SDL2 library to your project. ```zig const std = @import("std"); -const Sdk = @import("Sdk.zig"); // Import the Sdk at build time +const sdl = @import("SDL.zig/build.zig"); // Replace with the actual path in your project pub fn build(b: *std.Build.Builder) !void { // Determine compilation target const target = b.standardTargetOptions(.{}); // Create a new instance of the SDL2 Sdk - const sdk = Sdk.init(b, null); + const sdk = sdl.init(b, null); // Create executable for our example const demo_basic = b.addExecutable(.{ @@ -25,6 +25,7 @@ pub fn build(b: *std.Build.Builder) !void { .root_source_file = .{ .path = "my-game.zig" }, .target = target, }); + sdk.link(demo_basic, .dynamic); // link SDL2 as a shared library // Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow) @@ -124,7 +125,7 @@ pub fn main() !void { } ``` -## `Sdk.zig` API +## `build.zig` API ```zig /// Just call `Sdk.init(b, null)` to obtain a handle to the Sdk! From 8b261488fdef8876aa6538fb18f94510e4a92ca0 Mon Sep 17 00:00:00 2001 From: Charlie Date: Sun, 16 Jun 2024 10:25:08 +0100 Subject: [PATCH 25/50] fixed nom compiling code --- examples/native.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/native.zig b/examples/native.zig index 9b1978f..915182c 100644 --- a/examples/native.zig +++ b/examples/native.zig @@ -23,15 +23,15 @@ pub fn main() !void { const vertices = [_]SDL.SDL_Vertex{ .{ .position = .{ .x = 400, .y = 150 }, - .color = .{ .r = 255, .g = 0, .b = 0 }, + .color = .{ .r = 255, .g = 0, .b = 0, .a = 255 }, }, .{ .position = .{ .x = 350, .y = 200 }, - .color = .{ .r = 0, .g = 0, .b = 255 }, + .color = .{ .r = 0, .g = 0, .b = 255, .a = 255 }, }, .{ .position = .{ .x = 450, .y = 200 }, - .color = .{ .r = 0, .g = 255, .b = 0 }, + .color = .{ .r = 0, .g = 255, .b = 0, .a = 255 }, }, }; From fac3c2dd126d05bee13fe4cc837f6492a6fbb077 Mon Sep 17 00:00:00 2001 From: kdx Date: Sun, 16 Jun 2024 23:25:09 +0200 Subject: [PATCH 26/50] build.zig: use splitScalar instead of split --- build.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.zig b/build.zig index f58d007..b263e00 100644 --- a/build.zig +++ b/build.zig @@ -520,7 +520,7 @@ const PrepareStubSourceStep = struct { var writer = file.writer(); try writer.writeAll(".text\n"); - var iter = std.mem.split(u8, sdl2_symbol_definitions, "\n"); + var iter = std.mem.splitScalar(u8, sdl2_symbol_definitions, '\n'); while (iter.next()) |line| { const sym = std.mem.trim(u8, line, " \r\n\t"); if (sym.len == 0) From 19dc253e9939e1b7da6452613e56ca63484976c9 Mon Sep 17 00:00:00 2001 From: Charlie Date: Mon, 17 Jun 2024 20:07:25 +0100 Subject: [PATCH 27/50] fix linking ttf --- build.zig | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/build.zig b/build.zig index b263e00..4e51904 100644 --- a/build.zig +++ b/build.zig @@ -220,20 +220,24 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { }); } -pub fn linkTtf(_: *Sdk, exe: *Compile) void { - const target = (std.zig.system.NativeTargetInfo.detect(exe.target) catch @panic("failed to detect native target info!")).target; +pub fn linkTtf(sdk: *Sdk, exe: *Compile) void { + const b = sdk.build; + const target = exe.root_module.resolved_target.?; + const is_native = target.query.isNativeOs(); - // This is required on all platforms - exe.linkLibC(); + if (target.result.os.tag == .linux) { + if (!is_native) { + @panic("Cannot cross-compile with TTF to linux yet."); + } - if (target.os.tag == .linux) { + // on linux with compilation for native target, + // we should rely on the system libraries to "just work" exe.linkSystemLibrary("sdl2_ttf"); - } else if (target.os.tag == .windows) { - @compileError("Not implemented yet"); - } else if (target.isDarwin()) { - - // on MacOS, we require a brew install - // requires sdl_ttf to be installed via brew + } else if (target.result.os.tag == .windows) { + @panic("Cannot link TTF on windows yet."); + } else if (target.result.isDarwin()) { + if (!host_system.os.tag.isDarwin()) + @panic("Cannot cross-compile with TTF to macOS yet."); exe.linkSystemLibrary("sdl2_ttf"); exe.linkSystemLibrary("freetype"); @@ -242,6 +246,9 @@ pub fn linkTtf(_: *Sdk, exe: *Compile) void { exe.linkSystemLibrary("zlib"); exe.linkSystemLibrary("graphite2"); } else { + const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown"; + std.log.warn("Linking SDL2_TTF for {s} is not tested, linking might fail!", .{triple_string}); + // on all other platforms, just try the system way: exe.linkSystemLibrary("sdl2_ttf"); } From 8238a9aeb033c8ed3c40e60afc9b5edc55e24104 Mon Sep 17 00:00:00 2001 From: reokodoku Date: Thu, 20 Jun 2024 13:08:10 +0200 Subject: [PATCH 28/50] Add hints for VIDEODRIVER and AUDIODRIVER --- src/binding/sdl.zig | 2 ++ src/wrapper/sdl.zig | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/binding/sdl.zig b/src/binding/sdl.zig index 42c3e38..6808d91 100644 --- a/src/binding/sdl.zig +++ b/src/binding/sdl.zig @@ -2557,6 +2557,7 @@ pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = "SDL_ANDROID_BLOCK_ON_PAU pub const SDL_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON"; pub const SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS = "SDL_APPLE_TV_CONTROLLER_UI_EVENTS"; pub const SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION = "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION"; +pub const SDL_HINT_AUDIODRIVER = "SDL_AUDIODRIVER"; pub const SDL_HINT_AUDIO_CATEGORY = "SDL_AUDIO_CATEGORY"; pub const SDL_HINT_AUDIO_DEVICE_APP_NAME = "SDL_AUDIO_DEVICE_APP_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_NAME = "SDL_AUDIO_DEVICE_STREAM_NAME"; @@ -2633,6 +2634,7 @@ pub const SDL_HINT_THREAD_STACK_SIZE = "SDL_THREAD_STACK_SIZE"; pub const SDL_HINT_TIMER_RESOLUTION = "SDL_TIMER_RESOLUTION"; pub const SDL_HINT_TOUCH_MOUSE_EVENTS = "SDL_TOUCH_MOUSE_EVENTS"; pub const SDL_HINT_TV_REMOTE_AS_JOYSTICK = "SDL_TV_REMOTE_AS_JOYSTICK"; +pub const SDL_HINT_VIDEODRIVER = "SDL_VIDEODRIVER"; pub const SDL_HINT_VIDEO_ALLOW_SCREENSAVER = "SDL_VIDEO_ALLOW_SCREENSAVER"; pub const SDL_HINT_VIDEO_DOUBLE_BUFFER = "SDL_VIDEO_DOUBLE_BUFFER"; pub const SDL_HINT_VIDEO_EXTERNAL_CONTEXT = "SDL_VIDEO_EXTERNAL_CONTEXT"; diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index ef65265..e6dfd2c 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -2949,6 +2949,7 @@ pub const hint = struct { pub const android_trap_back_button = c.SDL_HINT_ANDROID_TRAP_BACK_BUTTON; pub const apple_tv_controller_ui_events = c.SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS; pub const apple_tv_remote_allow_rotation = c.SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION; + pub const audiodriver = c.SDL_HINT_AUDIODRIVER; pub const audio_category = c.SDL_HINT_AUDIO_CATEGORY; pub const audio_device_app_name = c.SDL_HINT_AUDIO_DEVICE_APP_NAME; pub const audio_device_stream_name = c.SDL_HINT_AUDIO_DEVICE_STREAM_NAME; @@ -3025,6 +3026,7 @@ pub const hint = struct { pub const timer_resolution = c.SDL_HINT_TIMER_RESOLUTION; pub const touch_mouse_events = c.SDL_HINT_TOUCH_MOUSE_EVENTS; pub const tv_remote_as_joystick = c.SDL_HINT_TV_REMOTE_AS_JOYSTICK; + pub const videodriver = c.SDL_HINT_VIDEODRIVER; pub const video_allow_screensaver = c.SDL_HINT_VIDEO_ALLOW_SCREENSAVER; pub const video_double_buffer = c.SDL_HINT_VIDEO_DOUBLE_BUFFER; pub const video_external_context = c.SDL_HINT_VIDEO_EXTERNAL_CONTEXT; From 0a8e0f5c3b3fb73d5a9a0ba7b69fdc891b7da5b2 Mon Sep 17 00:00:00 2001 From: reokodoku Date: Thu, 20 Jun 2024 15:16:50 +0200 Subject: [PATCH 29/50] Add binding for `TTF_RenderText_Blended_Wrapped` --- src/binding/sdl_ttf.zig | 7 +++++++ src/wrapper/ttf.zig | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/binding/sdl_ttf.zig b/src/binding/sdl_ttf.zig index c0a3d43..cdddd58 100644 --- a/src/binding/sdl_ttf.zig +++ b/src/binding/sdl_ttf.zig @@ -39,3 +39,10 @@ pub extern fn TTF_RenderText_Blended( text: [*c]const u8, foreground: sdl.SDL_Color, ) ?*sdl.SDL_Surface; + +pub extern fn TTF_RenderText_Blended_Wrapped( + font: *TTF_Font, + text: [*c]const u8, + foreground: sdl.SDL_Color, + wrap_length: u32, +) ?*sdl.SDL_Surface; diff --git a/src/wrapper/ttf.zig b/src/wrapper/ttf.zig index a0051a9..adeffdd 100644 --- a/src/wrapper/ttf.zig +++ b/src/wrapper/ttf.zig @@ -93,6 +93,17 @@ pub const Font = struct { }; } + pub fn renderTextBlendedWrapped(self: Font, text: [:0]const u8, foreground: sdl.Color, wrap_length: u32) !sdl.Surface { + return sdl.Surface{ + .ptr = sdl.c.TTF_RenderText_Blended_Wrapped( + self.ptr, + text.ptr, + .{ .r = foreground.r, .g = foreground.g, .b = foreground.b, .a = foreground.a }, + wrap_length, + ) orelse return makeError(), + }; + } + pub fn close(self: Font) void { sdl.c.TTF_CloseFont(self.ptr); } From da282f96823c4cdc64e1efcb187bca1cc6205027 Mon Sep 17 00:00:00 2001 From: reokodoku Date: Fri, 21 Jun 2024 11:27:01 +0200 Subject: [PATCH 30/50] Update section `build.zig API` of README --- README.md | 14 ++++++++++++++ build.zig | 2 ++ 2 files changed, 16 insertions(+) diff --git a/README.md b/README.md index 70acffd..0fff208 100644 --- a/README.md +++ b/README.md @@ -140,12 +140,26 @@ pub fn init(b: *Build, maybe_config_path: ?[]const u8) *Sdk /// This is similar to the *C import* result. pub fn getNativeModule(sdk: *Sdk) *Build.Module; +/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes +/// for a more *ziggy* feeling, with Vulkan support! The Vulkan module provided by `vulkan-zig` must be +/// provided as an argument. +/// This is similar to the *C import* result. +pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module; + /// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on. pub fn getWrapperModule(sdk: *Sdk) *Build.Module; +/// Returns the smart wrapper with Vulkan support. The Vulkan module provided by `vulkan-zig` must be +/// provided as an argument. +pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module; + /// Links SDL2 to the given exe and adds required installs if necessary. /// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: std.Build.LibExeObjStep.Linkage) void; + +/// Links SDL2 TTF to the given exe. +/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! +pub fn linkTtf(sdk: *Sdk, exe: *Compile) void; ``` ## Dependencies diff --git a/build.zig b/build.zig index 4e51904..06b4a24 100644 --- a/build.zig +++ b/build.zig @@ -220,6 +220,8 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { }); } +/// Links SDL2 TTF to the given exe. +/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! pub fn linkTtf(sdk: *Sdk, exe: *Compile) void { const b = sdk.build; const target = exe.root_module.resolved_target.?; From f887f6d95771858c388651a668b7c434669ac998 Mon Sep 17 00:00:00 2001 From: reokodoku Date: Sun, 23 Jun 2024 00:24:34 +0200 Subject: [PATCH 31/50] Move OpenGL context functions to `gl.Context` --- src/wrapper/gl.zig | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/wrapper/gl.zig b/src/wrapper/gl.zig index d0a426e..310b813 100644 --- a/src/wrapper/gl.zig +++ b/src/wrapper/gl.zig @@ -3,6 +3,16 @@ const std = @import("std"); pub const Context = struct { ptr: sdl.c.SDL_GLContext, + + pub fn makeCurrent(self: Context, window: sdl.Window) !void { + if (sdl.c.SDL_GL_MakeCurrent(window.ptr, self.ptr) != 0) { + return sdl.makeError(); + } + } + + pub fn delete(self: Context) void { + _ = sdl.c.SDL_GL_DeleteContext(self.ptr); + } }; pub fn createContext(window: sdl.Window) !Context { @@ -11,16 +21,6 @@ pub fn createContext(window: sdl.Window) !Context { }; } -pub fn makeCurrent(context: Context, window: sdl.Window) !void { - if (sdl.c.SDL_GL_MakeCurrent(window.ptr, context.ptr) != 0) { - return sdl.makeError(); - } -} - -pub fn deleteContext(context: Context) void { - _ = sdl.c.SDL_GL_DeleteContext(context.ptr); -} - pub fn getProcAddress(proc: [:0]const u8) ?*const anyopaque { return sdl.c.SDL_GL_GetProcAddress(proc.ptr); } From a51701f3bb4a822430e0c206cef8d842955f910f Mon Sep 17 00:00:00 2001 From: Adi Hodos Date: Tue, 25 Jun 2024 22:44:35 +0300 Subject: [PATCH 32/50] Fixed getWMInfo() returning invalid data. --- .envrc | 1 + flake.lock | 25 +++++++++++++++++++++++++ flake.nix | 37 +++++++++++++++++++++++++++++++++++++ src/binding/sdl.zig | 4 ++++ src/wrapper/sdl.zig | 3 ++- 5 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 .envrc create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..6add7d4 --- /dev/null +++ b/flake.lock @@ -0,0 +1,25 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1719075281, + "narHash": "sha256-CyyxvOwFf12I91PBWz43iGT1kjsf5oi6ax7CrvaMyAo=", + "rev": "a71e967ef3694799d0c418c98332f7ff4cc5f6af", + "revCount": 642660, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.642660%2Brev-a71e967ef3694799d0c418c98332f7ff4cc5f6af/0190462b-ab23-7472-8ae7-ae4f8bde47d9/source.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1.%2A.tar.gz" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..bb98f71 --- /dev/null +++ b/flake.nix @@ -0,0 +1,37 @@ +{ + description = "A Nix-flake-based Zig development environment"; + + inputs.nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1.*.tar.gz"; + + outputs = { + self, + nixpkgs, + }: let + supportedSystems = ["x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin"]; + forEachSupportedSystem = f: + nixpkgs.lib.genAttrs supportedSystems (system: + f { + pkgs = import nixpkgs {inherit system;}; + }); + in { + devShells = forEachSupportedSystem ({pkgs}: { + default = pkgs.mkShell { + packages = with pkgs; [ + zig + zls + zig-shell-completions + SDL2 + SDL2.dev + SDL2_gfx + SDL2_ttf + SDL2_image + pkg-config + libjpeg + libjpeg.dev + libtiff + libpng + ]; + }; + }); + }; +} diff --git a/src/binding/sdl.zig b/src/binding/sdl.zig index 6808d91..bc2dd70 100644 --- a/src/binding/sdl.zig +++ b/src/binding/sdl.zig @@ -2695,6 +2695,10 @@ pub const SDL_SysWMInfo = extern struct { hdc: std.os.windows.HDC, hinstance: std.os.windows.HINSTANCE, }, + x11: extern struct { + display: *opaque {}, + window: c_ulong, + }, // TODO: other variants }, }; diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index e6dfd2c..0fd245b 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -417,7 +417,8 @@ pub const Window = struct { pub fn getWMInfo(w: Window) !c.SDL_SysWMInfo { var info: c.SDL_SysWMInfo = undefined; - if (c.SDL_GetWindowWMInfo(w.ptr, &info) != 0) { + info.version = c.SDL_VERSION; + if (c.SDL_GetWindowWMInfo(w.ptr, &info) != c.SDL_TRUE) { return makeError(); } return info; From a4a1c9c4a274b47a40747a7bcfa8f579b4ad60d0 Mon Sep 17 00:00:00 2001 From: Adi Hodos Date: Fri, 28 Jun 2024 20:21:57 +0300 Subject: [PATCH 33/50] Updated NixOs flake to use the Zig overlay --- flake.lock | 161 ++++++++++++++++++++++++++++++++++++++++++++++++++--- flake.nix | 72 ++++++++++++++---------- 2 files changed, 194 insertions(+), 39 deletions(-) diff --git a/flake.lock b/flake.lock index 6add7d4..d243ce5 100644 --- a/flake.lock +++ b/flake.lock @@ -1,22 +1,165 @@ { "nodes": { + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1696426674, + "narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "0f9255e01c2351cc7d116c072cb317785dd33b33", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1710146030, + "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_2": { + "inputs": { + "systems": "systems_2" + }, + "locked": { + "lastModified": 1705309234, + "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "gitignore": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1709087332, + "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", + "owner": "hercules-ci", + "repo": "gitignore.nix", + "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "gitignore.nix", + "type": "github" + } + }, "nixpkgs": { "locked": { - "lastModified": 1719075281, - "narHash": "sha256-CyyxvOwFf12I91PBWz43iGT1kjsf5oi6ax7CrvaMyAo=", - "rev": "a71e967ef3694799d0c418c98332f7ff4cc5f6af", - "revCount": 642660, - "type": "tarball", - "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.642660%2Brev-a71e967ef3694799d0c418c98332f7ff4cc5f6af/0190462b-ab23-7472-8ae7-ae4f8bde47d9/source.tar.gz" + "lastModified": 1719234068, + "narHash": "sha256-1AjSIedDC/aERt24KsCUftLpVppW61S7awfjGe7bMio=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "90bd1b26e23760742fdcb6152369919098f05417", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-23.11", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1708161998, + "narHash": "sha256-6KnemmUorCvlcAvGziFosAVkrlWZGIc6UNT9GUYr0jQ=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "84d981bae8b5e783b3b548de505b22880559515f", + "type": "github" }, "original": { - "type": "tarball", - "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1.%2A.tar.gz" + "owner": "NixOS", + "ref": "nixos-23.11", + "repo": "nixpkgs", + "type": "github" } }, "root": { "inputs": { - "nixpkgs": "nixpkgs" + "flake-utils": "flake-utils", + "gitignore": "gitignore", + "nixpkgs": "nixpkgs", + "zig": "zig" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "systems_2": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "zig": { + "inputs": { + "flake-compat": "flake-compat", + "flake-utils": "flake-utils_2", + "nixpkgs": "nixpkgs_2" + }, + "locked": { + "lastModified": 1719576582, + "narHash": "sha256-67IXVODHbk7A6xh8qw7Yff8CVCOvxGX5LjPEBHpVve8=", + "owner": "mitchellh", + "repo": "zig-overlay", + "rev": "d001a0f4298c8e3ba7716b0c60c0d80e16a693df", + "type": "github" + }, + "original": { + "owner": "mitchellh", + "repo": "zig-overlay", + "type": "github" } } }, diff --git a/flake.nix b/flake.nix index bb98f71..259493b 100644 --- a/flake.nix +++ b/flake.nix @@ -1,37 +1,49 @@ { - description = "A Nix-flake-based Zig development environment"; + description = "An empty project that uses Zig."; - inputs.nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1.*.tar.gz"; + inputs = { + nixpkgs.url = "github:nixos/nixpkgs/nixos-23.11"; + flake-utils.url = "github:numtide/flake-utils"; + zig.url = "github:mitchellh/zig-overlay"; + + gitignore.url = "github:hercules-ci/gitignore.nix"; + gitignore.inputs.nixpkgs.follows = "nixpkgs"; + }; outputs = { self, nixpkgs, - }: let - supportedSystems = ["x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin"]; - forEachSupportedSystem = f: - nixpkgs.lib.genAttrs supportedSystems (system: - f { - pkgs = import nixpkgs {inherit system;}; - }); - in { - devShells = forEachSupportedSystem ({pkgs}: { - default = pkgs.mkShell { - packages = with pkgs; [ - zig - zls - zig-shell-completions - SDL2 - SDL2.dev - SDL2_gfx - SDL2_ttf - SDL2_image - pkg-config - libjpeg - libjpeg.dev - libtiff - libpng - ]; - }; - }); - }; + flake-utils, + gitignore, + ... + } @ inputs: let + overlays = [ + (final: prev: { + zigpkgs = inputs.zig.packages.${prev.system}; + }) + ]; + + systems = builtins.attrNames inputs.zig.packages; + in + flake-utils.lib.eachSystem systems ( + system: let + pkgs = import nixpkgs {inherit overlays system;}; + in rec { + devShells.default = pkgs.mkShell { + packages = with pkgs; [ + zigpkgs.master + zls + + SDL2 + SDL2.dev + SDL2_ttf + SDL2_gfx + SDL2_image + ]; + }; + + # For compatibility with older versions of the `nix` binary + devShell = self.devShells.${system}.default; + } + ); } From adee311e3c4803b1a28444296e3b955aa72ac5d7 Mon Sep 17 00:00:00 2001 From: Charlie Date: Fri, 28 Jun 2024 23:44:36 +0100 Subject: [PATCH 34/50] add zig-cache to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e6c5a58..4d18d90 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .zig-cache +zig-cache zig-out deps.zig gyro.lock From 3415156f6f2167ab0a201b32bcf9465b101d7f7b Mon Sep 17 00:00:00 2001 From: Jussi Date: Sat, 13 Jul 2024 11:40:17 +0300 Subject: [PATCH 35/50] refactor build.zig, add SDL_ttf support --- build.zig | 461 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 243 insertions(+), 218 deletions(-) diff --git a/build.zig b/build.zig index 06b4a24..e6ed51a 100644 --- a/build.zig +++ b/build.zig @@ -7,8 +7,10 @@ const std = @import("std"); const builtin = @import("builtin"); +const Library = enum { SDL2, SDL2_ttf }; + pub fn build(b: *std.Build) !void { - const sdk = Sdk.init(b, null); + const sdk = Sdk.init(b, null, null); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); @@ -43,7 +45,7 @@ pub fn build(b: *std.Build) !void { lib_test.linkSystemLibrary("sdl2"); lib_test.linkSystemLibrary("webp"); } - sdk.link(lib_test, .dynamic); + sdk.link(lib_test, .dynamic, .SDL2); const test_lib_step = b.step("test", "Runs the library tests."); test_lib_step.dependOn(&lib_test.step); @@ -55,7 +57,7 @@ pub fn build(b: *std.Build) !void { .target = target, .optimize = optimize, }); - sdk.link(demo_wrapper, sdl_linkage); + sdk.link(demo_wrapper, sdl_linkage, .SDL2); demo_wrapper.root_module.addImport("sdl2", sdk.getWrapperModule()); b.installArtifact(demo_wrapper); @@ -65,7 +67,7 @@ pub fn build(b: *std.Build) !void { .target = target, .optimize = optimize, }); - sdk.link(demo_wrapper_image, sdl_linkage); + sdk.link(demo_wrapper_image, sdl_linkage, .SDL2); demo_wrapper_image.root_module.addImport("sdl2", sdk.getWrapperModule()); demo_wrapper_image.linkSystemLibrary("sdl2_image"); demo_wrapper_image.linkSystemLibrary("jpeg"); @@ -83,7 +85,7 @@ pub fn build(b: *std.Build) !void { .target = target, .optimize = optimize, }); - sdk.link(demo_native, sdl_linkage); + sdk.link(demo_native, sdl_linkage, .SDL2); demo_native.root_module.addImport("sdl2", sdk.getNativeModule()); b.installArtifact(demo_native); @@ -124,25 +126,30 @@ fn sdkPath(comptime suffix: []const u8) []const u8 { const sdl2_symbol_definitions = @embedFile("stubs/libSDL2.def"); build: *Build, -config_path: []const u8, +sdl_config_path: []const u8, prepare_sources: *PrepareStubSourceStep, +sdl_ttf_config_path: []const u8, /// Creates a instance of the Sdk and initializes internal steps. /// Initialize once, use everywhere (in your `build` function). -pub fn init(b: *Build, maybe_config_path: ?[]const u8) *Sdk { +pub fn init(b: *Build, maybe_config_path: ?[]const u8, maybe_sdl_ttf_config_path: ?[]const u8) *Sdk { const sdk = b.allocator.create(Sdk) catch @panic("out of memory"); - const config_path = maybe_config_path orelse std.fs.path.join( + + const sdl_config_path = maybe_config_path orelse std.fs.path.join( b.allocator, - &[_][]const u8{ - b.pathFromRoot(".build_config"), - "sdl.json", - }, + &[_][]const u8{ b.pathFromRoot(".build_config"), "sdl.json" }, + ) catch @panic("out of memory"); + + const sdl_ttf_config_path = maybe_sdl_ttf_config_path orelse std.fs.path.join( + b.allocator, + &[_][]const u8{ b.pathFromRoot(".build_config"), "sdl_ttf.json" }, ) catch @panic("out of memory"); sdk.* = .{ .build = b, - .config_path = config_path, + .sdl_config_path = sdl_config_path, + .sdl_ttf_config_path = sdl_ttf_config_path, .prepare_sources = undefined, }; sdk.prepare_sources = PrepareStubSourceStep.create(sdk); @@ -220,225 +227,157 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { }); } -/// Links SDL2 TTF to the given exe. -/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn linkTtf(sdk: *Sdk, exe: *Compile) void { - const b = sdk.build; - const target = exe.root_module.resolved_target.?; - const is_native = target.query.isNativeOs(); +fn linkLinuxCross(sdk: *Sdk, exe: *Compile) !void { + const build_linux_sdl_stub = sdk.build.addSharedLibrary(.{ + .name = "SDL2", + .target = exe.root_module.resolved_target.?, + .optimize = exe.root_module.optimize.?, + }); + build_linux_sdl_stub.addAssemblyFile(sdk.prepare_sources.getStubFile()); + exe.linkLibrary(build_linux_sdl_stub); +} - if (target.result.os.tag == .linux) { - if (!is_native) { - @panic("Cannot cross-compile with TTF to linux yet."); +fn linkWindows( + sdk: *Sdk, + exe: *Compile, + linkage: std.builtin.LinkMode, + comptime library: Library, + paths: Paths, +) !void { + exe.addIncludePath(.{ .cwd_relative = paths.include }); + exe.addLibraryPath(.{ .cwd_relative = paths.libs }); + + const lib_name = switch (library) { + .SDL2 => "SDL2", + .SDL2_ttf => "SDL2_ttf", + }; + + if (exe.root_module.resolved_target.?.result.abi == .msvc) { + exe.linkSystemLibrary2(lib_name, .{ .use_pkg_config = .no }); + } else { + const file_name = try std.fmt.allocPrint(sdk.build.allocator, "lib{s}.{s}", .{ + lib_name, + if (linkage == .static) "a" else "dll.a", + }); + defer sdk.build.allocator.free(file_name); + + const lib_path = try std.fs.path.join(sdk.build.allocator, &[_][]const u8{ paths.libs, file_name }); + defer sdk.build.allocator.free(lib_path); + + exe.addObjectFile(.{ .cwd_relative = lib_path }); + + if (linkage == .static and library == .SDL2) { + const static_libs = [_][]const u8{ + "setupapi", + "user32", + "gdi32", + "winmm", + "imm32", + "ole32", + "oleaut32", + "shell32", + "version", + "uuid", + }; + for (static_libs) |lib| exe.linkSystemLibrary(lib); } + } - // on linux with compilation for native target, - // we should rely on the system libraries to "just work" - exe.linkSystemLibrary("sdl2_ttf"); - } else if (target.result.os.tag == .windows) { - @panic("Cannot link TTF on windows yet."); - } else if (target.result.isDarwin()) { - if (!host_system.os.tag.isDarwin()) - @panic("Cannot cross-compile with TTF to macOS yet."); + if (linkage == .dynamic and exe.kind == .exe) { + const dll_name = try std.fmt.allocPrint(sdk.build.allocator, "{s}.dll", .{lib_name}); + defer sdk.build.allocator.free(dll_name); + + const dll_path = try std.fs.path.join(sdk.build.allocator, &[_][]const u8{ paths.bin, dll_name }); + defer sdk.build.allocator.free(dll_path); + + sdk.build.installBinFile(dll_path, dll_name); + } +} + +fn linkMacOS(exe: *Compile, comptime library: Library) !void { + exe.linkSystemLibrary(switch (library) { + .SDL2 => "sdl2", + .SDL2_ttf => "sdl2_ttf", + }); - exe.linkSystemLibrary("sdl2_ttf"); + if (library == .SDL2) { + exe.linkFramework("IOKit"); + exe.linkFramework("Cocoa"); + exe.linkFramework("CoreAudio"); + exe.linkFramework("Carbon"); + exe.linkFramework("Metal"); + exe.linkFramework("QuartzCore"); + exe.linkFramework("AudioToolbox"); + exe.linkFramework("ForceFeedback"); + exe.linkFramework("GameController"); + exe.linkFramework("CoreHaptics"); + exe.linkSystemLibrary("iconv"); + } else if (library == .SDL2_ttf) { exe.linkSystemLibrary("freetype"); exe.linkSystemLibrary("harfbuzz"); exe.linkSystemLibrary("bz2"); exe.linkSystemLibrary("zlib"); exe.linkSystemLibrary("graphite2"); - } else { - const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown"; - std.log.warn("Linking SDL2_TTF for {s} is not tested, linking might fail!", .{triple_string}); - - // on all other platforms, just try the system way: - exe.linkSystemLibrary("sdl2_ttf"); } } -/// Links SDL2 to the given exe and adds required installs if necessary. +/// Links SDL2 or SDL2_ttf to the given exe and adds required installs if necessary. /// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void { - // TODO: Implement - +pub fn link( + sdk: *Sdk, + exe: *Compile, + linkage: std.builtin.LinkMode, + comptime library: Library, +) void { const b = sdk.build; const target = exe.root_module.resolved_target.?; const is_native = target.query.isNativeOs(); - // This is required on all platforms exe.linkLibC(); - if (target.result.os.tag == .linux and !is_native) { - // for cross-compilation to Linux, we use a magic trick: - // we compile a stub .so file we will link against an SDL2.so even if that file - // doesn't exist on our system - - const build_linux_sdl_stub = b.addSharedLibrary(.{ - .name = "SDL2", - .target = exe.root_module.resolved_target.?, - .optimize = exe.root_module.optimize.?, - }); - build_linux_sdl_stub.addAssemblyFile(sdk.prepare_sources.getStubFile()); - - // We need to link against libc - exe.linkLibC(); - - // link against the output of our stub - exe.linkLibrary(build_linux_sdl_stub); - } else if (target.result.os.tag == .linux) { - // on linux with compilation for native target, - // we should rely on the system libraries to "just work" - exe.linkSystemLibrary("sdl2"); - } else if (target.result.os.tag == .windows) { - const sdk_paths = sdk.getPaths(target) catch |err| { - const writer = std.io.getStdErr().writer(); - - const target_name = tripleName(sdk.build.allocator, target) catch @panic("out of memory"); - - switch (err) { - error.FileNotFound => { - writer.print("Could not auto-detect SDL2 sdk configuration. Please provide {s} with the following contents filled out:\n", .{ - sdk.config_path, - }) catch @panic("io error"); - writer.print("{{\n \"{s}\": {{\n", .{target_name}) catch @panic("io error"); - writer.writeAll( - \\ "include": "/include", - \\ "libs": "/lib", - \\ "bin": "/bin" - \\ } - \\} - \\ - ) catch @panic("io error"); - writer.writeAll( - \\ - \\You can obtain a SDL2 sdk for windows from https://www.libsdl.org/download-2.0.php - \\ - ) catch @panic("io error"); - }, - error.MissingTarget => { - writer.print("{s} is missing a SDK definition for {s}. Please add the following section to the file and fill the paths:\n", .{ - sdk.config_path, - target_name, - }) catch @panic("io error"); - writer.print(" \"{s}\": {{\n", .{target_name}) catch @panic("io error"); - writer.writeAll( - \\ "include": "/include", - \\ "libs": "/lib", - \\ "bin": "/bin" - \\} - ) catch @panic("io error"); - writer.writeAll( - \\ - \\You can obtain a SDL2 sdk for windows from https://www.libsdl.org/download-2.0.php - \\ - ) catch @panic("io error"); - }, - error.InvalidJson => { - writer.print("{s} contains invalid JSON. Please fix that file!\n", .{ - sdk.config_path, - }) catch @panic("io error"); - }, - error.InvalidTarget => { - writer.print("{s} contains a invalid zig triple. Please fix that file!\n", .{ - sdk.config_path, - }) catch @panic("io error"); - }, - } - - std.process.exit(1); - }; - - // linking on windows is sadly not as trivial as on linux: - // we have to respect 6 different configurations {x86,x64}-{msvc,mingw}-{dynamic,static} - - if (target.result.abi == .msvc and linkage != .dynamic) - @panic("SDL cannot be linked statically for MSVC"); - - // These will be added for C-Imports or C files. - if (target.result.abi != .msvc) { - // SDL2 (mingw) ships the SDL include files under `include/SDL2/` which is very inconsitent with - // all other platforms, so we just remove this prefix here - const include_path = std.fs.path.join(b.allocator, &[_][]const u8{ - sdk_paths.include, - "SDL2", - }) catch @panic("out of memory"); - exe.addIncludePath(.{ .cwd_relative = include_path }); - } else { - exe.addIncludePath(.{ .cwd_relative = sdk_paths.include }); - } - - // link the right libraries - if (target.result.abi == .msvc) { - // and links those as normal libraries - exe.addLibraryPath(.{ .cwd_relative = sdk_paths.libs }); - exe.linkSystemLibrary2("SDL2", .{ .use_pkg_config = .no }); - } else { - const file_name = switch (linkage) { - .static => "libSDL2.a", - .dynamic => "libSDL2.dll.a", - }; - - const lib_path = std.fs.path.join(b.allocator, &[_][]const u8{ - sdk_paths.libs, - file_name, - }) catch @panic("out of memory"); - - exe.addObjectFile(.{ .cwd_relative = lib_path }); - - if (linkage == .static) { - // link all system libraries required for SDL2: - const static_libs = [_][]const u8{ - "setupapi", - "user32", - "gdi32", - "winmm", - "imm32", - "ole32", - "oleaut32", - "shell32", - "version", - "uuid", + if (target.result.os.tag == .linux) { + if (!is_native) { + if (library == .SDL2) { + linkLinuxCross(sdk, exe) catch |err| { + std.debug.panic("Failed to link {s} for Linux cross-compilation: {s}", .{ @tagName(library), @errorName(err) }); }; - for (static_libs) |lib| - exe.linkSystemLibrary(lib); + } else { + std.debug.panic("Cross-compilation not supported for {s} on Linux", .{@tagName(library)}); } + } else { + exe.linkSystemLibrary(switch (library) { + .SDL2 => "sdl2", + .SDL2_ttf => "sdl2_ttf", + }); } + } else if (target.result.os.tag == .windows) { + const paths = switch (library) { + .SDL2 => getPaths(sdk, sdk.sdl_config_path, target, .SDL2), + .SDL2_ttf => getPaths(sdk, sdk.sdl_ttf_config_path, target, .SDL2_ttf), + } catch |err| { + std.debug.panic("Failed to get paths for {s}: {s}", .{ @tagName(library), @errorName(err) }); + }; - if (linkage == .dynamic and exe.kind == .exe) { - // On window, we need to copy SDL2.dll to the bin directory - // for executables - const sdl2_dll_path = std.fs.path.join(sdk.build.allocator, &[_][]const u8{ - sdk_paths.bin, - "SDL2.dll", - }) catch @panic("out of memory"); - sdk.build.installBinFile(sdl2_dll_path, "SDL2.dll"); - } + linkWindows(sdk, exe, linkage, library, paths) catch |err| { + std.debug.panic("Failed to link {s} for Windows: {s}", .{ @tagName(library), @errorName(err) }); + }; } else if (target.result.isDarwin()) { - // TODO: Implement cross-compilaton to macOS via system root provisioning - if (!host_system.os.tag.isDarwin()) - @panic("Cannot cross-compile to macOS yet."); - - // on MacOS, we require a brew install - // requires sdl2 and sdl2_image to be installed via brew - exe.linkSystemLibrary("sdl2"); - - exe.linkFramework("IOKit"); - exe.linkFramework("Cocoa"); - exe.linkFramework("CoreAudio"); - exe.linkFramework("Carbon"); - exe.linkFramework("Metal"); - exe.linkFramework("QuartzCore"); - exe.linkFramework("AudioToolbox"); - exe.linkFramework("ForceFeedback"); - exe.linkFramework("GameController"); - exe.linkFramework("CoreHaptics"); - exe.linkSystemLibrary("iconv"); + if (!host_system.os.tag.isDarwin()) { + std.debug.panic("Cross-compilation not supported for {s} on macOS", .{@tagName(library)}); + } + linkMacOS(exe, library) catch |err| { + std.debug.panic("Failed to link {s} for macOS: {s}", .{ @tagName(library), @errorName(err) }); + }; } else { - const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown"; - std.log.warn("Linking SDL2 for {s} is not tested, linking might fail!", .{triple_string}); - - // on all other platforms, just try the system way: - exe.linkSystemLibrary("sdl2"); + const triple_string = target.query.zigTriple(b.allocator) catch |err| { + std.debug.panic("Failed to get target triple: {s}", .{@errorName(err)}); + }; + defer b.allocator.free(triple_string); + std.log.warn("Linking {s} for {s} is not tested, linking might fail!", .{ @tagName(library), triple_string }); + exe.linkSystemLibrary(switch (library) { + .SDL2 => "sdl2", + .SDL2_ttf => "sdl2_ttf", + }); } } @@ -448,18 +387,101 @@ const Paths = struct { bin: []const u8, }; -fn getPaths(sdk: *Sdk, target_local: std.Build.ResolvedTarget) error{ MissingTarget, FileNotFound, InvalidJson, InvalidTarget }!Paths { - const json_data = std.fs.cwd().readFileAlloc(sdk.build.allocator, sdk.config_path, 1 << 20) catch |err| switch (err) { - error.FileNotFound => return error.FileNotFound, - else => |e| @panic(@errorName(e)), +const GetPathsError = error{ + FileNotFound, + InvalidJson, + InvalidTarget, + MissingTarget, +}; + +fn printPathsErrorMessage(sdk: *Sdk, config_path: []const u8, target_local: std.Build.ResolvedTarget, err: GetPathsError, library: Library) !void { + const writer = std.io.getStdErr().writer(); + const target_name = try tripleName(sdk.build.allocator, target_local); + defer sdk.build.allocator.free(target_name); + + const lib_name = switch (library) { + .SDL2 => "SDL2", + .SDL2_ttf => "SDL2_ttf", + }; + + const download_url = switch (library) { + .SDL2 => "https://github.com/libsdl-org/SDL/releases", + .SDL2_ttf => "https://github.com/libsdl-org/SDL_ttf/releases", + }; + + switch (err) { + GetPathsError.FileNotFound => { + try writer.print("Could not auto-detect {s} sdk configuration. Please provide {s} with the following contents filled out:\n", .{ lib_name, config_path }); + try writer.print("{{\n \"{s}\": {{\n", .{target_name}); + try writer.writeAll( + \\ "include": "/include", + \\ "libs": "/lib", + \\ "bin": "/bin" + \\ } + \\} + \\ + ); + try writer.print( + \\ + \\You can obtain a {s} sdk for Windows from {s} + \\ + , .{ lib_name, download_url }); + }, + GetPathsError.MissingTarget => { + try writer.print("{s} is missing a SDK definition for {s}. Please add the following section to the file and fill the paths:\n", .{ config_path, target_name }); + try writer.print(" \"{s}\": {{\n", .{target_name}); + try writer.writeAll( + \\ "include": "/include", + \\ "libs": "/lib", + \\ "bin": "/bin" + \\} + ); + try writer.print( + \\ + \\You can obtain a {s} sdk for Windows from {s} + \\ + , .{ lib_name, download_url }); + }, + GetPathsError.InvalidJson => { + try writer.print("{s} contains invalid JSON. Please fix that file!\n", .{config_path}); + }, + GetPathsError.InvalidTarget => { + try writer.print("{s} contains an invalid zig triple. Please fix that file!\n", .{config_path}); + }, + } +} + +fn getPaths(sdk: *Sdk, config_path: []const u8, target_local: std.Build.ResolvedTarget, library: Library) GetPathsError!Paths { + const json_data = std.fs.cwd().readFileAlloc(sdk.build.allocator, config_path, 1 << 20) catch |err| switch (err) { + error.FileNotFound => { + printPathsErrorMessage(sdk, config_path, target_local, GetPathsError.FileNotFound, library) catch |e| { + std.debug.panic("Failed to print error message: {s}", .{@errorName(e)}); + }; + return GetPathsError.FileNotFound; + }, + else => |e| { + std.log.err("Failed to read config file: {s}", .{@errorName(e)}); + return GetPathsError.FileNotFound; + }, + }; + defer sdk.build.allocator.free(json_data); + + const parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch { + printPathsErrorMessage(sdk, config_path, target_local, GetPathsError.InvalidJson, library) catch |e| { + std.debug.panic("Failed to print error message: {s}", .{@errorName(e)}); + }; + return GetPathsError.InvalidJson; }; + defer parsed.deinit(); - const parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch return error.InvalidJson; var root_node = parsed.value.object; var config_iterator = root_node.iterator(); while (config_iterator.next()) |entry| { const config_target = sdk.build.resolveTargetQuery( - std.Target.Query.parse(.{ .arch_os_abi = entry.key_ptr.* }) catch return error.InvalidTarget, + std.Target.Query.parse(.{ .arch_os_abi = entry.key_ptr.* }) catch { + std.log.err("Invalid target in config file: {s}", .{entry.key_ptr.*}); + return GetPathsError.InvalidTarget; + }, ); if (target_local.result.cpu.arch != config_target.result.cpu.arch) @@ -468,17 +490,20 @@ fn getPaths(sdk: *Sdk, target_local: std.Build.ResolvedTarget) error{ MissingTar continue; if (target_local.result.abi != config_target.result.abi) continue; - // load paths const node = entry.value_ptr.*.object; return Paths{ - .include = node.get("include").?.string, - .libs = node.get("libs").?.string, - .bin = node.get("bin").?.string, + .include = sdk.build.allocator.dupe(u8, node.get("include").?.string) catch @panic("out of memory"), + .libs = sdk.build.allocator.dupe(u8, node.get("libs").?.string) catch @panic("out of memory"), + .bin = sdk.build.allocator.dupe(u8, node.get("bin").?.string) catch @panic("out of memory"), }; } - return error.MissingTarget; + + printPathsErrorMessage(sdk, config_path, target_local, GetPathsError.MissingTarget, library) catch |e| { + std.debug.panic("Failed to print error message: {s}", .{@errorName(e)}); + }; + return GetPathsError.MissingTarget; } const PrepareStubSourceStep = struct { From 37e7dcae630d7829e199523015d89d6e60a9ae5c Mon Sep 17 00:00:00 2001 From: Jussi Date: Sat, 13 Jul 2024 22:33:37 +0300 Subject: [PATCH 36/50] fix: use switch instead of if-expression --- build.zig | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/build.zig b/build.zig index e6ed51a..4910179 100644 --- a/build.zig +++ b/build.zig @@ -300,24 +300,26 @@ fn linkMacOS(exe: *Compile, comptime library: Library) !void { .SDL2_ttf => "sdl2_ttf", }); - if (library == .SDL2) { - exe.linkFramework("IOKit"); - exe.linkFramework("Cocoa"); - exe.linkFramework("CoreAudio"); - exe.linkFramework("Carbon"); - exe.linkFramework("Metal"); - exe.linkFramework("QuartzCore"); - exe.linkFramework("AudioToolbox"); - exe.linkFramework("ForceFeedback"); - exe.linkFramework("GameController"); - exe.linkFramework("CoreHaptics"); - exe.linkSystemLibrary("iconv"); - } else if (library == .SDL2_ttf) { - exe.linkSystemLibrary("freetype"); - exe.linkSystemLibrary("harfbuzz"); - exe.linkSystemLibrary("bz2"); - exe.linkSystemLibrary("zlib"); - exe.linkSystemLibrary("graphite2"); + switch (library) { + .SDL2 => { + exe.linkFramework("Cocoa"); + exe.linkFramework("CoreAudio"); + exe.linkFramework("Carbon"); + exe.linkFramework("Metal"); + exe.linkFramework("QuartzCore"); + exe.linkFramework("AudioToolbox"); + exe.linkFramework("ForceFeedback"); + exe.linkFramework("GameController"); + exe.linkFramework("CoreHaptics"); + exe.linkSystemLibrary("iconv"); + }, + .SDL2_ttf => { + exe.linkSystemLibrary("freetype"); + exe.linkSystemLibrary("harfbuzz"); + exe.linkSystemLibrary("bz2"); + exe.linkSystemLibrary("zlib"); + exe.linkSystemLibrary("graphite2"); + }, } } From e231bcb392fe7abdb52bf17555daf76c3bba4427 Mon Sep 17 00:00:00 2001 From: jack Date: Thu, 18 Jul 2024 21:43:35 +0800 Subject: [PATCH 37/50] update to zig 0.14.0-dev.363+c3faae6bf --- build.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.zig b/build.zig index 4910179..e5925f7 100644 --- a/build.zig +++ b/build.zig @@ -539,8 +539,8 @@ const PrepareStubSourceStep = struct { return .{ .generated = .{ .file = &self.assembly_source } }; } - fn make(step: *Step, prog_node: std.Progress.Node) !void { - _ = prog_node; + fn make(step: *Step, make_opt: std.Build.Step.MakeOptions) !void { + _ = make_opt; const self: *Self = @fieldParentPtr("step", step); var cache = CacheBuilder.init(self.sdk.build, "sdl"); From 10ecb6c1685977cf653d4630cc8512233624d9ac Mon Sep 17 00:00:00 2001 From: aleloi Date: Mon, 22 Jul 2024 09:21:09 +0200 Subject: [PATCH 38/50] Update example build file in README.md std.Build has changed slightly by zig 0.14, and SDL.zig/build.zig has also some minor changes --- README.md | 8 ++++---- build.zig | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0fff208..8a531f7 100644 --- a/README.md +++ b/README.md @@ -12,21 +12,21 @@ This is an example `build.zig` that will link the SDL2 library to your project. const std = @import("std"); const sdl = @import("SDL.zig/build.zig"); // Replace with the actual path in your project -pub fn build(b: *std.Build.Builder) !void { +pub fn build(b: *std.Build) !void { // Determine compilation target const target = b.standardTargetOptions(.{}); // Create a new instance of the SDL2 Sdk - const sdk = sdl.init(b, null); + const sdk = sdl.init(b, null, null); // Create executable for our example const demo_basic = b.addExecutable(.{ .name = "demo-basic", - .root_source_file = .{ .path = "my-game.zig" }, + .root_source_file = b.path("my-game.zig"), .target = target, }); - sdk.link(demo_basic, .dynamic); // link SDL2 as a shared library + sdk.link(demo_basic, .dynamic, sdl.Library.SDL2); // link SDL2 as a shared library // Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow) demo_basic.root_module.addImport("sdl2", sdk.getNativeModule()); diff --git a/build.zig b/build.zig index e5925f7..6f221e6 100644 --- a/build.zig +++ b/build.zig @@ -7,7 +7,7 @@ const std = @import("std"); const builtin = @import("builtin"); -const Library = enum { SDL2, SDL2_ttf }; +pub const Library = enum { SDL2, SDL2_ttf }; pub fn build(b: *std.Build) !void { const sdk = Sdk.init(b, null, null); From 5b9dfdcaec566938a0412398b6c5cb5aea0b89a9 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:14:17 -0400 Subject: [PATCH 39/50] Add Window.setSize() --- src/wrapper/sdl.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 37328ea..928dfd3 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -398,6 +398,10 @@ pub const Window = struct { c.SDL_SetWindowPosition(w.ptr, p.x, p.y); } + pub fn setSize(w: Window, s: Size) !void { + c.SDL_SetWindowSize(w.ptr, s.width, s.height); + } + pub fn setMinimumSize(w: Window, width: c_int, height: c_int) void { c.SDL_SetWindowMinimumSize(w.ptr, width, height); } From 51619f310fb15c8403daa0291b17e63944652ad2 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:14:32 -0400 Subject: [PATCH 40/50] Add Window.setVisible() --- src/wrapper/sdl.zig | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 928dfd3..a04b4b7 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -431,6 +431,15 @@ pub const Window = struct { pub fn setTitle(w: Window, title: [:0]const u8) void { c.SDL_SetWindowTitle(w.ptr, title); } + + pub fn setVisible(w: Window, visible: bool) void { + if (visible) { + c.SDL_ShowWindow(w.ptr); + } else { + c.SDL_HideWindow(w.ptr); + } + } + }; pub const WindowPosition = union(enum) { From cd2707030376176747dab9f2ae746b11933b3907 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:15:18 -0400 Subject: [PATCH 41/50] Add Window.setFullscreen() --- src/wrapper/sdl.zig | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index a04b4b7..b02711c 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -440,6 +440,17 @@ pub const Window = struct { } } + pub fn setFullscreen(w: Window, dimension: WindowFlags.Dimension) !void { + const flags: u32 = switch (dimension) { + .fullscreen => c.SDL_WINDOW_FULLSCREEN, + .fullscreen_desktop => c.SDL_WINDOW_FULLSCREEN_DESKTOP, + else => 0, + }; + + if (c.SDL_SetWindowFullscreen(w.ptr, flags) != 0) { + return makeError(); + } + } }; pub const WindowPosition = union(enum) { From 126b5a5488c9d08f3d25548cd2cf9642d2b0efac Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:20:57 -0400 Subject: [PATCH 42/50] Wrap SDL_IsGameController() --- src/wrapper/sdl.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 37328ea..578c25b 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -2393,6 +2393,10 @@ pub const GameController = struct { }; } + pub fn is(joystick_index: u31) bool { + return c.SDL_IsGameController(joystick_index) > 0; + } + pub fn close(self: GameController) void { c.SDL_GameControllerClose(self.ptr); } From 839691bc44ebff775757ca091749180ba9c9513b Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:21:07 -0400 Subject: [PATCH 43/50] Add JoyBatteryEvent to the bindings --- src/binding/sdl.zig | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/binding/sdl.zig b/src/binding/sdl.zig index bc2dd70..161e3e9 100644 --- a/src/binding/sdl.zig +++ b/src/binding/sdl.zig @@ -1675,6 +1675,7 @@ pub const SDL_JOYBUTTONDOWN: c_int = 1539; pub const SDL_JOYBUTTONUP: c_int = 1540; pub const SDL_JOYDEVICEADDED: c_int = 1541; pub const SDL_JOYDEVICEREMOVED: c_int = 1542; +pub const SDL_JOYBATTERYUPDATED: c_int = 1543; pub const SDL_CONTROLLERAXISMOTION: c_int = 1616; pub const SDL_CONTROLLERBUTTONDOWN: c_int = 1617; pub const SDL_CONTROLLERBUTTONUP: c_int = 1618; @@ -1830,6 +1831,12 @@ pub const SDL_JoyDeviceEvent = extern struct { timestamp: u32, which: i32, }; +pub const SDL_JoyBatteryEvent = extern struct { + type: u32, + timestamp: u32, + which: SDL_JoystickID, + level: SDL_JoystickPowerLevel, +}; pub const SDL_ControllerAxisEvent = extern struct { type: u32, timestamp: u32, @@ -1964,6 +1971,7 @@ pub const SDL_Event = extern union { jhat: SDL_JoyHatEvent, jbutton: SDL_JoyButtonEvent, jdevice: SDL_JoyDeviceEvent, + jbattery: SDL_JoyBatteryEvent, caxis: SDL_ControllerAxisEvent, cbutton: SDL_ControllerButtonEvent, cdevice: SDL_ControllerDeviceEvent, From 5469724dc68b11448dec3605d62e07a987bfbd26 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:21:20 -0400 Subject: [PATCH 44/50] Expose joy_battery_level event in wrapper --- src/wrapper/sdl.zig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 578c25b..778589d 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -1615,6 +1615,7 @@ pub const Event = union(enum) { pub const TextEditingEvent = c.SDL_TextEditingEvent; pub const TextInputEvent = c.SDL_TextInputEvent; pub const JoyDeviceEvent = c.SDL_JoyDeviceEvent; + pub const JoyBatteryEvent = c.SDL_JoyBatteryEvent; pub const ControllerDeviceEvent = c.SDL_ControllerDeviceEvent; pub const AudioDeviceEvent = c.SDL_AudioDeviceEvent; pub const SensorEvent = c.SDL_SensorEvent; @@ -1652,6 +1653,7 @@ pub const Event = union(enum) { joy_button_up: JoyButtonEvent, joy_device_added: JoyDeviceEvent, joy_device_removed: JoyDeviceEvent, + joy_battery_level: JoyBatteryEvent, controller_axis_motion: ControllerAxisEvent, controller_button_down: ControllerButtonEvent, controller_button_up: ControllerButtonEvent, @@ -1703,6 +1705,7 @@ pub const Event = union(enum) { c.SDL_JOYBUTTONUP => Event{ .joy_button_up = JoyButtonEvent.fromNative(raw.jbutton) }, c.SDL_JOYDEVICEADDED => Event{ .joy_device_added = raw.jdevice }, c.SDL_JOYDEVICEREMOVED => Event{ .joy_device_removed = raw.jdevice }, + c.SDL_JOYBATTERYUPDATED => Event{ .joy_battery_level = raw.jbattery }, c.SDL_CONTROLLERAXISMOTION => Event{ .controller_axis_motion = ControllerAxisEvent.fromNative(raw.caxis) }, c.SDL_CONTROLLERBUTTONDOWN => Event{ .controller_button_down = ControllerButtonEvent.fromNative(raw.cbutton) }, c.SDL_CONTROLLERBUTTONUP => Event{ .controller_button_up = ControllerButtonEvent.fromNative(raw.cbutton) }, From dfd608f4eddcfd629c324eff45ea401010b14512 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:22:13 -0400 Subject: [PATCH 45/50] Fix GameController.nameForIndex to return the proper type --- src/wrapper/sdl.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 778589d..35da6c2 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -2404,8 +2404,8 @@ pub const GameController = struct { c.SDL_GameControllerClose(self.ptr); } - pub fn nameForIndex(joystick_index: u31) ?[:0]const u8 { - return stringToSlice(c.SDL_GameControllerNameForIndex(joystick_index), 0); + pub fn nameForIndex(joystick_index: u31) []const u8 { + return stringToSlice(c.SDL_GameControllerNameForIndex(joystick_index)); } pub fn getButton(self: GameController, button: Button) u8 { From 7cfa4227be8746cda856563aabea8db2b7e3f6df Mon Sep 17 00:00:00 2001 From: mlarouche Date: Mon, 29 Jul 2024 09:22:33 -0400 Subject: [PATCH 46/50] Add GameController.instanceId() that return the joystick instance ID --- src/wrapper/sdl.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wrapper/sdl.zig b/src/wrapper/sdl.zig index 35da6c2..df3ed60 100644 --- a/src/wrapper/sdl.zig +++ b/src/wrapper/sdl.zig @@ -2420,6 +2420,10 @@ pub const GameController = struct { return @as(f32, @floatFromInt(self.getAxis(axis))) / @as(f32, @floatFromInt(c.SDL_JOYSTICK_AXIS_MAX)); } + pub fn instanceId(self: GameController) c.SDL_JoystickID { + return c.SDL_JoystickInstanceID(c.SDL_GameControllerGetJoystick(self.ptr)); + } + pub const Button = enum(i32) { a = c.SDL_CONTROLLER_BUTTON_A, b = c.SDL_CONTROLLER_BUTTON_B, From a8ed4b309acea16ed484bdc99773e220d266b712 Mon Sep 17 00:00:00 2001 From: jack Date: Wed, 31 Jul 2024 21:13:46 +0800 Subject: [PATCH 47/50] update to zig 0.14.0-dev.737+30b4a87db, deprecated sdkPath --- README.md | 16 ++++++++++++---- build.zig | 37 ++++++++++++++++++++----------------- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 8a531f7..9892a82 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,15 @@ This is an example `build.zig` that will link the SDL2 library to your project. ```zig const std = @import("std"); -const sdl = @import("SDL.zig/build.zig"); // Replace with the actual path in your project +const sdl = @import("sdl"); // Replace with the actual name in your build.zig.zon pub fn build(b: *std.Build) !void { // Determine compilation target const target = b.standardTargetOptions(.{}); // Create a new instance of the SDL2 Sdk - const sdk = sdl.init(b, null, null); + // Specifiy dependency name explicitly if necessary (use sdl by default) + const sdk = sdl.init(b, .{}); // Create executable for our example const demo_basic = b.addExecutable(.{ @@ -128,12 +129,19 @@ pub fn main() !void { ## `build.zig` API ```zig -/// Just call `Sdk.init(b, null)` to obtain a handle to the Sdk! +/// Just call `Sdk.init(b, .{})` to obtain a handle to the Sdk! +/// Use `sdl` as dependency name by default. const Sdk = @This(); /// Creates a instance of the Sdk and initializes internal steps. /// Initialize once, use everywhere (in your `build` function). -pub fn init(b: *Build, maybe_config_path: ?[]const u8) *Sdk +/// +/// const SdkOption = struct { +/// dep_name: ?[]const u8 = "sdl", +/// maybe_config_path: ?[]const u8 = null, +/// maybe_sdl_ttf_config_path: ?[]const u8 = null, +/// }; +pub fn init(b: *Build, opt: SdkOption) *Sdk /// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes /// for a more *ziggy* feeling. diff --git a/build.zig b/build.zig index 6f221e6..6ff63b1 100644 --- a/build.zig +++ b/build.zig @@ -10,7 +10,7 @@ const builtin = @import("builtin"); pub const Library = enum { SDL2, SDL2_ttf }; pub fn build(b: *std.Build) !void { - const sdk = Sdk.init(b, null, null); + const sdk = Sdk.init(b, .{ .dep_name = null }); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); @@ -115,16 +115,14 @@ const Compile = Build.Step.Compile; const Sdk = @This(); -fn sdkPath(comptime suffix: []const u8) []const u8 { - if (suffix[0] != '/') @compileError("relToPath requires an absolute path!"); - return comptime blk: { - const root_dir = std.fs.path.dirname(@src().file) orelse "."; - break :blk root_dir ++ suffix; - }; -} - const sdl2_symbol_definitions = @embedFile("stubs/libSDL2.def"); +const SdkOption = struct { + dep_name: ?[]const u8 = "sdl", + maybe_config_path: ?[]const u8 = null, + maybe_sdl_ttf_config_path: ?[]const u8 = null, +}; + build: *Build, sdl_config_path: []const u8, @@ -133,21 +131,26 @@ sdl_ttf_config_path: []const u8, /// Creates a instance of the Sdk and initializes internal steps. /// Initialize once, use everywhere (in your `build` function). -pub fn init(b: *Build, maybe_config_path: ?[]const u8, maybe_sdl_ttf_config_path: ?[]const u8) *Sdk { +pub fn init(b: *Build, opt: SdkOption) *Sdk { const sdk = b.allocator.create(Sdk) catch @panic("out of memory"); - const sdl_config_path = maybe_config_path orelse std.fs.path.join( + const sdl_config_path = opt.maybe_config_path orelse std.fs.path.join( b.allocator, &[_][]const u8{ b.pathFromRoot(".build_config"), "sdl.json" }, ) catch @panic("out of memory"); - const sdl_ttf_config_path = maybe_sdl_ttf_config_path orelse std.fs.path.join( + const sdl_ttf_config_path = opt.maybe_sdl_ttf_config_path orelse std.fs.path.join( b.allocator, &[_][]const u8{ b.pathFromRoot(".build_config"), "sdl_ttf.json" }, ) catch @panic("out of memory"); + const builder = if (opt.dep_name) |name| + b.dependency(name, .{}).builder + else + b; + sdk.* = .{ - .build = b, + .build = builder, .sdl_config_path = sdl_config_path, .sdl_ttf_config_path = sdl_ttf_config_path, .prepare_sources = undefined, @@ -164,7 +167,7 @@ pub fn getNativeModule(sdk: *Sdk) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", false); return sdk.build.createModule(.{ - .root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") }, + .root_source_file = sdk.build.path("src/binding/sdl.zig"), .imports = &.{ .{ .name = sdk.build.dupe("build_options"), @@ -182,7 +185,7 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { const build_options = sdk.build.addOptions(); build_options.addOption(bool, "vulkan", true); return sdk.build.createModule(.{ - .root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") }, + .root_source_file = sdk.build.path("src/binding/sdl.zig"), .imports = &.{ .{ .name = sdk.build.dupe("build_options"), @@ -199,7 +202,7 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { /// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on. pub fn getWrapperModule(sdk: *Sdk) *Build.Module { return sdk.build.createModule(.{ - .root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") }, + .root_source_file = sdk.build.path("src/wrapper/sdl.zig"), .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), @@ -213,7 +216,7 @@ pub fn getWrapperModule(sdk: *Sdk) *Build.Module { /// provided as an argument. pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { return sdk.build.createModule(.{ - .root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") }, + .root_source_file = sdk.build.path("src/wrapper/sdl.zig"), .imports = &.{ .{ .name = sdk.build.dupe("sdl-native"), From 93e215307d0817b11919365c8fa5e16e54322305 Mon Sep 17 00:00:00 2001 From: jack Date: Thu, 8 Aug 2024 23:27:22 +0800 Subject: [PATCH 48/50] allow using absolute path for SDL2 sdk --- build.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 6ff63b1..48717e9 100644 --- a/build.zig +++ b/build.zig @@ -293,7 +293,8 @@ fn linkWindows( const dll_path = try std.fs.path.join(sdk.build.allocator, &[_][]const u8{ paths.bin, dll_name }); defer sdk.build.allocator.free(dll_path); - sdk.build.installBinFile(dll_path, dll_name); + const install_bin = sdk.build.addInstallBinFile(.{ .cwd_relative = dll_path }, dll_name); + exe.step.dependOn(&install_bin.step); } } From 97f9331c1f2be39cd904c20bd0bc2d2e0c3298a1 Mon Sep 17 00:00:00 2001 From: reokodoku Date: Thu, 22 Aug 2024 21:34:13 +0200 Subject: [PATCH 49/50] Update `link` function doc in the README --- README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9892a82..b55b904 100644 --- a/README.md +++ b/README.md @@ -161,13 +161,9 @@ pub fn getWrapperModule(sdk: *Sdk) *Build.Module; /// provided as an argument. pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module; -/// Links SDL2 to the given exe and adds required installs if necessary. +/// Links SDL2 or SDL2_ttf to the given exe and adds required installs if necessary. /// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: std.Build.LibExeObjStep.Linkage) void; - -/// Links SDL2 TTF to the given exe. -/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing! -pub fn linkTtf(sdk: *Sdk, exe: *Compile) void; +pub fn link(sdk: *Sdk, exe: *Build.Step.Compile, linkage: std.builtin.LinkMode, comptime library: Library) void; ``` ## Dependencies From 2052d6e6b348764ac155a4db225ba3f90f8871ec Mon Sep 17 00:00:00 2001 From: jack Date: Sun, 1 Sep 2024 12:04:37 +0800 Subject: [PATCH 50/50] update to 0.14.0-dev.1391+e084c46ed --- build.zig | 102 +++++++++++++++++++++++++++--------------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/build.zig b/build.zig index 48717e9..e03ed12 100644 --- a/build.zig +++ b/build.zig @@ -123,7 +123,7 @@ const SdkOption = struct { maybe_sdl_ttf_config_path: ?[]const u8 = null, }; -build: *Build, +builder: *Build, sdl_config_path: []const u8, prepare_sources: *PrepareStubSourceStep, @@ -150,7 +150,7 @@ pub fn init(b: *Build, opt: SdkOption) *Sdk { b; sdk.* = .{ - .build = builder, + .builder = builder, .sdl_config_path = sdl_config_path, .sdl_ttf_config_path = sdl_ttf_config_path, .prepare_sources = undefined, @@ -164,13 +164,13 @@ pub fn init(b: *Build, opt: SdkOption) *Sdk { /// for a more *ziggy* feeling. /// This is similar to the *C import* result. pub fn getNativeModule(sdk: *Sdk) *Build.Module { - const build_options = sdk.build.addOptions(); + const build_options = sdk.builder.addOptions(); build_options.addOption(bool, "vulkan", false); - return sdk.build.createModule(.{ - .root_source_file = sdk.build.path("src/binding/sdl.zig"), + return sdk.builder.createModule(.{ + .root_source_file = sdk.builder.path("src/binding/sdl.zig"), .imports = &.{ .{ - .name = sdk.build.dupe("build_options"), + .name = sdk.builder.dupe("build_options"), .module = build_options.createModule(), }, }, @@ -182,17 +182,17 @@ pub fn getNativeModule(sdk: *Sdk) *Build.Module { /// provided as an argument. /// This is similar to the *C import* result. pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { - const build_options = sdk.build.addOptions(); + const build_options = sdk.builder.addOptions(); build_options.addOption(bool, "vulkan", true); - return sdk.build.createModule(.{ - .root_source_file = sdk.build.path("src/binding/sdl.zig"), + return sdk.builder.createModule(.{ + .root_source_file = sdk.builder.path("src/binding/sdl.zig"), .imports = &.{ .{ - .name = sdk.build.dupe("build_options"), + .name = sdk.builder.dupe("build_options"), .module = build_options.createModule(), }, .{ - .name = sdk.build.dupe("vulkan"), + .name = sdk.builder.dupe("vulkan"), .module = vulkan, }, }, @@ -201,11 +201,11 @@ pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { /// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on. pub fn getWrapperModule(sdk: *Sdk) *Build.Module { - return sdk.build.createModule(.{ - .root_source_file = sdk.build.path("src/wrapper/sdl.zig"), + return sdk.builder.createModule(.{ + .root_source_file = sdk.builder.path("src/wrapper/sdl.zig"), .imports = &.{ .{ - .name = sdk.build.dupe("sdl-native"), + .name = sdk.builder.dupe("sdl-native"), .module = sdk.getNativeModule(), }, }, @@ -215,15 +215,15 @@ pub fn getWrapperModule(sdk: *Sdk) *Build.Module { /// Returns the smart wrapper with Vulkan support. The Vulkan module provided by `vulkan-zig` must be /// provided as an argument. pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { - return sdk.build.createModule(.{ - .root_source_file = sdk.build.path("src/wrapper/sdl.zig"), + return sdk.builder.createModule(.{ + .root_source_file = sdk.builder.path("src/wrapper/sdl.zig"), .imports = &.{ .{ - .name = sdk.build.dupe("sdl-native"), + .name = sdk.builder.dupe("sdl-native"), .module = sdk.getNativeModuleVulkan(vulkan), }, .{ - .name = sdk.build.dupe("vulkan"), + .name = sdk.builder.dupe("vulkan"), .module = vulkan, }, }, @@ -231,7 +231,7 @@ pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module { } fn linkLinuxCross(sdk: *Sdk, exe: *Compile) !void { - const build_linux_sdl_stub = sdk.build.addSharedLibrary(.{ + const build_linux_sdl_stub = sdk.builder.addSharedLibrary(.{ .name = "SDL2", .target = exe.root_module.resolved_target.?, .optimize = exe.root_module.optimize.?, @@ -258,14 +258,14 @@ fn linkWindows( if (exe.root_module.resolved_target.?.result.abi == .msvc) { exe.linkSystemLibrary2(lib_name, .{ .use_pkg_config = .no }); } else { - const file_name = try std.fmt.allocPrint(sdk.build.allocator, "lib{s}.{s}", .{ + const file_name = try std.fmt.allocPrint(sdk.builder.allocator, "lib{s}.{s}", .{ lib_name, if (linkage == .static) "a" else "dll.a", }); - defer sdk.build.allocator.free(file_name); + defer sdk.builder.allocator.free(file_name); - const lib_path = try std.fs.path.join(sdk.build.allocator, &[_][]const u8{ paths.libs, file_name }); - defer sdk.build.allocator.free(lib_path); + const lib_path = try std.fs.path.join(sdk.builder.allocator, &[_][]const u8{ paths.libs, file_name }); + defer sdk.builder.allocator.free(lib_path); exe.addObjectFile(.{ .cwd_relative = lib_path }); @@ -287,13 +287,13 @@ fn linkWindows( } if (linkage == .dynamic and exe.kind == .exe) { - const dll_name = try std.fmt.allocPrint(sdk.build.allocator, "{s}.dll", .{lib_name}); - defer sdk.build.allocator.free(dll_name); + const dll_name = try std.fmt.allocPrint(sdk.builder.allocator, "{s}.dll", .{lib_name}); + defer sdk.builder.allocator.free(dll_name); - const dll_path = try std.fs.path.join(sdk.build.allocator, &[_][]const u8{ paths.bin, dll_name }); - defer sdk.build.allocator.free(dll_path); + const dll_path = try std.fs.path.join(sdk.builder.allocator, &[_][]const u8{ paths.bin, dll_name }); + defer sdk.builder.allocator.free(dll_path); - const install_bin = sdk.build.addInstallBinFile(.{ .cwd_relative = dll_path }, dll_name); + const install_bin = sdk.builder.addInstallBinFile(.{ .cwd_relative = dll_path }, dll_name); exe.step.dependOn(&install_bin.step); } } @@ -335,7 +335,7 @@ pub fn link( linkage: std.builtin.LinkMode, comptime library: Library, ) void { - const b = sdk.build; + const b = sdk.builder; const target = exe.root_module.resolved_target.?; const is_native = target.query.isNativeOs(); @@ -402,8 +402,8 @@ const GetPathsError = error{ fn printPathsErrorMessage(sdk: *Sdk, config_path: []const u8, target_local: std.Build.ResolvedTarget, err: GetPathsError, library: Library) !void { const writer = std.io.getStdErr().writer(); - const target_name = try tripleName(sdk.build.allocator, target_local); - defer sdk.build.allocator.free(target_name); + const target_name = try tripleName(sdk.builder.allocator, target_local); + defer sdk.builder.allocator.free(target_name); const lib_name = switch (library) { .SDL2 => "SDL2", @@ -458,7 +458,7 @@ fn printPathsErrorMessage(sdk: *Sdk, config_path: []const u8, target_local: std. } fn getPaths(sdk: *Sdk, config_path: []const u8, target_local: std.Build.ResolvedTarget, library: Library) GetPathsError!Paths { - const json_data = std.fs.cwd().readFileAlloc(sdk.build.allocator, config_path, 1 << 20) catch |err| switch (err) { + const json_data = std.fs.cwd().readFileAlloc(sdk.builder.allocator, config_path, 1 << 20) catch |err| switch (err) { error.FileNotFound => { printPathsErrorMessage(sdk, config_path, target_local, GetPathsError.FileNotFound, library) catch |e| { std.debug.panic("Failed to print error message: {s}", .{@errorName(e)}); @@ -470,9 +470,9 @@ fn getPaths(sdk: *Sdk, config_path: []const u8, target_local: std.Build.Resolved return GetPathsError.FileNotFound; }, }; - defer sdk.build.allocator.free(json_data); + defer sdk.builder.allocator.free(json_data); - const parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch { + const parsed = std.json.parseFromSlice(std.json.Value, sdk.builder.allocator, json_data, .{}) catch { printPathsErrorMessage(sdk, config_path, target_local, GetPathsError.InvalidJson, library) catch |e| { std.debug.panic("Failed to print error message: {s}", .{@errorName(e)}); }; @@ -483,7 +483,7 @@ fn getPaths(sdk: *Sdk, config_path: []const u8, target_local: std.Build.Resolved var root_node = parsed.value.object; var config_iterator = root_node.iterator(); while (config_iterator.next()) |entry| { - const config_target = sdk.build.resolveTargetQuery( + const config_target = sdk.builder.resolveTargetQuery( std.Target.Query.parse(.{ .arch_os_abi = entry.key_ptr.* }) catch { std.log.err("Invalid target in config file: {s}", .{entry.key_ptr.*}); return GetPathsError.InvalidTarget; @@ -500,9 +500,9 @@ fn getPaths(sdk: *Sdk, config_path: []const u8, target_local: std.Build.Resolved const node = entry.value_ptr.*.object; return Paths{ - .include = sdk.build.allocator.dupe(u8, node.get("include").?.string) catch @panic("out of memory"), - .libs = sdk.build.allocator.dupe(u8, node.get("libs").?.string) catch @panic("out of memory"), - .bin = sdk.build.allocator.dupe(u8, node.get("bin").?.string) catch @panic("out of memory"), + .include = sdk.builder.allocator.dupe(u8, node.get("include").?.string) catch @panic("out of memory"), + .libs = sdk.builder.allocator.dupe(u8, node.get("libs").?.string) catch @panic("out of memory"), + .bin = sdk.builder.allocator.dupe(u8, node.get("bin").?.string) catch @panic("out of memory"), }; } @@ -521,14 +521,14 @@ const PrepareStubSourceStep = struct { assembly_source: GeneratedFile, pub fn create(sdk: *Sdk) *PrepareStubSourceStep { - const psss = sdk.build.allocator.create(Self) catch @panic("out of memory"); + const psss = sdk.builder.allocator.create(Self) catch @panic("out of memory"); psss.* = .{ .step = Step.init( .{ .id = .custom, .name = "Prepare SDL2 stub sources", - .owner = sdk.build, + .owner = sdk.builder, .makeFn = make, }, ), @@ -547,7 +547,7 @@ const PrepareStubSourceStep = struct { _ = make_opt; const self: *Self = @fieldParentPtr("step", step); - var cache = CacheBuilder.init(self.sdk.build, "sdl"); + var cache = CacheBuilder.init(self.sdk.builder, "sdl"); cache.addBytes(sdl2_symbol_definitions); @@ -571,7 +571,7 @@ const PrepareStubSourceStep = struct { try writer.writeAll(" .byte 0\n"); } - self.assembly_source.path = try std.fs.path.join(self.sdk.build.allocator, &[_][]const u8{ + self.assembly_source.path = try std.fs.path.join(self.sdk.builder.allocator, &[_][]const u8{ dirpath.path, "sdl.S", }); @@ -589,13 +589,13 @@ fn tripleName(allocator: std.mem.Allocator, target_local: std.Build.ResolvedTarg const CacheBuilder = struct { const Self = @This(); - build: *std.Build, + builder: *std.Build, hasher: std.crypto.hash.Sha1, subdir: ?[]const u8, pub fn init(builder: *std.Build, subdir: ?[]const u8) Self { return Self{ - .build = builder, + .builder = builder, .hasher = std.crypto.hash.Sha1.init(.{}), .subdir = if (subdir) |s| builder.dupe(s) @@ -609,10 +609,10 @@ const CacheBuilder = struct { } pub fn addFile(self: *Self, file: LazyPath) !void { - const path = file.getPath(self.build); + const path = file.getPath(self.builder); - const data = try std.fs.cwd().readFileAlloc(self.build.allocator, path, 1 << 32); // 4 GB - defer self.build.allocator.free(data); + const data = try std.fs.cwd().readFileAlloc(self.builder.allocator, path, 1 << 32); // 4 GB + defer self.builder.allocator.free(data); self.addBytes(data); } @@ -623,20 +623,20 @@ const CacheBuilder = struct { const path = if (self.subdir) |subdir| try std.fmt.allocPrint( - self.build.allocator, + self.builder.allocator, "{s}/{s}/o/{}", .{ - self.build.cache_root.path.?, + self.builder.cache_root.path.?, subdir, std.fmt.fmtSliceHexLower(&hash), }, ) else try std.fmt.allocPrint( - self.build.allocator, + self.builder.allocator, "{s}/o/{}", .{ - self.build.cache_root.path.?, + self.builder.cache_root.path.?, std.fmt.fmtSliceHexLower(&hash), }, );