#zig-sdl3: A Zig Wrapper For SDL3
1 messages Β· Page 3 of 1
epic
It's working just without DIA (pdb support) and spirv since I havent bothered wrapping those deps yet
spirv I can do pretty quickly dia idk
works on linux too but I have no idea how to make dxc file dxcompiler.so
compiles on macos (no way to test)
I'll add spirv support then publish tonight
I'll also make a ci step for release artifacts so theres no need to keep rebuilding
Oooo
In protest of Microsoft I will be moving to codeberg
I'll copy everything over to there and make github read only
I might also tackle all the MRs first if there is no easy integration for them
All my future projects will be hosted there too
I am doing the same
I'm also using this opportunity to put this under my indie studio 7Games: https://codeberg.org/7Games
I have a lot of other gamedev projects in the works
All my games will be released open source as well
followed!
Cool!
This is like the most AI issue ever: https://codeberg.org/7Games/zig-sdl3/issues/151#issuecomment-8975028
Very weird
Thanks for your work Gota7, I spent many days making sdl + ttf works from c to zig, took me 10min with yours :). I'm currently using it and I'm looking into the Zig shaders, the zig/spir-v assembly issue is so out my league π
Any plan to add SDL 3.4 that released recently?
It has a builtin GPU Renderer which is quite handy π
there's a new gpu renderer that was introduced in that version?
Renderer API but GPU backed so you can throw on shaders etc. Also native PNG support, better atomics, better Wayland support, renderer api render batching for D3D/Metal/vk, improved logic to find the users fastest vk GPU, some new toolkit for X11 (havent checked it out yet but it sounds like it helps with native dialogs etc)
And I guess better precision scrolling and pen input lol
My understanding was the castholm version is/was very far behind.
Castholm version is from Dec 2
I've been away from my pc between christmas and new years but I'm back now and I'm going to try to get it in sync with 3.4 as soon as possible, however please understand that it might take a few days. they have been developing 3.4.x on a separate branch from 3.2.x so it's not as straightforward as a simple merge like with 3.2.x bumps. they have also added a few new linux system dependencies so I'll need to add all new/update all existing vendored headers for cross-compilation to work
Thank you for your work
things have come a long way since i last looked at this lol
the extras module is cool
glad you like it :>
Progress on this will probably resume after I finish the release of ProtoGame
I'm using this with dvui and worked out-of-the-box. Impressive. Keep up! πͺ
it does? How is your project structured @reef hearth I've been wanting to use this with DVUI but I'm not sure how
You know what I may be tricking myself, it might just be that dvui is managing an install of sdl and I just thought I was using the zig-sdl3 that my project has.
Feel free to check, as I don't even know anymore, zig build system confuses me: https://github.com/Jonatanc05/ZiglyNode
I think you are right. Swapping out the dvui backend takes a lot more. I wish it was easier, but I don't know how.
castholm/SDL has been updated for 3.4.0 now
hell yeah thnx
I will update the wrapper to use your new version either tonight or tomorrow night, I'll try and add the new functions over the weekend
wooo!
Was busy yesterday I should be good to do stuff tonight though
the new SDL features will not be wrapped just yet, but zig-sdl3 will be using the new SDL version so you can do the c. functions for now at least
push once I figure out why some of the tests are failing
tagged v0.1.6 that has the new updated SDL3.4
not sure why CI is failing but I'm currently looking into it, works locally though
https://codeberg.org/7Games/zig-sdl3/actions/runs/5/jobs/3/attempt/1 if there are any guesses please let me know :p
Get:37 http://deb.debian.org/debian bullseye/main amd64 libxi-dev amd64 2:1.7.10-1 [242 kB]
Old debian
Add support for XI 2.4 gesture events
Tags
libXi-1.7.99.2
libXi-1.8
libXi-1.8.1
libXi-1.8.2
.SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_GESTURE = linux,
Maybe the included headers from castholm not working? (Though that step is optional, I think. The install_build_config_h default is false, but I don't know how this works.)
hm yeah I wonder if using a newer version of debian for the CI runner will fix it
when you build for native targets, the system headers in /usr/include take precedence over the vendored headers. you need to explicitly specify a target triple like x86_64-linux-gnu to get a hermetic build that doesn't pull in system dependencies
(this is how zig works normally, but I intentionally kept it that way so that if the user has newer or specialized headers, they take precedence)
Will zig-sdl3 always track only the latest stable release of Zig? (as opposed to staying closer to master)
Though as it stands now, seems like most of the incompatibilities are simply in build.zig itself :/
yes
I don't have time to develop for a moving target
anyone is welcome to target zig-master if they want, I don't mind having a branch for it
why I don't target zig-master:
- What zig master? Any library that targets zig master is a different master
- It takes time I don't have to develop
- All my other libs are also on latest stable, committing to one lib means updating everything constantly for any breaking change
- Zig master isn't stable, some features can just break and then what do you do start backporting changes to an older master??
Yeah makes total sense
thnx to Castholm's advice, I got CI working again :>
time to start working on porting over SDL3.4 stuff
also closed out a few easy issues and MRs while I was at it
Didn't have much time over the weekend and so didn't get as much progress done as I thought, but there is a WIP branch that has some 3.4 stuff
Thank you so much
Got about halfway done with the 3.4 stuff over the weekend, didn't push it though
I'll make sure to push tonight when I work on it some more
ok so I finished all the 3.4 stuff that is universal for every platform
once I do the applicable platform stuff I'll merge it into main and tag a new version
I also saw SDL image was updated and a pre-release of SDL mixer is available 
So that'll be future work I make issues for
tagged v0.1.7, it has the new SDL 3.4 features :>
I'm going to leave 17 tada's there π
very fitting lol
when zig 0.16.0 or later is released, I want to make zig IO interfaces for SDL's filesystem, storage, net, and async categories
kind of how zig IO reader and writer interfaces exist for io_stream, since SDL3 is my OS layer I prefer the SDL3 functions over std ones but still want compatible std interfaces
I will follow this, super interesting idea π
SDL3 has an AsyncIO interface, maybe that could be used!
ye, we'll see how it goes when I get to play with the new zig release when it comes out
Not sure how well this will work, SDL keeps its Filesystem/Storage APIs rather basic and path based which is not really compatible with the IO system, which requires handle relative access
hmm something to investigate I suppose
can at least use the standard reader/writer interfaces tho
I cant build neither gpu examples nor gpu template on win10
on gpu examples a bunch of spirv failures
i get spirv-opt.exe (depthOutline.frag-opt.spv) transitive failure
on template
build.zig:32:27: error: no field named 'target' in struct 'Build.Graph'
.target = b.graph.target,
^~~~~~
C:\Users\Bananaft.zvm\0.15.2\lib\std\Build.zig:113:19: note: struct declared here
pub const Graph = struct {
^~~~~~
Windows isn't well supported atm, might be some inherent zig issues. The branch is still fairly WIP
looking thru the zig stdlib on codeberg i'm not sure this is platform-specific? it looks like this field just doesn't exist
Is the ttf implementation actually fully working?
Since I do have a 2 issues with the SDF generation of that part I a little unsure what dependency might be the cause here.
I mean it could be the binding, SDL3 TFF, or FreeType.
it should? I mean the example compiles and works for me at least and CI now compiles it too: https://codeberg.org/7Games/zig-sdl3/issues/160
https://codeberg.org/7Games/zig-sdl3/pulls/159 should of been caught for CI.
I haven't used the TTF implementation personally though, just ran the example to verify that works
Yeah so for me it reports that the texture it generates in "alpha" even though it ouputs SDF and I set it to SDF
And there are some heavy artifacts inside the text where overlap happens. So I would at the very least the second should not be because of the bindings.
this looks like your font file has something weird with the contours
I encountered the same bug but with msdfgen
either you fix them externally with a tool like font forge
or use something to rasterize and recreate the sdf again
(which msdfgen turns to skia for)
hm so I downloaded this from
https://fonts.google.com/specimen/Roboto
oh yeah same one I used for testing
Seem like you are spot on. Thanks, this would takes me a while to figure out. But why the hell are the google fonts corrupted
Here is an example of the font which has such curves: https://github.com/MostofaRiad/PicEdit-Android/raw/master/app/src/main/assets/fonts/Eunjin.ttf msdfgen msdf -font Eunjin.ttf 'e' -autof...
π
is it working now?
jip, I took this one here and everything works
https://www.dafont.com/roboto.font
Roboto Font | dafont.com
an angel coming out of no where and knowing the exact issue to some ultra specific problem
I've seen the same issue in Inkscape when converting text to paths for fonts with overlapping strokes. To be clear, these fonts are perfectly valid. It's the software that is broken.
I have been using it for the last month, that's a very cool project. Thank you
Is there any reason why the enable_alpha_to_coverage is commented out? In the SDL docu there is nothing mentioning that it should not work
ah it might of been a 3.4 feature not stated in the changelog
I'll have to try and uncomment it out and see what happens
how is vscode working out for you with zig?
well I really haven't had any problem on the vscode side. Its more that very frequently zls, the zig LSP is not working properly, that's probably the most annoying thing I encountered but really that is not a problem on the vscode side.
pushed a new tag that has more logging functions and by default logs errors with SDL's logging functionality rather than throwing them into the void
Pushed another new tag with various fixes, removes the main callbacks flag (just use the main callbacks subsystem at comptime now), and extension libraries now properly show their docs
Currently watching the exact video that promoted this 
anyerror π
Surprised u can force in Io since to me it's seems like a zig exclusive thing
the anyerror gets converted to a true/false value in the SDL callback code so it really doesn't matter as error info is completely lost
finished the reader/writer stream implementation with tests for it and pushed it to a WIP branch
@nimble stag ik you're probably busy, but do you plan on looking into https://github.com/castholm/SDL/pull/32 in the future?
I realized I kinda left out an equivalent for the macros for assertions so I got a solution to that on a WIP local branch
I swear these issues are hydras, every time I get one done another pops up because I have a great idea to expand the wrapper functionality 
but yeah assertions are now up on the master branch, I don't think there is anyone in particular that wants them but they are good to have lol
and I got yet another idea
the hydra will never end @w@
this sounds quite awesome actually π
Thnx :>
probably not. I've been on a bit of a hiatus but I am back now and planning to get around to taking a closer look at that PR this week, however, I will probably reject it as I don't have any personal interest in iOS/Android and they both look like very time-consuming targets to maintain at a respectable enough level of quality. anything involving developing for apple hardware makes me want to blow my brains out
instead I'd like to try and document recommendations and provide examples for how consumers of my SDL fork should swap it out for alternate methods when building for unsupported targets. e.g. for things like zig-sdl3 or DVUI that let people consume the SDL fork transitively, I'd like to see them employ some kind of set of "bring your own SDL" options like b.options(LazyPath, "sdl_artifact_path", "...") so that people can vendor prebuilt binaries or build through cmake and still make use of your libraries
it's ok, I understand. Thanks for the clarity. In that case I think the approach would be me working with Mozbeel for some possible way to externalize the android/iOS stuff such that it can be used by zig-sdl3. Some setup where zig-sdl3 would be pulling in both your SDL fork and the new lib
That sounds reasonable to me and we will try to work towards that. We already get people wanting to swap in a different version of the library and it would cover that as well.
Rebased the shadercross branch to now have the latest zig-sdl3 changes
Currently in the process of adding a function to sdl3's build system that when called will compile your hlsl or spirv shader to different formats based on the shader format flags you give it
The output will be a zig file you can import to your program that will be a struct that maps format flags as member names to a ShaderCreateInfo struct per each field
So basically you'll be able to just add shaders to the build system and then make them able to be imported for your program, I'll make an extras function to even do the shader loading for you that would just take a GPU device and the import of the shader file you added to the root module by using this shader build function
But if you want/need runtime shaders that'll also be an option, I'll probably make my load shaders function I use in the gpu examples its own thing in the extras
for your program I'm thinking something like this:
const vert_shader = try sdl3.extras.loadShaderEmbedded(gpu_device, @import("my_shader.vert"));
and then in the build script:
sdl3.shaders.compileAndEmbedShader(my_mod, "my_shader.vert", b.path("shaders/my_shader.vert.hlsl"), .hlsl, .{ .spirv = true, .dxil = true });
ofc I'll also have helpers with more flexibility (bc I want to support custom shader pipelines from languages like GLSL or zig ofc)
and I'll also have helpers for dealing with shaders as content and for shaders at runtime
aiming to make it so the GPU templates are fairly straightforward and getting shaders working in your zig program is easy and just works
this is why I did not just add shadercross extension support and call it a day: I want to ensure getting started with SDL_GPU using zig-sdl3 is painless and until that's done I am not satisfied with offloading that effort to the end user
Nice, I can successfully build shadercross as a build tool and run it too
And these are publicly exported from the build script so your build script can just use these functions
Now that I got done, next is:
- Wrapper over shadercross run function that can also get the shader metadata in addition to the output
- Function that maps requested output formats to shader metadata and outputs if given a list of output formats
- Function that takes an output format to metadata and shader map and embeds it into your zig program
- Function that takes an output format to metadata and shader map and outputs it to the install directory
- Extras function to load shader from embedded data
- Extras function to load shader from install directory
- Function to compile a zig shader to spirv
Also I just realized I never need to read the shader metadata during build, I could just embed the file and comptime parse the json
This is so exciting! This will all be huge quality of life improvements since I last played with your shaders βΊοΈ
Ye, I'm excited to have shaders be a lot easier they are way too much manual work rn
How are you building shadercross by the way?
I still need to add dxc support, but while my current method for building for the host is not pushed its basically the same with how I am building it now on the shadercross branch, just with a dummy main.zig file and adding cli.c and the target being the host ofc
Fair fair
I'll clean up the build system to share code between them in the near future
I just realized something... for embedded shaders the shadercross json is available at comptime and has all shader data including input and output variables
this means comptime shader reflection is possible for any shader, not just zig ones
this means if you use say HLSL I could add something to extras that given this comptime data can generate structures for vertices, uniforms, etc.
making it impossible to achieve CPU<->GPU mismatch will be an any shader format thing, not just a zig shader thing
I have personally a system for my engine where I generate zig types from the SPIRV for each shader and store one global shader instance + a zig binding struct. Each binding value is also nullable. So I have a nice system where you get errors for not binding something and can also only and exactly bind the structs / buffers you have in the shader.
I am really happy with that
do you have the code open?
no, I do plan to make it public eventually but I pretty busy on making everything work and changing a lot
fair, I might ask you for some details later when I get into the weeds of implementing such a reflection system
Having this is really a game changer. I come from Unity and doing shader programming there is an absolute nightmare compared to the system I have now. I hand so many issues with binding the correct thing to the correct name, forgetting something, not updating both sides at the same time and so on
I am also doing a lot more. Like ensuring no hidden padding in shader structs, so that you zig structs will 100% match what you have in the shader and all the fields allign. Or custom GPUArray types for readOnly or writeOnly with some generic inner type
this is what I get generated for example:
And the binding also happens automatically with comptime for all the ReadOnlyBuffer / ReadWriteBuffer / ConstBuffers / Textures / ReadWriteTexture
that's neat, and you have a function that can take changes to the binding and then upload them?
also I was thinking of going the type function route rather than the generated zig code route, but the zig code route does have the advantage of being able to reference fields and work better with LSP
yeah, at the moment it binds the entire Binding I think, but I did plan it out so that I can only bind what changed
yeah for me personally not having a clear list of what things a type can exactly do is unacceptable, I mean types can give you so much information about the code almost for free
yeah, I might have to reconsider how I plan to handle metadata
But you also probably cant do all the things I do here since your lib is not nearly as invasive as an engine, so I am not sure how much you can actually do and if the same approach would be correct
But at least I am very happy with my current solution
might just go with the type function anyways bc it would allow me to have code in sdl3.extras instead of being fixed to the build system and you'd still get compiler errors. I don't think the build system should do much more than transform compile time data if the user wants. I also have to support as many use cases as possible which also means splitting vertex attributes across multiple buffers. And specifying the vertex buffers would be awkward at build time rather than within the program you want those buffers?
Hm yes specifically stuff for the vertex input is kinda weird since you could have many different valid inputs for a single shader.
So vertex input is also specified at runtime in my system, though for regular mesh data I have a single shared vertex buffer in my engine.
makes sense
my dev machine going through hell trying to compile this fans are going crazy
I think my craptop would actually just die trying lol
are you kidding me it compiles correctly but every single build it rebuilds
why
at least I can confirm shader embedding works
once I get dxc to behave I'll write an extras function to deal with loading
how it looks so far
as you can see, it automatically generates a zig file with constants depending on the formats exported
so if you have spirv, msl, and json as output formats it'll have those as fields in the generated zig file
I think it keeps recompiling bc the CLI tool its for keeps failing bc I am linking things incorrectly
getting tired of this trial and error though :p
I GOT IT TO COMPILE AND WORK DXC WORKS
...but it still compiles every time
what the fuck
no idea what's going on
I pushed what I have to shadercross, if anyone wants to try and figure it out just zig build run when cd'd into the gpu_template folder and see what I mean
you'll get some JSON output, and then if you zig build run again it'll rebuild dxc...
it's like man it's SO CLOSE but it just keeps rebuilding DXC for no reason and waiting a few minutes per build no matter what is unacceptable...
@celest lion do you know what the cause may be? I'm using your dxc to zig build system port (except it's the last 0.15.2 commit of your branch and I changed python to be python3)
I'm not sure if this is a problem with DXC or how I'm using it
(don't mean to sound angry I'm just had the entirety of DXC compile many many times over and I'm sure you understand how that feels lol)
it's impressive DXC is building so cleanly and working to begin with thanks to your work
Hm I wonder if it is due to the way I handle the lazy dep, I exit kinda late into the build of shadercross maybe if I get the dep before I do any work
Can't test it rn though
Once this works the templates will be:
- GPU embedded shaders template
- GPU content shaders template
- GPU embedded shaders with reflection template
- GPU runtime shader loading template
All will have a vertex shader, fragment shader, and compute kernel in hlsl, glsl, and zig with the option to choose which format is used at build time. It would be intended for you to go with the language you want for the template and delete the others
Well except runtime, that'll just be hlsl and a shadertoy like example program
Uhhh
Are there any errors?
unfortunately putting it up here like I thought would work does not
@celest lion there are no errors, it works perfectly fine. Though the latest commit did have errors since I use zig 0.15.2. And also the python command errored because my debian 13 system only has python3 available on path, not python but I fixed that. It just keeps recompiling DXC for some reason every zig build run
It might not be cached properly, I'll go check
I also did zig build on DXC and can confirm it rebuilds with that every time as well
hm not sure
ik I should of tried doing zig build --summary all to see what was being built
can't do it until tonight though
Assuming I get other stuff done, I plan to at least get the non reflection gpu templates done this weekend at least
Also rework the examples a bit, for the examples do you think I should:
- Embed shaders and use reflection
- Embed shaders but do not use reflection
- Treat shaders as content
ok nvm it seems to just be an issue on how zig-sdl3 is using dxc and not a problem for it
it doesn't rebuild every time for just dxc
β― zig build run --summary new
{ "samplers": 0, "storage_textures": 0, "storage_buffers": 0, "uniform_buffers": 0, "inputs": [{ "name": "in.var.TEXCOORD0", "type": "float3", "location": 0 }, { "name": "in.var.TEXCOORD1", "type": "float4", "location": 1 }], "outputs": [{ "name": "out.var.TEXCOORD0", "type": "float4", "location": 0 }] }
Build Summary: 60/60 steps succeeded
run success
ββ run exe template success 692us MaxRSS:14M
ββ compile exe template Debug native success 651ms MaxRSS:328M
β ββ run exe shadercross (positionColor.vert.spirv) success 8ms MaxRSS:28M
β β ββ compile exe shadercross ReleaseFast native success 231ms MaxRSS:213M
β β ββ compile lib dxcompiler ReleaseFast native success 6s MaxRSS:417M
β β β ββ compile lib libclang ReleaseFast native success 15s MaxRSS:468M
β β β β ββ compile lib clang ReleaseFast native success 1m MaxRSS:473M
β β β β β ββ WriteFile success
β β β β ββ WriteFile (+1 more reused dependencies)
β β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ compile lib dxcvalidator ReleaseFast native success 2s MaxRSS:167M
β β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β β ββ WriteFile (+1 more reused dependencies)
β β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ WriteFile (+1 more reused dependencies)
β β β ββ compile lib libclang ReleaseFast native (+9 more reused dependencies)
β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ compile lib dxcvalidator ReleaseFast native (+9 more reused dependencies)
β β ββ compile lib dxil ReleaseFast native success 274ms MaxRSS:237M
β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ compile lib dxcvalidator ReleaseFast native (+9 more reused dependencies)
β β β ββ compile lib clang ReleaseFast native (+6 more reused dependencies)
β β β ββ compile lib dxcvalidator ReleaseFast native (+9 more reused dependencies)
β β ββ compile lib dxcompiler ReleaseFast native (+26 more reused dependencies)
β β ββ compile lib dxil ReleaseFast native (+9 more reused dependencies)
β ββ run exe shadercross (positionColor.vert.json) success 10ms MaxRSS:28M
β ββ compile exe shadercross ReleaseFast native (+12 more reused dependencies)
ββ install success
ββ install template success
ββ compile exe template Debug native (+17 more reused dependencies)
ok so it does rebuild again actually after I deleted the cache
it for some reason needs to build "N amount of times" before it stops rebuilding
so the problem is with the dxc build
holy shot my friend got it working
the hard part for the GPU templates are now over
Yeah I noticed I had to rebuild twice for it to cqche
No idea why but I'll debug
Oh thank you π
ye np
ye
output files need to be marked as output
otherwise zig build does not know how to cache them
Alright cool
I'll also be spending some time later updating to the latest dxc release upstream
Ye, bit odd to have b.path() to the shader, but still type jn the shader name later
I mean that's the output base name
could be anything you want
I just mean I want to have it automatically go through a directory and compile shaders from it
also I got rid of the allocator since it's comptime stuff
Small problem though, comptime json is not possible so I'll need to have a json to zon for shader reflection stuff :p
We created something somewhat similar to convert hjson to zig source code, maybe you can use it for inspiration βΊοΈ
neat
going to make type safe GPU buffers π
ofc this also means I'll make type safe transfer buffers
hm, oversight
transfer buffers typically have a variety of "segments" that store data, and then later you upload those segments to various buffers
it's more efficient this way
so I'll have to think about how an interface like that would be structured
Yeah I think having a type on transfer buffer directly is not good. I have how some "Uploader" struct which has some function which takes in a type if you want to upload something and then some slice of that type. For me the GPU buffer are also typed and I also have upload functions directly exposed on them for convince.
I also also queue the upload on the cpu and you then have to flush the "Uploader" that avoid starting 100 copy passes and transferbuffer map and unmaps if you upload a bunch of stuff
I also have a directUpload function where you can request a slice you want to write into directly and then afterwards can tell it how much you actually wrote into. That avoids one more copy
wait really? std.json doesn't work at comptime?
is it completely nonfunctional at comptime, is it really slow or does it quickly exhaust the branch quota
Hm maybe what I can do is have segments for the max limits of something and then the ability to push items to transfer onto it kinda like a stack? Not sure. I'll play around with different designs
You can't do any allocations. It's fine if you don't have any pointer types but I want slices soooo
So I added zon as an output to the shadercross build tool but all it actually does is run a json through a custom shadermetadata2zon build tool
see how much memory you need relative to input length on average and use a FixedBufferAllocator?
as in in your code?
yeah i guess the extra build step is more than enough, it's probably faster than parsing JSON at comptime would be even if that was easily doable anyway
it's the json parson code that uses intToPtr with the fixed buffer allocator
Celebrating over 100 issues closed! π The road to 1.0.0 is long but is getting closer a little at a time
Preface: I know you've probably been asked this a lot ... maybe. And also this sort-of escapes into a general discussion. If you could point me to an answer you've made on this, if you've already, I'd appreciate it.
What's the difference between this, and zsdl? Well, bindings and wrappers in general, but yours says in the description 'lightweight wrapper.' Idiomatic Zig code as opposed to using C code inside Zig functions or a hypothetical Zig engine?
This sentence, pretty much, "This library aims to unite the power of SDL3 with general zigisms to feel right at home alongside the zig standard library."
How would one compare Zig code with C-like SDL3 code?
funny enough I've never been asked this before. I believe my bindings are more of an imagining of SDL3 as if SDL3 were designed like the zig standard library. I tried my best to namespace categories and hide as much as the C interop as possible so it feels like SDL3 is in native zig. From what I can tell, zsdl is just making the functions zig friendly and does not do namespacing or have types have self functions (Ex: in my bindings you would be able to get the window border size from a video.Window by calling its .getBorderSize() function). Also ZSDL does not seem to cover the entire API like I do, which I can understand as it's large and it took me months! Zig-sdl3 also has extensive API documentation adapted from the SDL wiki: https://7games.codeberg.page/zig-sdl3/@docs/
I think zig-sdl3 in general aims to be an entire ecosystem with docs, examples, build tools, unit testing, etc. and not just a wrapper
as for comparing zig code with C-like SDL code, that would be more of the lines of just using C SDL3 directly. A lot of people do this, but I don't think there is any reason to do it and to me it misses the point of using zig for some things. Now many functions return booleans instead of errors in C interfacing land, and I highly doubt anyone using the C lib is going to handle errors. If you want to interface with some functions in a zig friendly way you'll end up writing abstractions anyways. Zig-sdl3 gives you many batteries included such as optional integration with zig logging, optional error logging, the ability to use a zig allocator for SDL's allocator, and soon even a way to compile shaders at build time to embed in the binary (functionality exists in the shadercross branch)
Compile shaders at build time = that would be nice!!
yep, shadercross branch has a WIP version of it
you can run the shadercross CLI tool at build time to generate shaders for all the formats you want to support for your app
one of the templates in the repo will have a setup for loading content shaders and another template will have a setup for loading embedded shaders
there will also be a template for loading runtime shaders (for something like a shader toy app where hot reload with shader compilation is needed)
and also for embedded shaders adding extra helper functions for shader reflection and such, lots of ambitous stuff coming
This is going to be one of the coolest features!!
You cannot imagine how many hours I wasted staring on a black screen because some stuff was not wired up correctly π
oh yeah I'm excited for it too. The problem is mostly the slippery slope of scope creep
bc then it's like well if I'm making shader reflection safety, then what's stopping me from adding pipeline and buffer reflection safety
ofc everything would be in extras and not the main gpu namespace
Have you been doing 3d programming? π I am looking at switching back to zig btw for the opengl learning
Yes, I did quite some OpenGL programming during university π
Cool! I just started learning it. Itβs so powerful! π
I do fear moving on to vulcan later though
I have tried using vulkan and it was so painfull. Getting started and setting up everything is probably the hardest. But then i discovered sdl3 gpu and i am never going back again to vulkan :D. Although you basicaly do almost the same stuff its so much less boilerplate + you get more than just vulkan.
Have you worked with opengl? Just curious to where you would place that one in the range of complexity compared to both sdl3 and vulkan π
i have but honestly its kinda hard to compare the two. OpenGL is way more straightforward to use to get simple things done. I havent gone into the complex stuff because i thought that opengl might be to slow or something, which is not entirely true. I would say using vulkan or basicaly any of the knew apis (dx12 metal) is not so straight forward. It feels like making detours to accomplish the same thing as in opengl. But i would also say that once you wrap you head around how the graphics pipeline works you can get quiet comfortable. I havent switched since so i guess using modern apis is not so bad.
Hi.
I just wanted to know If i messed up this or its a bug:
const props = ctx.device.getProperties() catch {
std.log.err("Failed to get device properties", .{});
std.process.exit(1);
};
std.log.info("{s}\n, {s}\n, {s}\n, {s}", .{ props.name.?, props.device_driver_info.?, props.device_driver_name.?, props.device_driver_version.? });
}
and I get this:
thread 5247 panic: access of union field 'pointer' while field 'string' is active
/home/scallyt/dev/z_sdl_gpu/zig-pkg/sdl3-0.1.9-NmT1Q7mEJwCHlAbWKlECsusuVdGDnqkE9SG-2tyWjEa_/src/gpu.zig:1922:124: 0x1360f45 in fromSdl (sdl3.zig)
.name = if (value.get(c.SDL_PROP_GPU_DEVICE_NAME_STRING)) |val| std.mem.span(@as([*c]const u8, @ptrCast(val.pointer.?))) else null,
/home/scallyt/dev/z_sdl_gpu/zig-pkg/sdl3-0.1.9-NmT1Q7mEJwCHlAbWKlECsusuVdGDnqkE9SG-2tyWjEa_/src/gpu.zig:2357:34: 0x134f7c4 in getProperties (sdl3.zig)
return Properties.fromSdl(properties.Group{ .value = try errors.wrapCall(c.SDL_PropertiesID, ret, 0) });
^
/home/scallyt/dev/z_sdl_gpu/src/main.zig:40:43: 0x134fb26 in main (main.zig)
const props = ctx.device.getProperties() catch {
this looks like a bug, pls make an issue on codeberg
heey, trying to compile from an aarch64 mac for x86-64
; zig build -Dtarget=x86_64-macos
error: '--sysroot' is required when building SDL for non-native macOS targets
canβt find this error message on the zig-sdl3βs repo, so i guess itβs from castholmβs (?). anyway, adding sysroot:
; zig build -Dtarget=x86_64-macos --sysroot "$(xcrun --sdk macosx --show-sdk-path)"
install
ββ install blasted_goodbye
ββ compile exe blasted_goodbye Debug x86_64-macos failure
error: error: unable to find framework 'CoreMedia'. searched paths: none
error: unable to find framework 'CoreVideo'. searched paths: none
error: unable to find framework 'Cocoa'. searched paths: none
error: unable to find framework 'UniformTypeIdentifiers'. searched paths: none
error: unable to find framework 'IOKit'. searched paths: none
error: unable to find framework 'ForceFeedback'. searched paths: none
error: unable to find framework 'Carbon'. searched paths: none
error: unable to find framework 'CoreAudio'. searched paths: none
error: unable to find framework 'AudioToolbox'. searched paths: none
error: unable to find framework 'AVFoundation'. searched paths: none
error: unable to find framework 'Foundation'. searched paths: none
error: unable to find framework 'GameController'. searched paths: none
error: unable to find framework 'Metal'. searched paths: none
error: unable to find framework 'QuartzCore'. searched paths: none
error: unable to find framework 'CoreHaptics'. searched paths: none
β¦and frameworks are not found. can anyone reproduce this?
all good π
Yea I had that, needed to downgrade xcode by one minor version, there was an issue on zig codeberg with a fix in main.
i also had that, but here SDL couldnβt find the path at all for x86_64-macos, while aarch64 was fine. I hade to give them like
if (target.result.os.tag == .macos) {
system_include_path = pathjoinfromsysroot;
system_framework_path = β¦;
library_path = β¦;
}
---8<---
my_very_own_mod.addSystemIncludePath(system_include_path);
my_very_own_mod.addSystemFrameworkPath(system_framework_path);
my_very_own_mod.addLibraryPath(library_path);
(on my phone sorry)
Oh sorry, I read that quickly and didn't piece it all, this is good to know!
doesnβt work with SDL3_image and SDL3_ttf, though. same error π€
finally fixed CI, it was some weird thing of a job stuck in limbo causing the pipelines to fail
well not fail but also get stuck in limbo

if anyone wants to help with this getting ported to zig 016.0, what you can do is checkout the 196-zig-16 branch
if you run zig build test you'll see a TLS error that I'm having trouble solving that looks like it might be a bug with zig...
I'll probably have to get around it by hosting my own download of freetype
however if there is a way to not (or maybe just ignore TLS) let me know
I just tried, didn't get the TLS error though. I did get a UnknownHostName, had to run git fetch manually for castholm's SDL. Then I had a bunch of TTF errors (eg error: undefined symbol: _TTF_DrawRendererText) had to update the build.zig to pass the deps to setupTest explicitly and modify the individual ext builds.
pub fn setupTest(
b: *std.Build,
cfg: Config,
options: *std.Build.Step.Options,
c_module: *std.Build.Module,
sdl_dep_lib: *std.Build.Step.Compile,
image_lib: ?*std.Build.Step.Compile,
net_lib: ?*std.Build.Step.Compile,
ttf_lib: ?*std.Build.Step.Compile,
) *std.Build.Step.Compile {
But now these tests pass:
../zig-0.16.0/zig build test -Dext_image=true -Dext_ttf=true
And quick allocator change allowed the ttf example to build too!
../zig-0.16.0/zig build run -Dext_image=true -Dext_ttf=true -Dexample=ttf
Oh, i'm on mac, that's probably why I never got the TLS issue
@bleak bone huh interesting, definitely has to be a zig bug of some sort...
I'm not sure what I should do
What if you point the cert to use your system's, like SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt zig build test (or wherever the distro stores certs, i don't have a linux machine so I can't test), but that's not a nice solution for downstream users...
Or maybe just manually fetch the deps individually as well? Does zig fetch work directly? zig fetch 'git+https://github.com/allyourcodebase/freetype#884fd2235e6ae1ec4306eda30b3259f20930ed2e'
That's a reasonable fix for downstream until a real fix comes, I think
I'll have to put it in the FAQ
but no one reads the FAQ
maybe I just have something in the setup instructions that's like something not working? See the FAQ
bc yeah not looking forward to getting at least 3 issues opened about this
Yeah that's fair, and definitely going to happen. Maybe an issues template check mark "I have read the FAQ before opening this issue" haha
oh perfect, I didn't know that's a thing
I got zig 0.16.0 working locally, it's mostly CI now until I can merge it
YEAHHHHHHHHHHHHHH
once I fix the feel of the now-springs in Princeton's GameView I'll switch
nice
also man it sucks not having my dev machine available atm, CI has to run on my laptop and it's so painful
half the jobs keep failing bc networking on my laptop sucks
funnily I can't rn because of a transitive dependency of dvui's lmao
tree-sitter-zig, fsr it's... losing its fingerprint? idk
I ran into that and hopefully pushed a fix to the zig16-dev branch
what was it?
I forked tree-sitter-zig and added a fingerprint
I can't wait to add a zig IO backend that uses SDL calls when I get a chance
I realized that when SDL3 controls the entry point you no longer have the juicy main init features :<
time to add sdl3.extras.juice
Any plans for SDL_mixer or are you still busy with other stuff?
it is planned, but might be a while before I do it
so if anyone wants to do that atm go ahead
I need some core libs for my gamedev done so I'm kinda trying to do a wide spread
thanks to Chinmay Dalal, you can now use the system's SDL3!
due to rising complexity of getting GPU added completely, I decided it will be best to add GPU support in parts
first, I will add shadercross by itself
then, I will add the GPU examples
I will make separate issues for a GPU template with shaders loaded as content, a template with shaders loaded as rodata, a template for using shadercross at runtime, and a template for using shader reflection and ofc all the reflection details that comes with it
I realized that shadercross in itself has been done basically forever but people can't really use it since I wanted to do everything at once which has proven to be too ambitious
for any GPU examples that are too involved to add atm I'll make issues for each one separately
this way what's working for GPU stuff is out and I will no longer be in just one more feature before I merge everything mode
You definitely want to do some bits of this differently to how I did it, but if it helps, I did eventually get a full sdl_gpu example running through zig build, with the possibility to compile shadercross into the application or to install it as a separate executable. Feel free to copy and rewrite whatever you need from here: https://github.com/swan-www/zig_sdl3/blob/main/build.zig
thnx, but I already got it covered
shadercross is merged
have fun
there's also a CLI tool included too that you can use to build shaders with and them embed them or use them as content
and now there's 4 more issues lol
This weekend I'll try and get some of the gpu examples up
And make issues for what I don't get working fully
This is awesome π₯³
Ye, want to finally just release what I have working lol
working on juicy main for SDL3 callbacks
some WIP adjusted test code
unfortunately you will just kinda be stuck with this init parameter, however idk when you wouldn't want it
I'll probably put the args in the init parameter too
it's working well so far
it's done, got it working through all the tests and added it to the template
it's a bit non-optional unfortunately but I don't think it's too controversial? Having the argument be optional appeared to be more trouble than it's worth
released zig-sdl3 v0.2.1
now I can start adding the GPU examples formally tomorrow (well technically later today)
wanted to get juice out of the way bc it would be a pain to fix up later lol
oh yeah app state is also different
I made it so you no longer have to allocate it yourself
you just fill it in while in the init function and if the init function errors then the app state will end up null in quit
not possible for app state to be null in iterate or event since to get there init would have succeeded, so app state will be valid assuming you actually filled it in during init
but I might make it so that you return app state during init instead of filling it in
also reorganized the extras namespace now loggers and error handlers have their own namespaces rather than polluting the main extras one
and yeah the sdl3 init parameters are structured similarly to juicy main's, I borrowed the same logic
your gpa in debug mode by default has leak detection
there we go, now you get actually good error messages when any of your callback signatures is incorrect
75%...
in the WIP gpu-examples branch, there are now helpful functions to work with shaders :>
I don't think I'll do all the examples before merging, just some that do texture sampling, compute shaders, and maybe more
I kinda want to prioritize getting templates for GPU stuff when I know things are doing well
This is the kind of stuff I am really excited about!!
Also so much looking forward to the spriv backend, will be a gamechanger for code reuse when we can use zig for GPUs βΊοΈ
Ye definitely, spirv types as a builtin was just merged so texture sampling will be a lot easier for 0.17.0
comptime vertex buffer type generation
the "other buffers" is designed so that you can specify data to go into other vertex buffersx
for example, you could do const other_buffers = &.{ &.{ .name = "tex_coord" } }; to have the texture coordinates be at buffer 1
but this way, kinda impossible for your vertex buffers and vertex shader to not be in sync
being able to create vertex buffer info and attribute info from metadata coming soonish
btw, I got this working for GLSL, HLSL, and zig shaders so it's not just zig reflection trickery
I just realized I can make it return a tuple of types and not an array, that would be much nicer
It's kinda lame you can't have constants with comptime types though? Idk it complains if I store graphics shader Metadata in a global constant
some examples on zig-sdl3 master
tomorrow I will start building out the templates
this also gets zig compute kernels working too
so yeah the zig-sdl3 build system now has some very useful helper functions
but it's good to have some stuff merged in the main branch
even if everything isn't quite complete
merged a template for embedding shaders into the executable: https://codeberg.org/7Games/zig-sdl3/src/branch/master/templates/gpu_embedded
I decided I'll just keep incrementally adding these templates and examples and not tag a new zig-sdl3 version until I'm sufficiently satisfied
I need to make READMEs though
templates and examples will need the master version of zig-sdl3 atm
And dxil soon to be deprecated
Huh
Being almost two years now and still no release of that but it is the intention
this library has come a long way since i last engaged with it lol
also the one example that opens a url in the browser still opens the old github repo lol
oh lol I need to fix that
also i think zig master removes @cImport/@cInclude so if that's the case i think that is going to break some things when zig 0.17 rolls around lol
hm not sure what to do about that, bc how I use it basically declares the main callbacks inline...
my main goals for this month are to finish making the GPU templates, refactor the build script to be nicer and not use IO (and make extensions for testing work properly), and then finish up the mixer support peartree did
mhmhm
better late on making the GPU templates than never :p I know how annoying setting up building shaders is so this should hopefully help a lot of people
hell yeah
(and yeah sdl shadercross is a lot more of a pain to set up than sokol shdc lol)
yeahhh it was kinda annoying to get working
but now you have some helpful wrapper functions for getting a CLI of shadercross to run and a helper function for running it for either one or outputting multiple formats
it's a bit weird since you need to get zig-sdl3's builder, but in practice it really isn't hard if you know what to do like the template shows you
mhmhm
i'm at real risk of getting back into game dev so these improvements are nice
bc zig-sdl seems to somehow be the most practical option for me
ooo nice, do it
issue is i have a full time job now lol
turns out that eats up a Lot of time and energy
also hm
is sdl-image supported by the zig bindings yet?
I also have some other game dev related libs that are either released or coming out sometime this year (some need new zig version updates though):
- ZBuf - Easy (de)serialization for binary or text for most structs
- ResourceHandles - A way to either load resources if not loaded already or use the existing one (in the middle of a big rework to support async)
- EasyFSM - Easier way to declare FSMs using comptime magic
- ZMS - Zig Math Shell, provides vector and matrix math for any dimensions for any underlying number implementation (floats, fixed-point, etc). Also includes binary angles and eval functions where you can use a math-like DSL
- BBSP - Bitwise-Binary Space Partitions, Useful for making N dimensional BSPs (quadtrees, octrees, etc) where search is accelerated by taking advantage of bitwise operations (making this friendly for systems that don't have floats)
- LibGravity - Provides various shapes for gravity simulations (like Mario Galaxy)
- Lucid - 3d graphics middleware for 3ds/Wii like graphics
- Collision Lib - 2d and 3d collision detection and resolution using sphere-prism, ray-prism, and point-prism
- ProtoGame - Uses comptime magic and ECS to provide automatic scene de(serialization) and an editor that updates with your game as you program it without breaking forwards or backwards compatibility
yeahhh ik how that is
I've been using what little free time I have supporting zig-sdl3 and these libs mostly lol
sdl-image is supported but not fully
I still need to get support for formats like JpegXL
mhmhm
i'm just wondering if it's easy to load a png or if i get to have Fun implementing my own QOI loader
oh damn, nice
nifty
though I will write kra image support for when I do actual gamedev
hella
not to ship ofc but for dev
honestly png and qoi are the only formats i really care about for game dev and i mostly care about qoi bc i think it's Cool
it's literally a zip file with a preview PNG along with actual project files (the KRA format)
idk much about QOI, but I'll probably ship JXL
ohhh I see
it's like PNG but fast
that's good to have
its main feature of note is being Extremely Easy to write encoders and decoders for
that is good
I still need to figure out how I want to handle content
ofc I want the dev-friendly formats during dev, but performance formats for actual builds
like ik for 3d textures I'll probably be using KRA for dev, but LZ compressed KTX for builds? Idk
see any games i develop will probably be simple enough that image decoding is never going to be the bottleneck
bigger bottleneck for the forever project is probably going to be "local rat decides to roll its own physics code and fails to optimize it right"
yeahhh true lol
though I tried loading PNGs on the 3ds and it took like 5-10 seconds to load everything for the demo scene :|
oof
new GPU template
in case you wanted to store shaders in a content folder instead of embedding them into the executable
hey nice work on this stuff. I was wondering if you'd looked into SDL_ShaderCross at all? seems like a pretty nice extension to SDL for cross-compiling shaders from X -> Y shader language
yeah?
I mean not only does the extension exist but you can run it as a CLI tool as part of the SDL3 build system like in the templates
Is there support for all major targets? Ios, mac, android, Linux, win?
Linux and Windows exists and is tested through CI. Web worked last time I checked but might be broken now, still trying to add it to CI. Mac should work but is unsupported. IOS is unsupported and will never be. Android is planned but currently unsupported
if someone wants to add more platform support go ahead, but the only platform lacking support I will care to dev for is Android
Oh dang I must have missed that, Iβll check it out, thanks
whatever the case, build failed
yeah dxc is based off llvm
horrifying
i feel like there has Got to be a better way
i know sokol-zig doesn't have this problem with sokol-shdc but i think it might be downloading prebuilt shdc binaries so shrug
Yeah it builds shadercross from source, not the best unfortunately but it works. In order for zig shaders to work since they are experimental you need to have spirv-tools installed (I need to specify that in the Readme actually). You need glslang installed for hlsl or glsl shaders, there's a flag to control the shader format
Unfortunately zig makes it impossible to build shaders for the logical addressing mode atm due to some design decisions so I hack it away using optimizer trickery
This should be fixed soon in master though
mhmhm
Actually since I don't use hlsl to spirv for those templates for shadercross I think I can disable dxc
That should make things a lot faster
Hlsl to spirv doesn't produce the right names for reflection in shadercross so that's why I use glslang for that
oh nvm
I need to compile to DXIL which yeah needs DXC support
DXC isn't just used for compiling HLSL in shadercross I forgot
perhaps related reading: https://devlog.hexops.org/2024/building-the-directx-shader-compiler-better-than-microsoft/
This is a story about the messy state of Microsoftβs DirectX shader compiler, and trying to wrangle it into a nicer experience for game developers. In some respects, building the DXC compiler better than how Microsoft does.
oo thnx
build system refactor done
now you don't need to specify any extension options to build tests, examples, or docs
...and also the build system will no longer build the examples whenever you use zig-sdl3
yea i think it is downloading prebuilt bins at some point but it works super smoothly
(except that the module route breaks the language server a bit lol)
Zig bindings for the sokol headers (https://github.com/floooh/sokol) - floooh/sokol-zig
might be worth looking into
at least once you compile shadercross for your template once you shouldn't need to do it again unless you delete the cache
true
Mixer support is going well so far, though I forgot how tedious of a process wrapping these is lol
I also found out that a lot of things weren't tested bc of refDecls instead of the recursive function. I made my own recursive function bc I need it
I wish they didn't remove it
mixer not coming today unfortunately bc I forgot how long these things can take, but it will be coming soon and there is a WIP branch available at least
I think Mixer is about halfway done
I predict it'll be ready sometime on Wednesday
after mixer is completed, I'll revisit image
after that I will touch up net than ttf, and I believe that'll be it for extension libs
Looks like there's also a native MIDI playback extension lib but idk how useful that is to people? Wouldn't hurt but idk don't see the point as sdl3 mixer can play MIDI just not os level
How I am supposed to pass arguments from the process to enterAppMainCallbacks?
pub fn main(main_init: std.process.Init) !u8 {
sdl3.main_funcs.setMainReady();
const arena = main_init.arena.allocator();
const app_args_zig = try main_init.minimal.args.toSlice(main_init.arena.allocator());
const app_args_sdl = try arena.alloc([*:0]u8, app_args_zig.len);
for (app_args_zig, 0..) |arg, index| {
app_args_sdl[index] = try arena.dupeZ(u8, arg);
}
return sdl3.main_funcs.enterAppMainCallbacks(&app_args_sdl, AppState, init, iterate, event, quit);
}
This didn't work of course, but I would like to know how to approach this
if you are using the latest master of zig-sdl3, you don't need to specify the init yourself. See the callbacks or main callbacks example here: https://codeberg.org/7Games/zig-sdl3/src/branch/master/examples. SDL3 has its own version of juicy main passed to your app's init function
yeah but it does not have the args passed to the executable
it should? Unless I programmed that wrong
it uses the args parameter you pass to enterAppMainCallbacks
ah and you would like it to take in zig args, yes that makes sense
I would recommend just using the callbacks method instead of enterAppMainCallbacks
you shouldn't have to wrap the arguments yourself that way
I was migrating a app from 0.15 to 0.16 and I was already using enterAppMainCallbacks, having the arguments passed from the executable is a minimum expectation IMO
is there any reason you need zig's main to run? If you comptime import sdl3.main_callbacks it will call your init, iterate, event, and quit functions and take over main for you and give you args without you having to forward them
converting zig args to sdl args is nontrivial and I don't want to hide the conversion under the hood
it's best to just have SDL export its main instead
the main problem is args on Windows would be WTF-16 encoded
and SDL wants ASCII (or is it UTF-8? Idk)
so I get it correctly:
comptime {
_ = sdl3.main-callbacks
}
to replace my main?
init_data has your gpa, arena, args, etc.
it does not have environment though
SDL has its own ways for dealing with environment vars
and unfortunately I don't know how to really recreate that
I just need the args so it should be good!
nice
thanks, will look to migrate this code tomorrow morning
the mixer extension has been added and version 0.2.2 has been tagged!
https://ziglang.org/devlog/2026/#2026-06-26
spir-v backend progress
yep, I've been helping find bugs for it
(unfortunately in the current master shaders are completely broken)
(we kinda need vector externs...)
oof
yeahhhh not the best situation..
at this point I want to 0.17.0 release to not come anytime soon so that there's enough time to get SPIR-V well supported :p
I'd like to have some of my texture sampling additions in
I've been working on std.spirv.imageSampleImplicitLod
(also vector externs in zig master work again for anyone interested in that)
this wrapper is awesome definitely the best one out of all that I've seen
thnx, glad you like it :>
