51 Commits
Author SHA1 Message Date
adrien e03cb3f285 Added back VRAM budget check for GpuBuffer, must be forgotten when refactoring it 2026-05-22 00:17:54 +02:00
adrien 14def5d555 Updated example in README 2026-05-21 23:38:22 +02:00
adrien e61c5f775d Prevent building example when use as module 2026-05-21 23:33:54 +02:00
AdrienBouvais d503ce7dea Added optional label in definitions and added logs when alloc, free and device info 2026-05-21 10:26:20 +02:00
adrien 69f9cad2c1 Updated README ref 2026-05-20 15:45:02 +02:00
adrien c5d7fd927d Updated README and build.zon version 2026-05-20 14:04:25 +02:00
adrien 17977cc718 Merge branch 'render' 2026-05-20 13:47:43 +02:00
adrien 5104d61ef6 Synthax for compute example 2026-05-20 13:41:04 +02:00
adrien 7d5331aed7 Circle example use device allocator directly 2026-05-20 13:39:20 +02:00
adrien 7d425e4061 Changed how Allocator work to be more Zig like
Now GpuArena doesn't do everything.

- Created GpuDeviceAllocator that allocate to the device
- GpuArena become GpuArenaAllocator and use a child_allocator like
std.heap.ArenaAllocator
2026-05-20 13:32:37 +02:00
adrien a06b040a29 Render and COmpute Pipelines now use a gloc and is tracked by Arena 2026-05-20 12:29:41 +02:00
adrien af210e2fb2 Working self contained rendering (simple circle) 2026-05-20 11:46:06 +02:00
adrien 545c4b98e9 Create a GpuTextureView 2026-05-20 10:56:35 +02:00
adrien 45c0f3180e Created a GpuTextureDef 2026-05-20 09:55:34 +02:00
adrien fc57bee3af Created GpuPrimitiveTolopogy to replace c.WGPUPrimitiveTopology 2026-05-20 09:37:46 +02:00
adrien bcb1b1e98b GpuRender now take a GpuTextureFormat and not a c.WGPUTextureFormat 2026-05-20 09:24:37 +02:00
adrien 32f5d2b828 Added GpuTexture tied to arena like buffer 2026-05-20 09:14:54 +02:00
adrien ad3fcf2592 Basic working circle render pipeline 2026-05-19 21:58:14 +02:00
adrien 83ef8bcd12 Renamed ProcessDef to COmputeDef 2026-05-19 21:35:52 +02:00
adrien e467539f6e Renamed GpuProcess to GpuCompute 2026-05-19 21:15:31 +02:00
AdrienBouvais fb2f454c1c Removed unused import 2026-05-19 09:18:26 +02:00
AdrienBouvais 7e1bc387ca Synthax 2026-05-19 09:15:32 +02:00
AdrienBouvais 09e62cf667 Update README and comment for new GpuProcess 2026-05-19 08:00:42 +02:00
AdrienBouvais 62b5224e6e Changed GpuProcess to use a definition
Now GpuProcess isnt limited to 2 in, 1 out but to anything.
2026-05-19 07:54:16 +02:00
AdrienBouvais 44d26feba5 . 2026-05-19 07:41:50 +02:00
AdrienBouvais bfac170936 Added better dependencies info in README 2026-05-19 07:35:08 +02:00
adrien 523a9b69ac .Synthax 2026-05-18 23:21:26 +02:00
adrien 571a9db71f Started to add a mnist Deep Learning example
No reason why, that for the love of the game
2026-05-18 23:11:58 +02:00
adrien 6ec53bb909 Moved add and bench into an examples directory so src is just the library 2026-05-18 22:57:13 +02:00
adrien 6b933465b0 Better example 2026-05-18 17:00:44 +02:00
adrien 3d9cb4df04 Removed TensorInfo from example shader 2026-05-18 16:45:55 +02:00
adrien c62bead6e9 Better example (no Vec) 2026-05-18 16:38:30 +02:00
adrien 9dbd668de9 . 2026-05-18 16:33:26 +02:00
adrien 50bf436fa5 Update README 2026-05-18 16:33:07 +02:00
adrien df4eb36bc8 Added README 2026-05-18 16:30:27 +02:00
adrien c7afe28cc6 GpuBuffer align with size 4 as required by WebGPU
Otherwise a GpuBuffer of a single f16 is too small (only 2) and a eneven
f16 wouldn't work either
2026-05-18 16:24:43 +02:00
adrien d9cb4c4672 Better example comments 2026-05-18 16:18:58 +02:00
adrien 3a09e11f54 Deleted Vec.zig 2026-05-18 16:05:50 +02:00
adrien e608681ce1 Added preference power in DeviceCOnf 2026-05-18 16:05:42 +02:00
adrien d2b0735540 Moved all f32 out of GpuXxxx to all be in Vec 2026-05-18 15:35:38 +02:00
adrien 8e137c8f33 Vec no longer need import c 2026-05-18 15:28:28 +02:00
adrien 97d5f9001f Removed GpuPipeline for a GpuProcess 2026-05-18 15:28:02 +02:00
adrien d5e7f60926 Moved read stuff to GpuBuffer directly 2026-05-18 14:27:11 +02:00
adrien 2673aef0fd Moved c.gpuQueuWriteBuffer to GpuBuffer 2026-05-18 14:16:01 +02:00
adrien 7ce6b9cd1d Better example 2026-05-18 14:11:17 +02:00
adrien f5daf66784 Changed GpuAllocator to be like std.mem.Allocator
Now it is 2 ptr and I created a GpuArena. Point is to be like Zig, a
const allocator and a var arena that track everything.
2026-05-18 14:07:28 +02:00
adrien c3166e552b GpuBuffer init now take a EnumSet of BufferUsage and not a c.WGPUBufferUsage 2026-05-18 10:49:11 +02:00
adrien d42c521a96 Added f16 capability 2026-05-18 10:12:36 +02:00
adrien 0fc5f5dbb8 GpuBuffer can be for any float and init now 2026-05-18 09:31:58 +02:00
adrien 545e67d72f Added a example.zig 2026-05-18 00:19:37 +02:00
adrien 0fcb9ee351 Synthax improv + GpuDeviceConfig 2026-05-18 00:10:09 +02:00
22 changed files with 1855 additions and 419 deletions
+1
View File
@@ -1,2 +1,3 @@
.zig-cache .zig-cache
zig-out zig-out
examples/mnist
+238
View File
@@ -0,0 +1,238 @@
# Minimal Zig WebGPU Compute & Render Library
This is a minimal, self-contained Zig library designed to simplify running compute shaders and rendering pipelines using WebGPU. It abstracts away much of the boilerplate required for GPU device initialization, memory management, bind groups, and pipeline execution.
## Core Modules
The library exports the following primary components:
* **`GpuDevice`**: Initializes the WebGPU instance, adapter, device, and queue. It is configured to prioritize high performance and automatically requests the `ShaderF16` feature if the adapter supports it. It provides the base `GpuAllocator` for raw VRAM allocations.
* **`GpuArenaAllocator`**: A memory management layer that wraps a base allocator to track and automatically destroy all allocated WebGPU buffers, textures, views, and pipelines when deinitialized.
* **`GpuBuffer`**: Wraps native WebGPU buffers. It provides a `.load()` method for CPU-to-GPU data transfers and a `.read()` method that utilizes a staging buffer to map GPU data back to the CPU.
* **`GpuCompute`**: Compiles WGSL source code into a compute pipeline and dispatches compute workgroups.
* **`GpuRender` / `GpuTexture` / `GpuTextureView`**: Components used to initialize render pipelines, set up render attachments (textures), and bind render targets for offscreen drawing.
---
## Example 1: Compute Pipeline
Below is a complete example demonstrating how to initialize the GPU via the device allocator, manage VRAM using a GPU Arena, run a compute shader, and read the results back to the CPU:
```zig
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Create a GPU Arena to manage VRAM
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load the WGSL compute pipeline
const add_cp = try GpuCompute.init(
gloc,
@embedFile("shaders/add.wgsl"),
.{
.label = "add",
.bindings = &.{
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
},
},
);
// 4. Setup CPU data
const len: usize = 16;
const data_a = try allocator.alloc(f16, len);
defer allocator.free(data_a);
const data_b = try allocator.alloc(f16, len);
defer allocator.free(data_b);
for (0..len) |i| {
data_a[i] = @floatFromInt(i);
data_b[i] = @floatFromInt(len - 1 - i);
}
// 5. Initialize raw GPU Buffers
const byte_size = len * @sizeOf(f16);
const buf_a = try GpuBuffer.init(gloc, .{ .label = "a", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_b = try GpuBuffer.init(gloc, .{ .label = "b", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_out = try GpuBuffer.init(gloc, .{ .label = "out", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
// Note: Buffers are safely tied to the GpuArenaAllocator which will automatically
// release them at the end. You can also manually call buf_x.deinit() if desired.
// This will also release pipelines, textures, ect. Everything using a GpuAllocator to init.
// 6. Transfer data from CPU slices to GPU Buffers
try buf_a.load(f16, data_a);
try buf_b.load(f16, data_b);
// 7. Dispatch the Compute
try add_cp.run(gloc, .{ buf_a, buf_b, buf_out });
// 8. Map and copy the resulting buffer back to the CPU
const out = try buf_out.read(allocator, f16);
defer allocator.free(out);
std.debug.print("Result: {any}\n", .{out});
}
```
---
## Example 2: Rendering Pipeline (Offscreen to PPM Image)
This example demonstrates how to initialize a rendering pipeline, allocate an output texture target, draw primitives via WebGPU,
and pull the frame pixels back to the CPU to write a standard image file:
```zig
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer;
const GpuRender = gpu.GpuRender;
const GpuTexture = gpu.GpuTexture;
const GpuTextureView = gpu.GpuTextureView;
const width: u32 = 512;
const height: u32 = 512;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Init VRAM Arena
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load Render Pipeline
const circle_rp = try GpuRender.init(
gloc,
@embedFile("shaders/circle.wgsl"),
.{ .bindings = &.{}, .texture_format = .RGBA8Unorm, .topology = .TriangleStrip },
);
defer circle_rp.deinit();
// 4. Create VRAM texture to render into
const texture = try GpuTexture.init(gloc, .{
.format = .RGBA8Unorm,
.size = .{ .width = width, .height = height, .depthOrArrayLayers = 1 },
.usage = .initMany(&.{ .RenderAttachment, .CopySrc }),
});
defer texture.deinit();
// 5. Create a view from texture
const view = try GpuTextureView.init(gloc, texture, .{});
defer view.deinit();
// 6. Run the rendering pipeline
try circle_rp.draw(gloc, view, 4, .{});
// 7. Load Texture into GpuBuffer
const cpu_staging_cpu = try texture.buffCopy(gloc);
defer cpu_staging_cpu.deinit();
// 8. Read GpuBuffer to CPU
// This need to be free manually because CPU memory
const pixels = try cpu_staging_cpu.read(allocator, u8);
defer allocator.free(pixels);
// 9. Write a simple ppm image
try savePpm(init.io, "circle.ppm", width, height, pixels);
}
fn savePpm(io: std.Io, filename: []const u8, w: u32, h: u32, rgba_pixels: []const u8) !void {
const file = try std.Io.Dir.cwd().createFile(io, filename, .{});
defer file.close(io);
var buf: [255]u8 = undefined;
var writer = file.writer(io, &buf);
// PPM Header: P6 format means raw RGB bytes
try writer.interface.print("P6\n{d} {d}\n255\n", .{ w, h });
// Strip Alpha channel when writing out to standard RGB PPM format
var i: usize = 0;
while (i < rgba_pixels.len) : (i += 4) {
try writer.interface.writeAll(rgba_pixels[i .. i + 3]);
}
}
```
---
## Running Examples Locally
If you have cloned the repository, you can run the included examples directly using the Zig build system:
```bash
# Run the rendering example (generates circle.ppm)
zig build circle
# Run the compute example
zig build compute
# Run the compute benchmark
zig build bench_cp
```
---
## Dependencies
* **`wgpu.h`**: The library relies on WebGPU C API headers to bind to the native system graphics.
## System Requirements
Because this library binds to native system graphics APIs via `wgpu-native`, you must ensure the appropriate development headers and libraries are available on your system before compiling.
### Linux (Vulkan)
* **Ubuntu / Debian:** `sudo apt update && sudo apt install libvulkan-dev mesa-vulkan-drivers`
* **Fedora / RHEL:** `sudo dnf install vulkan-devel mesa-vulkan-drivers`
* **Arch Linux:** `sudo pacman -S vulkan-headers vulkan-icd-loader`
### macOS (Metal)
No extra installation required. Automatically links against `Metal`, `QuartzCore`, `Foundation`, and `CoreGraphics`.
### Windows (DirectX 12)
No extra installation required. Automatically links against `d3d12`, `dxgi`, and `user32`. Ensure you have MSVC build tools installed.
---
## Adding to your project
Add it to your `build.zig.zon`:
```bash
zig fetch --save git+[https://git.bouvais.lu/adrien/zig-wgpu#ref=0.2.0](https://git.bouvais.lu/adrien/zig-wgpu)
```
Then, expose it in your `build.zig`:
```zig
const zig_wgpu = b.dependency("zig-wgpu", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("gpu", zig_wgpu.module("zig-wgpu"));
```
+41 -41
View File
@@ -1,61 +1,61 @@
// build.zig
// zig build run
//
// Expects wgpu-native pre-built in libs/wgpu-native/:
// include/wgpu.h
// lib/libwgpu_native.a (or .so / .dylib / .dll)
//
// Download release: https://github.com/gfx-rs/wgpu-native/releases
// Pick the archive matching your OS/arch, e.g.:
// wgpu-linux-x86_64-release.zip → libwgpu_native.a + wgpu.h
// wgpu-macos-aarch64-release.zip
// wgpu-windows-x86_64-msvc-release.zip
const std = @import("std"); const std = @import("std");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
// 1. Define the module so other projects can import it const mod = b.addModule("zig-wgpu", .{
_ = b.addModule("zig-wgpu", .{
.root_source_file = b.path("src/lib.zig"), .root_source_file = b.path("src/lib.zig"),
});
const exe = b.addExecutable(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/bench.zig"),
.link_libc = true,
.target = target, .target = target,
.optimize = optimize,
}),
.name = "gpu_matrix_add",
}); });
// wgpu-native headers + pre-built static library mod.addIncludePath(b.path("libs/wgpu-native/include"));
exe.root_module.addIncludePath(b.path("libs/wgpu-native/include")); mod.addLibraryPath(b.path("libs/wgpu-native/lib"));
exe.root_module.addLibraryPath(b.path("libs/wgpu-native/lib")); mod.addObjectFile(b.path("libs/wgpu-native/lib/libwgpu_native.a"));
exe.root_module.addObjectFile(b.path("libs/wgpu-native/lib/libwgpu_native.a"));
// Platform-specific system frameworks needed by wgpu-native // Platform-specific system frameworks needed by wgpu-native
const t = target.result; const t = target.result;
if (t.os.tag == .macos) { if (t.os.tag == .macos) {
exe.root_module.linkFramework("Metal", .{}); mod.linkFramework("Metal", .{});
exe.root_module.linkFramework("QuartzCore", .{}); mod.linkFramework("QuartzCore", .{});
exe.root_module.linkFramework("Foundation", .{}); mod.linkFramework("Foundation", .{});
exe.root_module.linkFramework("CoreGraphics", .{}); mod.linkFramework("CoreGraphics", .{});
} else if (t.os.tag == .windows) { } else if (t.os.tag == .windows) {
exe.root_module.linkSystemLibrary("d3d12", .{}); mod.linkSystemLibrary("d3d12", .{});
exe.root_module.linkSystemLibrary("dxgi", .{}); mod.linkSystemLibrary("dxgi", .{});
exe.root_module.linkSystemLibrary("user32", .{}); mod.linkSystemLibrary("user32", .{});
} else { } else {
exe.root_module.linkSystemLibrary("vulkan", .{}); mod.linkSystemLibrary("vulkan", .{});
exe.root_module.linkSystemLibrary("gcc_s", .{}); mod.linkSystemLibrary("gcc_s", .{});
} }
if (b.pkg_hash.len == 0) {
var threaded: std.Io.Threaded = .init_single_threaded;
const io = threaded.io();
var buf: [1024]u8 = undefined;
const exemples = try std.Io.Dir.cwd().openDir(io, "examples", .{ .access_sub_paths = false, .iterate = true });
var iter = exemples.iterate();
while (try iter.next(io)) |entry| {
if (entry.kind != .file) continue;
if (!std.mem.eql(u8, entry.name[entry.name.len - 4 ..], ".zig")) continue;
const exe = b.addExecutable(.{
.name = entry.name[0 .. entry.name.len - 4],
.root_module = b.createModule(.{
.root_source_file = b.path(try std.fmt.bufPrint(&buf, "examples/{s}", .{entry.name})),
.target = target,
.optimize = optimize,
.imports = &.{},
}),
});
exe.root_module.addImport("gpu", mod);
b.installArtifact(exe); b.installArtifact(exe);
const run = b.addRunArtifact(exe); const run_step = b.step(entry.name[0 .. entry.name.len - 4], try std.fmt.bufPrint(&buf, "Run {s} demo", .{entry.name}));
run.step.dependOn(b.getInstallStep()); const run_cmd = b.addRunArtifact(exe);
b.step("bench", "Benchmark a simple add vector").dependOn(&run.step); run_step.dependOn(&run_cmd.step);
}
}
} }
+3 -33
View File
@@ -1,43 +1,13 @@
.{ .{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .zig_wgpu, .name = .zig_wgpu,
// This is a [Semantic Version](https://semver.org/). .version = "0.2.0",
// In a future version of Zig it will be used for package deduplication. .fingerprint = 0x5d0e853acbc0c2c6,
.version = "0.0.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
// package is first created, and then *never changes*. This allows
// unambiguous detection of one package being an updated version of
// another.
//
// When forking a Zig project, this id should be regenerated (delete the
// field and run `zig build`) if the upstream project is still maintained.
// Otherwise, the fork is *hostile*, attempting to take control over the
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0x5d0e853acbc0c2c6, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.16.0", .minimum_zig_version = "0.16.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{}, .dependencies = .{},
.paths = .{ .paths = .{
"build.zig", "build.zig",
"build.zig.zon", "build.zig.zon",
"src", "src",
// For example... "libs",
//"LICENSE",
//"README.md",
}, },
} }
+78 -37
View File
@@ -1,37 +1,79 @@
const std = @import("std"); const std = @import("std");
const GpuDevice = @import("GpuDevice.zig"); const gpu = @import("gpu");
const GpuAllocator = @import("GpuAllocator.zig"); const GpuDevice = gpu.GpuDevice;
const GpuPipeline = @import("GpuPipeline.zig"); const GpuArenaAllocator = gpu.GpuArenaAllocator;
const Vec = @import("Vec.zig"); const GpuAllocator = gpu.GpuAllocator;
const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute;
const c = @import("c.zig").c; pub const std_options = std.Options{ .log_level = .info };
/// Minimal implementation of a f16 Vector
const Vec = struct {
buf: GpuBuffer,
len: usize,
// Changed: gloc is passed by value (const)
pub fn initZero(gloc: GpuAllocator, len: usize) !Vec {
return .{
.buf = try GpuBuffer.init(gloc, .{
.size = len * @sizeOf(f16),
.usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }),
}),
.len = len,
};
}
// Changed: gloc is passed by value
pub fn initLoad(gloc: GpuAllocator, data: []const f16) !Vec {
var self = try initZero(gloc, data.len);
try self.load(data); // Direct access via the interface copy
return self;
}
pub fn deinit(self: Vec) void {
self.buf.deinit();
}
/// CPU to GPU.
pub fn load(self: Vec, data: []const f16) !void {
try self.buf.load(f16, data);
}
// Changed: gloc is passed by value instead of *GpuAllocator
pub fn run(self: Vec, gloc: GpuAllocator, other: Vec, process: GpuCompute) !Vec {
std.debug.assert(self.len == other.len);
const result = try Vec.initZero(gloc, self.len);
errdefer result.deinit();
try process.run(gloc, .{ self.buf, other.buf, result.buf });
return result;
}
// Changed: gloc is passed by value instead of *GpuAllocator
pub fn read(self: Vec, alloc: std.mem.Allocator) ![]f16 {
return self.buf.read(alloc, f16);
}
};
pub fn main(init: std.process.Init) !void { pub fn main(init: std.process.Init) !void {
const device = try GpuDevice.init(); const device = try GpuDevice.init(.{ .vram_bytes_limit = 4 * 1024 * 1024 * 1024 });
defer device.deinit(); defer device.deinit();
var gloc = try GpuAllocator.init(init.gpa, device); var grena = GpuArenaAllocator.init(init.gpa, device.gpuAllocator());
defer gloc.deinit(); defer grena.deinit();
const gloc = grena.gpuAllocator();
const add_pip = try GpuPipeline.init(device, @embedFile("shaders/add.wgsl")); const add_pip = try GpuCompute.init(gloc, @embedFile("shaders/add.wgsl"), .{ .bindings = &.{
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
} });
defer add_pip.deinit(); defer add_pip.deinit();
const allocator = init.gpa; const allocator = init.gpa;
// --- WARM-UP PHASE ---
{
var warmup_a = [_]f32{1.0};
var warmup_b = [_]f32{1.0};
const wa = try Vec.initLoad(&gloc, &warmup_a);
defer wa.deinit();
const wb = try Vec.initLoad(&gloc, &warmup_b);
defer wb.deinit();
const wsum = try wa.run(&gloc, wb, add_pip);
defer wsum.deinit();
const wout = try wsum.read(&gloc, allocator);
defer allocator.free(wout);
}
const sizes = [_]usize{ const sizes = [_]usize{
1, 1,
256, 256,
@@ -44,8 +86,8 @@ pub fn main(init: std.process.Init) !void {
4 * 1024 * 1024, 4 * 1024 * 1024,
4 * 4 * 1024 * 1024, 4 * 4 * 1024 * 1024,
4 * 4 * 4 * 1024 * 1024, 4 * 4 * 4 * 1024 * 1024,
4 * 4 * 4 * 4 * 1024 * 1024, // 4 * 4 * 4 * 4 * 1024 * 1024,
4 * 4 * 4 * 4 * 4 * 1024 * 1024, // 4 * 4 * 4 * 4 * 4 * 1024 * 1024,
}; };
const iterations = 10; const iterations = 10;
@@ -56,9 +98,9 @@ pub fn main(init: std.process.Init) !void {
for (sizes) |size| { for (sizes) |size| {
// --- Phase 1: Host Init/Alloc (Outside the iteration loop for pure host prep) --- // --- Phase 1: Host Init/Alloc (Outside the iteration loop for pure host prep) ---
var data_a = try allocator.alloc(f32, size); const data_a = try allocator.alloc(f16, size);
defer allocator.free(data_a); defer allocator.free(data_a);
var data_b = try allocator.alloc(f32, size); const data_b = try allocator.alloc(f16, size);
defer allocator.free(data_b); defer allocator.free(data_b);
for (0..size) |i| { for (0..size) |i| {
@@ -72,15 +114,15 @@ pub fn main(init: std.process.Init) !void {
var min_compute_ns: u64 = std.math.maxInt(u64); var min_compute_ns: u64 = std.math.maxInt(u64);
// Track peak VRAM usage observed during the iterations // Track peak VRAM usage observed during the iterations
var peak_vram_bytes: usize = 0; var peak_vram_bytes: u64 = 0;
for (0..iterations) |_| { for (0..iterations) |_| {
// --- 1. GPU ALLOCATION PHASE --- // --- 1. GPU ALLOCATION PHASE ---
const alloc_start = std.Io.Clock.awake.now(init.io); const alloc_start = std.Io.Clock.awake.now(init.io);
const a = try Vec.initLoad(&gloc, data_a); const a = try Vec.initLoad(gloc, data_a);
defer a.deinit(); defer a.deinit();
const b = try Vec.initLoad(&gloc, data_b); const b = try Vec.initLoad(gloc, data_b);
defer b.deinit(); defer b.deinit();
const alloc_duration = alloc_start.durationTo(std.Io.Clock.awake.now(init.io)); const alloc_duration = alloc_start.durationTo(std.Io.Clock.awake.now(init.io));
@@ -90,16 +132,15 @@ pub fn main(init: std.process.Init) !void {
// --- 2. COMPUTE PHASE --- // --- 2. COMPUTE PHASE ---
const compute_start = std.Io.Clock.awake.now(init.io); const compute_start = std.Io.Clock.awake.now(init.io);
const sum = try a.run(&gloc, b, add_pip); const sum = try a.run(gloc, b, add_pip);
defer sum.deinit(); defer sum.deinit();
// All 3 buffers (a, b, sum) are currently resident in VRAM here. // All 3 buffers (a, b, sum) are currently resident in VRAM here.
// Querying now catches the true peak allocation step. // Querying now catches the true peak allocation step.
if (gloc.allocated_vram_bytes > peak_vram_bytes) { if (grena.allocated_vram_bytes > peak_vram_bytes)
peak_vram_bytes = gloc.allocated_vram_bytes; peak_vram_bytes = grena.allocated_vram_bytes;
}
_ = c.wgpuDevicePoll(device.device, 1, null); device.poll();
const compute_duration = compute_start.durationTo(std.Io.Clock.awake.now(init.io)); const compute_duration = compute_start.durationTo(std.Io.Clock.awake.now(init.io));
const compute_ns = @as(u64, @intCast(compute_duration.toNanoseconds())); const compute_ns = @as(u64, @intCast(compute_duration.toNanoseconds()));
@@ -108,7 +149,7 @@ pub fn main(init: std.process.Init) !void {
// --- 3. TRANSFER PHASE (Device -> Host) --- // --- 3. TRANSFER PHASE (Device -> Host) ---
const transfer_start = std.Io.Clock.awake.now(init.io); const transfer_start = std.Io.Clock.awake.now(init.io);
const out = try sum.read(&gloc, allocator); const out = try sum.read(allocator);
defer allocator.free(out); defer allocator.free(out);
const transfer_duration = transfer_start.durationTo(std.Io.Clock.awake.now(init.io)); const transfer_duration = transfer_start.durationTo(std.Io.Clock.awake.now(init.io));
@@ -118,7 +159,7 @@ pub fn main(init: std.process.Init) !void {
// --- Metrics Calculations --- // --- Metrics Calculations ---
const f_size = @as(f64, @floatFromInt(size)); const f_size = @as(f64, @floatFromInt(size));
const element_bytes = f_size * @as(f64, @floatFromInt(@sizeOf(f32))); const element_bytes = f_size * @as(f64, @floatFromInt(@sizeOf(f16)));
const mb = element_bytes / (1024.0 * 1024.0); const mb = element_bytes / (1024.0 * 1024.0);
// Individual Phase Timings (ms) // Individual Phase Timings (ms)
+76
View File
@@ -0,0 +1,76 @@
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer;
const GpuRender = gpu.GpuRender;
const GpuTexture = gpu.GpuTexture;
const GpuTextureView = gpu.GpuTextureView;
const width: u32 = 512;
const height: u32 = 512;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Init VRAM Arena
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load Render Pipeline
const circle_rp = try GpuRender.init(
gloc,
@embedFile("shaders/circle.wgsl"),
.{ .bindings = &.{}, .texture_format = .RGBA8Unorm, .topology = .TriangleStrip },
);
defer circle_rp.deinit();
// 4. Create VRAM texture to render into
const texture = try GpuTexture.init(gloc, .{
.format = .RGBA8Unorm,
.size = .{ .width = width, .height = height, .depthOrArrayLayers = 1 },
.usage = .initMany(&.{ .RenderAttachment, .CopySrc }),
});
defer texture.deinit();
// 5. Create a view from texture
const view = try GpuTextureView.init(gloc, texture, .{});
defer view.deinit();
// 6. Run the rendering pipeline
try circle_rp.draw(gloc, view, 4, .{});
// 7. Load Texture into GpuBuffer
const cpu_staging_cpu = try texture.buffCopy(gloc);
defer cpu_staging_cpu.deinit();
// 8. Read GpuBuffer to CPU
// This need to be free manually because CPU memory
const pixels = try cpu_staging_cpu.read(allocator, u8);
defer allocator.free(pixels);
// 9. Write a simple ppm image
try savePpm(init.io, "circle.ppm", width, height, pixels);
}
fn savePpm(io: std.Io, filename: []const u8, w: u32, h: u32, rgba_pixels: []const u8) !void {
const file = try std.Io.Dir.cwd().createFile(io, filename, .{});
defer file.close(io);
var buf: [255]u8 = undefined;
var writer = file.writer(io, &buf);
// PPM Header: P6 format means raw RGB bytes
try writer.interface.print("P6\n{d} {d}\n255\n", .{ w, h });
// Strip Alpha channel when writing out to standard RGB PPM format
var i: usize = 0;
while (i < rgba_pixels.len) : (i += 4) {
try writer.interface.writeAll(rgba_pixels[i .. i + 3]);
}
}
+68
View File
@@ -0,0 +1,68 @@
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Create a GPU Arena to manage VRAM
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load the WGSL compute pipeline
const add_cp = try GpuCompute.init(
gloc,
@embedFile("shaders/add.wgsl"),
.{
.label = "add",
.bindings = &.{
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) },
},
},
);
// 4. Setup CPU data
const len: usize = 16;
const data_a = try allocator.alloc(f16, len);
defer allocator.free(data_a);
const data_b = try allocator.alloc(f16, len);
defer allocator.free(data_b);
for (0..len) |i| {
data_a[i] = @floatFromInt(i);
data_b[i] = @floatFromInt(len - 1 - i);
}
// 5. Initialize raw GPU Buffers
const byte_size = len * @sizeOf(f16);
const buf_a = try GpuBuffer.init(gloc, .{ .label = "a", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_b = try GpuBuffer.init(gloc, .{ .label = "b", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_out = try GpuBuffer.init(gloc, .{ .label = "out", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
// Note: Buffers are safely tied to the GpuArenaAllocator which will automatically
// release them at the end. You can also manually call buf_x.deinit() if desired.
// This will also release pipelines, textures, ect. Everything using a GpuAllocator to init.
// 6. Transfer data from CPU slices to GPU Buffers
try buf_a.load(f16, data_a);
try buf_b.load(f16, data_b);
// 7. Dispatch the Compute
try add_cp.run(gloc, .{ buf_a, buf_b, buf_out });
// 8. Map and copy the resulting buffer back to the CPU
const out = try buf_out.read(allocator, f16);
defer allocator.free(out);
std.debug.print("Result: {any}\n", .{out});
}
@@ -1,11 +1,9 @@
@group(0) @binding(0) var<storage, read> A: array<f32>; enable f16;
@group(0) @binding(1) var<storage, read> B: array<f32>;
@group(0) @binding(2) var<storage, read_write> C: array<f32>;
struct TensorInfo { @group(0) @binding(0) var<storage, read> A: array<f16>;
size: u32, @group(0) @binding(1) var<storage, read> B: array<f16>;
}; @group(0) @binding(2) var<storage, read_write> C: array<f16>;
@group(0) @binding(3) var<uniform> info: TensorInfo; @group(0) @binding(3) var<uniform> size: u32;
@compute @workgroup_size(256) @compute @workgroup_size(256)
fn main( fn main(
@@ -19,7 +17,7 @@ fn main(
var index = global_id.x; var index = global_id.x;
// 3. Stride through the tensor elements // 3. Stride through the tensor elements
while (index < info.size) { while (index < size) {
C[index] = A[index] + B[index]; C[index] = A[index] + B[index];
index += total_threads; // Jump forward by the total thread count index += total_threads; // Jump forward by the total thread count
} }
+39
View File
@@ -0,0 +1,39 @@
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) uv: vec2f,
};
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
var output: VertexOutput;
// Hardcoded fullscreen quad layout using 4 vertices (Triangle Strip)
// Indexes: 0: Top-Left, 1: Bottom-Left, 2: Top-Right, 3: Bottom-Right
var pos = array<vec2f, 4>(
vec2f(-1.0, 1.0),
vec2f(-1.0, -1.0),
vec2f( 1.0, 1.0),
vec2f( 1.0, -1.0)
);
output.position = vec4f(pos[vertex_index], 0.0, 1.0);
output.uv = pos[vertex_index]; // Ranges cleanly from -1.0 to 1.0
return output;
}
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4f {
// Distance from the center (0,0)
let distance = length(input.uv);
let radius = 0.5;
// Smooth out pixel edges (anti-aliasing)
let edge_softness = 0.005;
let alpha = 1.0 - smoothstep(radius - edge_softness, radius + edge_softness, distance);
if (alpha <= 0.0) {
discard;
}
// Draw a sharp/smooth red circle
return vec4f(1.0, 0.3, 0.3, alpha);
}
+47 -43
View File
@@ -1,55 +1,59 @@
const std = @import("std");
const GpuDevice = @import("GpuDevice.zig"); const GpuDevice = @import("GpuDevice.zig");
const GpuBuffer = @import("GpuBuffer.zig"); const c = @import("utils.zig").c;
const c = @import("c.zig").c;
pub const VTable = struct {
allocBuffer: *const fn (ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer,
freeBuffer: *const fn (ctx: *anyopaque, buf_raw: c.WGPUBuffer) void,
allocTexture: *const fn (ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture,
freeTexture: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTexture) void,
allocTextureView: *const fn (ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView,
freeTextureView: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTextureView) void,
allocRenderPipeline: *const fn (ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline,
freeRenderPipeline: *const fn (ctx: *anyopaque, buf_raw: c.WGPURenderPipeline) void,
allocComputePipeline: *const fn (ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline,
freeComputePipeline: *const fn (ctx: *anyopaque, buf_raw: c.WGPUComputePipeline) void,
};
device: GpuDevice, device: GpuDevice,
tracked_buffers: std.AutoHashMap(c.WGPUBuffer, void), ptr: *anyopaque,
allocated_vram_bytes: u64 = 0, vtable: *const VTable,
pub fn init(cpu_allocator: std.mem.Allocator, device: GpuDevice) !@This() { pub fn allocBuffer(self: @This(), desc: c.WGPUBufferDescriptor) !c.WGPUBuffer {
return .{ return self.vtable.allocBuffer(self.ptr, desc);
.device = device,
.tracked_buffers = .init(cpu_allocator),
};
} }
pub fn deinit(self: *@This()) void { pub fn freeBuffer(self: @This(), raw: c.WGPUBuffer) void {
var it = self.tracked_buffers.keyIterator(); self.vtable.freeBuffer(self.ptr, raw);
while (it.next()) |buf_ptr| {
const buf = buf_ptr.*;
c.wgpuBufferDestroy(buf);
c.wgpuBufferRelease(buf);
}
self.tracked_buffers.deinit();
} }
pub fn registerBuffer( pub fn allocTexture(self: @This(), desc: c.WGPUTextureDescriptor) !c.WGPUTexture {
self: *@This(), return self.vtable.allocTexture(self.ptr, desc);
bytes: u64,
usage: c.WGPUBufferUsage,
) !c.WGPUBuffer {
if (bytes > self.device.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
if (bytes + self.allocated_vram_bytes > self.device.config.vram_bytes_limit)
return error.ExceedsVramBudget;
const buf = c.wgpuDeviceCreateBuffer(self.device.device, &.{
.usage = usage,
.size = bytes,
}) orelse return error.BufferAlloc;
try self.tracked_buffers.put(buf, {});
self.allocated_vram_bytes += bytes;
return buf;
} }
pub fn unregisterAndDestroyBuffer(self: *@This(), buf: GpuBuffer) void { pub fn freeTexture(self: @This(), raw: c.WGPUTexture) void {
if (self.tracked_buffers.remove(buf.raw)) { self.vtable.freeTexture(self.ptr, raw);
c.wgpuBufferDestroy(buf.raw);
c.wgpuBufferRelease(buf.raw);
self.allocated_vram_bytes -= buf.size;
self.device.poll();
} }
pub fn allocTextureView(self: @This(), texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) !c.WGPUTextureView {
return self.vtable.allocTextureView(self.ptr, texture, desc);
}
pub fn freeTextureView(self: @This(), raw: c.WGPUTextureView) void {
self.vtable.freeTextureView(self.ptr, raw);
}
pub fn allocRenderPipeline(self: @This(), desc: c.WGPURenderPipelineDescriptor) !c.WGPURenderPipeline {
return self.vtable.allocRenderPipeline(self.ptr, desc);
}
pub fn freeRenderPipeline(self: @This(), raw: c.WGPURenderPipeline) void {
self.vtable.freeRenderPipeline(self.ptr, raw);
}
pub fn allocComputePipeline(self: @This(), desc: c.WGPUComputePipelineDescriptor) !c.WGPUComputePipeline {
return self.vtable.allocComputePipeline(self.ptr, desc);
}
pub fn freeComputePipeline(self: @This(), raw: c.WGPUComputePipeline) void {
self.vtable.freeComputePipeline(self.ptr, raw);
} }
+222
View File
@@ -0,0 +1,222 @@
const std = @import("std");
const GpuDevice = @import("GpuDevice.zig");
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const c = @import("utils.zig").c;
const viewStr = @import("utils.zig").viewStr;
child_allocator: GpuAllocator, // I use Zig naming child_allocator, but that should be a parent for me. Likely something idk
tracked_buffers: std.AutoHashMap(c.WGPUBuffer, c.WGPUBufferDescriptor),
tracked_textures: std.AutoHashMap(c.WGPUTexture, c.WGPUTextureDescriptor),
tracked_views: std.AutoHashMap(c.WGPUTextureView, c.WGPUTextureViewDescriptor),
tracked_renders: std.AutoHashMap(c.WGPURenderPipeline, c.WGPURenderPipelineDescriptor),
tracked_computes: std.AutoHashMap(c.WGPUComputePipeline, c.WGPUComputePipelineDescriptor),
allocated_vram_bytes: u64 = 0,
pub fn init(cpu_allocator: std.mem.Allocator, child_allocator: GpuAllocator) @This() {
return .{
.child_allocator = child_allocator,
.tracked_buffers = .init(cpu_allocator),
.tracked_textures = .init(cpu_allocator),
.tracked_views = .init(cpu_allocator),
.tracked_computes = .init(cpu_allocator),
.tracked_renders = .init(cpu_allocator),
};
}
pub fn deinit(self: *@This()) void {
std.log.debug("Freeing GpuArenaAllocator (Used VRAM: {}/{} MB)", .{
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
var it_buffer = self.tracked_buffers.keyIterator();
while (it_buffer.next()) |buf_ptr|
freeBuffer(self, buf_ptr.*);
self.tracked_buffers.deinit();
var it_tex = self.tracked_textures.keyIterator();
while (it_tex.next()) |buf_ptr|
freeTexture(self, buf_ptr.*);
self.tracked_textures.deinit();
var it_view = self.tracked_views.keyIterator();
while (it_view.next()) |buf_ptr|
freeTextureView(self, buf_ptr.*);
self.tracked_views.deinit();
var it_render = self.tracked_renders.keyIterator();
while (it_render.next()) |buf_ptr|
freeRenderPipeline(self, buf_ptr.*);
self.tracked_renders.deinit();
var it_compute = self.tracked_computes.keyIterator();
while (it_compute.next()) |buf_ptr|
freeComputePipeline(self, buf_ptr.*);
self.tracked_computes.deinit();
std.log.debug("Freed GpuArenaAllocator (Used VRAM: {}/{} MB)", .{
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
/// Returns the type-erased immutable interface wrapper
pub fn gpuAllocator(self: *@This()) GpuAllocator {
return .{
.device = self.child_allocator.device,
.ptr = self,
.vtable = &.{
.allocBuffer = allocBuffer,
.freeBuffer = freeBuffer,
.allocTexture = allocTexture,
.freeTexture = freeTexture,
.allocTextureView = allocTextureView,
.freeTextureView = freeTextureView,
.allocRenderPipeline = allocRenderPipeline,
.freeRenderPipeline = freeRenderPipeline,
.allocComputePipeline = allocComputePipeline,
.freeComputePipeline = freeComputePipeline,
},
};
}
// NOTE: I use ensureTotalCapacity so I know that try self.tracked_x.put will not fail!
// Like that I dont have to use errdefer to release what I just allocated in VRAM
fn allocBuffer(ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_buffers.ensureTotalCapacity(self.tracked_buffers.count() + 1);
const bytes = desc.size;
if (bytes > self.child_allocator.device.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
if (bytes + self.allocated_vram_bytes > self.child_allocator.device.def.vram_bytes_limit)
return error.ExceedsVramBudget;
const raw = try self.child_allocator.allocBuffer(desc);
self.tracked_buffers.putAssumeCapacity(raw, desc);
self.allocated_vram_bytes += desc.size;
std.log.debug("Allocated Buffer '{s}': {d} B (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
desc.size,
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
return raw;
}
fn freeBuffer(ctx: *anyopaque, raw: c.WGPUBuffer) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_buffers.fetchRemove(raw)) |kv| {
self.child_allocator.freeBuffer(raw);
self.allocated_vram_bytes -= kv.value.size;
std.log.debug("Freed Buffer '{s}' (Total VRAM: {}/{} MB)", .{
viewStr(kv.value.label),
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
}
fn allocTexture(ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_textures.ensureTotalCapacity(self.tracked_textures.count() + 1);
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
if (bytes_size + self.allocated_vram_bytes > self.child_allocator.device.def.vram_bytes_limit)
return error.ExceedsVramBudget;
const raw = try self.child_allocator.allocTexture(desc);
self.tracked_textures.putAssumeCapacity(raw, desc);
self.allocated_vram_bytes += bytes_size;
std.log.debug("Allocated Texture '{s}': {d} B (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
bytes_size,
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
return raw;
}
fn freeTexture(ctx: *anyopaque, raw: c.WGPUTexture) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_textures.fetchRemove(raw)) |kv| {
self.child_allocator.freeTexture(raw);
const desc = kv.value;
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
self.allocated_vram_bytes -= bytes_size;
std.log.debug("Freed Texture '{s}' (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
}
fn allocTextureView(ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_views.ensureTotalCapacity(self.tracked_views.count() + 1);
const raw = try self.child_allocator.allocTextureView(texture, desc);
self.tracked_views.putAssumeCapacity(raw, desc);
std.log.debug("Allocated Texture View '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeTextureView(ctx: *anyopaque, raw: c.WGPUTextureView) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_views.fetchRemove(raw)) |kv| {
self.child_allocator.freeTextureView(raw);
const desc = kv.value;
std.log.debug("Freed Texture View '{s}'", .{viewStr(desc.label)});
}
}
fn allocRenderPipeline(ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_renders.ensureTotalCapacity(self.tracked_renders.count() + 1);
const raw = try self.child_allocator.allocRenderPipeline(desc);
self.tracked_renders.putAssumeCapacity(raw, desc);
std.log.debug("Allocated Render Pipeline '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeRenderPipeline(ctx: *anyopaque, raw: c.WGPURenderPipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_renders.fetchRemove(raw)) |kv| {
self.child_allocator.freeRenderPipeline(raw);
const desc = kv.value;
std.log.debug("Freed Render Pipeline '{s}'", .{viewStr(desc.label)});
}
}
fn allocComputePipeline(ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_computes.ensureTotalCapacity(self.tracked_computes.count() + 1);
const raw = try self.child_allocator.allocComputePipeline(desc);
self.tracked_computes.putAssumeCapacity(raw, desc);
std.log.debug("Allocated Compute Pipeline '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeComputePipeline(ctx: *anyopaque, raw: c.WGPUComputePipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_computes.fetchRemove(raw)) |kv| {
self.child_allocator.freeComputePipeline(raw);
const desc = kv.value;
std.log.debug("Freed Compute Pipeline '{s}'", .{viewStr(desc.label)});
}
}
+116 -16
View File
@@ -1,29 +1,62 @@
const std = @import("std"); const std = @import("std");
const c = @import("c.zig").c; const c = @import("utils.zig").c;
const GpuAllocator = @import("GpuAllocator.zig"); const GpuAllocator = @import("GpuAllocator.zig");
const svOpt = @import("utils.zig").svOpt;
raw: c.WGPUBuffer, raw: c.WGPUBuffer,
size: u64, size: u64,
usage: c.WGPUBufferUsage, usage: c.WGPUBufferUsage,
gloc: *GpuAllocator, gloc: GpuAllocator,
/// Allocates the underlying WebGPU handle and registers it to the parent GpuAllocator const BufferUsage = enum(u64) {
pub fn init(gloc: *GpuAllocator, bytes: u64, usage: c.WGPUBufferUsage) !@This() { None = 0x0000000000000000,
const raw_handle = try gloc.registerBuffer(bytes, usage); MapRead = 0x0000000000000001,
MapWrite = 0x0000000000000002,
CopySrc = 0x0000000000000004,
CopyDst = 0x0000000000000008,
Index = 0x0000000000000010,
Vertex = 0x0000000000000020,
Uniform = 0x0000000000000040,
Storage = 0x0000000000000080,
Indirect = 0x0000000000000100,
QueryResolve = 0x0000000000000200,
};
const GpuBufferDef = struct {
label: ?[]const u8 = null,
size: u64,
usage: std.EnumSet(BufferUsage),
};
pub fn init(gloc: GpuAllocator, def: GpuBufferDef) !@This() {
var use: u64 = 0;
var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag);
// Automatically align the buffer size forward to a multiple of 4 bytes under the hood
const aligned_size = std.mem.alignForward(u64, def.size, 4);
const raw_handle = try gloc.allocBuffer(.{
.size = aligned_size,
.usage = use,
.label = svOpt(def.label),
});
return .{ return .{
.raw = raw_handle, .raw = raw_handle,
.size = bytes, .size = aligned_size,
.usage = usage, .usage = use,
.gloc = gloc, .gloc = gloc,
}; };
} }
/// Unregisters from the parent GpuAllocator and cleanly destroys GPU resources
pub fn deinit(self: @This()) void { pub fn deinit(self: @This()) void {
self.gloc.unregisterAndDestroyBuffer(self); self.gloc.freeBuffer(self.raw);
}
pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque {
return c.wgpuBufferGetConstMappedRange(self.raw, offset, size);
} }
/// Native mapAsync wrapper
pub fn mapAsync( pub fn mapAsync(
self: @This(), self: @This(),
mode: c.WGPUMapMode, mode: c.WGPUMapMode,
@@ -34,12 +67,79 @@ pub fn mapAsync(
_ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info); _ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info);
} }
/// Native getConstMappedRange wrapper
pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque {
return c.wgpuBufferGetConstMappedRange(self.raw, offset, size);
}
/// Native unmap wrapper
pub fn unmap(self: @This()) void { pub fn unmap(self: @This()) void {
c.wgpuBufferUnmap(self.raw); c.wgpuBufferUnmap(self.raw);
} }
/// CPU to GPU
pub fn load(
self: @This(),
T: type,
data: []const T,
) !void {
const bytes = data.len * @sizeOf(T);
if (bytes == self.size) {
// Aligned path: direct download
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, 0, data.ptr, self.size);
} else {
// Unaligned path: Split the write into an aligned chunk and a padded remainder
// to support arbitrary lengths without any allocations or large stack arrays.
const aligned_part = (bytes / 4) * 4;
if (aligned_part > 0) {
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, 0, data.ptr, aligned_part);
}
var remainder_buf: [4]u8 = .{ 0, 0, 0, 0 };
const data_bytes = std.mem.sliceAsBytes(data);
@memcpy(remainder_buf[0 .. bytes - aligned_part], data_bytes[aligned_part..bytes]);
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, aligned_part, &remainder_buf, 4);
}
}
/// GPU to CPU
pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T {
const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T)));
const staging = try init(self.gloc, .{
.size = self.size,
.usage = .initMany(&.{ .MapRead, .CopyDst }),
.label = "staging_read_buffer",
});
defer staging.deinit();
const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder;
c.wgpuCommandEncoderCopyBufferToBuffer(enc, self.raw, 0, staging.raw, 0, self.size);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(self.gloc.device.queue, 1, &cmd);
var mapped = false;
staging.mapAsync(
c.WGPUMapMode_Read,
0,
self.size,
.{ .callback = onMapped, .userdata1 = &mapped },
);
while (!mapped) self.gloc.device.poll();
const ptr: [*]const T = @ptrCast(@alignCast(
staging.getConstMappedRange(0, self.size),
));
@memcpy(out[0..out.len], ptr[0..out.len]);
staging.unmap();
return out;
}
fn onMapped(
status: c.WGPUMapAsyncStatus,
_: c.WGPUStringView,
userdata1: ?*anyopaque,
_: ?*anyopaque,
) callconv(.c) void {
const flag: *bool = @ptrCast(@alignCast(userdata1.?));
flag.* = (status == c.WGPUMapAsyncStatus_Success);
}
+176
View File
@@ -0,0 +1,176 @@
const c = @import("utils.zig").c;
const sv = @import("utils.zig").sv;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig");
const GpuDevice = @import("GpuDevice.zig");
pub const Binding = struct {
/// Element size in bytes for this binding. E.g. @sizeOf(f32).
/// If 0, no element-based size validation is performed for this buffer.
element_size: u32 = 0,
};
pub const ComputeDef = struct {
label: ?[]const u8 = null,
bindings: []const Binding,
workgroup_size: u32 = 256,
max_workgroups: u32 = 65535,
/// If true, automatically adds a Uniform Buffer containing `elements_count` as a `u32`
/// to the next available binding slot.
append_info_buffer: bool = true,
};
pip: c.WGPUComputePipeline,
gloc: GpuAllocator,
def: ComputeDef,
pub fn init(gloc: GpuAllocator, wgsl: []const u8, def: ComputeDef) !@This() {
var wgsl_src = c.WGPUShaderSourceWGSL{
.chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL },
.code = sv(wgsl),
};
const shader = c.wgpuDeviceCreateShaderModule(gloc.device.device, &.{
.nextInChain = @ptrCast(&wgsl_src),
}) orelse return error.Shader;
defer c.wgpuShaderModuleRelease(shader);
const pip = try gloc.allocComputePipeline(.{
.label = svOpt(def.label),
.compute = .{ .module = shader, .entryPoint = sv("main") },
});
return .{
.gloc = gloc,
.pip = pip,
.def = def,
};
}
pub fn deinit(self: @This()) void {
self.gloc.freeComputePipeline(self.pip);
}
/// Execute the compute pass with arbitrary buffer bindings via a tuple.
/// Example: `try proc.run(gloc, .{ buf_a, buf_b, buf_out });`
pub fn run(
self: @This(),
gloc: GpuAllocator,
args: anytype,
) !void {
const type_info = @typeInfo(@TypeOf(args));
if (type_info != .@"struct" or !type_info.@"struct".is_tuple)
@compileError("Expected a tuple of GpuBuffers for args. E.g. .{ buf_a, buf_b }");
const fields = type_info.@"struct".fields;
if (fields.len != self.def.bindings.len)
return error.InvalidArgumentCount;
var elements_count: u32 = 0;
// Infer elements_count from the first arg with a defined element_size
inline for (fields, 0..) |field, i| {
if (elements_count == 0) {
const buf = @field(args, field.name);
const el_size = self.def.bindings[i].element_size;
if (el_size > 0) {
elements_count = @intCast(buf.size / el_size);
}
}
}
// Validate runtime buffer sizes before dispatching
inline for (fields, 0..) |field, i| {
const buf = @field(args, field.name);
const el_size = self.def.bindings[i].element_size;
if (el_size > 0) {
const expected_min_bytes = @as(u64, elements_count) * el_size;
if (buf.size < expected_min_bytes)
return error.BufferTooSmall;
}
}
var entries_buf: [32]c.WGPUBindGroupEntry = undefined;
var entry_count: usize = 0;
// Unpack tuple into WebGPU BindGroupEntries
inline for (fields, 0..) |field, i| {
const buf = @field(args, field.name);
if (@TypeOf(buf) != GpuBuffer) {
@compileError("All arguments in the tuple must be of type GpuBuffer");
}
entries_buf[entry_count] = .{
.binding = @intCast(i),
.buffer = buf.raw,
.offset = 0,
.size = buf.size, // Size exposes the fully allocated length
};
entry_count += 1;
}
// Optional uniform dispatch buffer appended at the end
var info_buf: ?GpuBuffer = null;
defer if (info_buf) |b| b.deinit();
if (self.def.append_info_buffer) {
info_buf = try GpuBuffer.init(gloc, .{
.size = @sizeOf(u32),
.usage = .initMany(&.{ .Uniform, .CopyDst }),
.label = "compute_info_buffer",
});
c.wgpuQueueWriteBuffer(gloc.device.queue, info_buf.?.raw, 0, &elements_count, @sizeOf(u32));
entries_buf[entry_count] = .{
.binding = @intCast(entry_count),
.buffer = info_buf.?.raw,
.offset = 0,
.size = @sizeOf(u32),
};
entry_count += 1;
}
const entries = entries_buf[0..entry_count];
try submitPass(gloc, self.pip, entries, elements_count, self.def.workgroup_size, self.def.max_workgroups);
}
fn submitPass(
gloc: GpuAllocator,
pipeline: c.WGPUComputePipeline,
entries: []const c.WGPUBindGroupEntry,
n: usize,
workgroup_size: u32,
max_workgroups: u32,
) !void {
if (n == 0) return;
const bgl = c.wgpuComputePipelineGetBindGroupLayout(pipeline, 0);
defer c.wgpuBindGroupLayoutRelease(bgl);
const bg = c.wgpuDeviceCreateBindGroup(gloc.device.device, &.{
.layout = bgl,
.entries = entries.ptr,
.entryCount = entries.len,
}) orelse return error.BindGroup;
defer c.wgpuBindGroupRelease(bg);
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse return error.Encoder;
const pass = c.wgpuCommandEncoderBeginComputePass(enc, null);
c.wgpuComputePassEncoderSetPipeline(pass, pipeline);
c.wgpuComputePassEncoderSetBindGroup(pass, 0, bg, 0, null);
const desired_workgroups = ceilDiv(n, workgroup_size);
const dispatch_count = @min(desired_workgroups, max_workgroups);
c.wgpuComputePassEncoderDispatchWorkgroups(pass, @intCast(dispatch_count), 1, 1);
c.wgpuComputePassEncoderEnd(pass);
c.wgpuComputePassEncoderRelease(pass);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
}
fn ceilDiv(n: usize, d: usize) usize {
return (n + d - 1) / d;
}
+130 -16
View File
@@ -1,22 +1,36 @@
const std = @import("std"); const std = @import("std");
const c = @import("c.zig").c; const c = @import("utils.zig").c;
const sv = @import("utils.zig").sv;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const Ctx = struct { const Ctx = struct {
adapter: c.WGPUAdapter = null, adapter: c.WGPUAdapter = null,
device: c.WGPUDevice = null, device: c.WGPUDevice = null,
}; };
const GpuDeviceDef = struct {
label: ?[]const u8 = null,
/// VRAM limit. Default 2 GB
vram_bytes_limit: u64 = 2 * 1024 * 1024 * 1024,
power_preference: enum(c_uint) {
Undefined = 0x00000000,
LowPower = 0x00000001,
HighPerformance = 0x00000002,
Force32 = 0x7FFFFFFF,
} = .HighPerformance,
};
instance: c.WGPUInstance, instance: c.WGPUInstance,
adapter: c.WGPUAdapter, adapter: c.WGPUAdapter,
device: c.WGPUDevice, device: c.WGPUDevice,
queue: c.WGPUQueue, queue: c.WGPUQueue,
limits: c.WGPULimits, limits: c.WGPULimits,
config: struct { def: GpuDeviceDef,
vram_bytes_limit: u64 = 10 * 1024 * 1024 * 1024, // 10 GB
} = .{},
pub fn init() !@This() { pub fn init(def: GpuDeviceDef) !@This() {
const instance = c.wgpuCreateInstance( const instance = c.wgpuCreateInstance(
&std.mem.zeroes(c.WGPUInstanceDescriptor), &std.mem.zeroes(c.WGPUInstanceDescriptor),
) orelse return error.NoInstance; ) orelse return error.NoInstance;
@@ -25,28 +39,58 @@ pub fn init() !@This() {
var ctx = Ctx{}; var ctx = Ctx{};
_ = c.wgpuInstanceRequestAdapter( _ = c.wgpuInstanceRequestAdapter(
instance, instance,
&.{ .powerPreference = c.WGPUPowerPreference_HighPerformance }, &.{ .powerPreference = @intFromEnum(def.power_preference) },
.{ .callback = onAdapter, .userdata1 = &ctx }, .{ .callback = onAdapter, .userdata1 = &ctx },
); );
c.wgpuInstanceProcessEvents(instance); c.wgpuInstanceProcessEvents(instance);
const adapter = ctx.adapter orelse return error.NoAdapter; const adapter = ctx.adapter orelse return error.NoAdapter;
errdefer c.wgpuAdapterRelease(adapter); errdefer c.wgpuAdapterRelease(adapter);
// --- QUERY HARDWARE LIMITS --- var adapter_info = std.mem.zeroes(c.WGPUAdapterInfo);
_ = c.wgpuAdapterGetInfo(adapter, &adapter_info);
std.log.info("=== WebGPU Device Initialized ===", .{});
if (adapter_info.device.length > 0 and adapter_info.device.data != null) {
std.log.info(" Device Name : {s}", .{adapter_info.device.data[0..adapter_info.device.length]});
}
if (adapter_info.architecture.length > 0 and adapter_info.architecture.data != null) {
std.log.info(" Architecture : {s}", .{adapter_info.architecture.data[0..adapter_info.architecture.length]});
}
std.log.info(" Backend Type : {d}", .{adapter_info.backendType});
var supported_features = std.mem.zeroes(c.WGPUSupportedFeatures);
c.wgpuAdapterGetFeatures(adapter, &supported_features);
var supported_limits = std.mem.zeroes(c.WGPULimits); var supported_limits = std.mem.zeroes(c.WGPULimits);
supported_limits.nextInChain = null; supported_limits.nextInChain = null;
// Fetch what your physical graphic card can actually handle
if (c.wgpuAdapterGetLimits(adapter, &supported_limits) != 1) return error.FailedToGetAdapterLimits; if (c.wgpuAdapterGetLimits(adapter, &supported_limits) != 1) return error.FailedToGetAdapterLimits;
std.log.info(" Max Buf Size : {d} MB", .{supported_limits.maxBufferSize / 1024 / 1024});
std.log.info(" Max Storage : {d} MB", .{supported_limits.maxStorageBufferBindingSize / 1024 / 1024});
std.log.info(" Max Workgroup: X: {d}, Y: {d}, Z: {d}", .{ supported_limits.maxComputeWorkgroupSizeX, supported_limits.maxComputeWorkgroupSizeY, supported_limits.maxComputeWorkgroupSizeZ });
std.log.info(" VRAM Budget : {d} MB", .{def.vram_bytes_limit / 1024 / 1024});
var has_f16 = false;
for (0..supported_features.featureCount) |i| {
if (supported_features.features[i] == c.WGPUFeatureName_ShaderF16) {
has_f16 = true;
break;
}
}
std.log.info(" Shader F16 : {}", .{has_f16});
std.log.info("=================================", .{});
var feature_buf = [_]c.WGPUFeatureName{c.WGPUFeatureName_ShaderF16};
const required_features: []const c.WGPUFeatureName =
if (has_f16) feature_buf[0..1] else &.{};
const device_descriptor = c.WGPUDeviceDescriptor{ const device_descriptor = c.WGPUDeviceDescriptor{
.nextInChain = null, .nextInChain = null,
.label = sv("TensorCompilerDevice"), .label = svOpt(def.label),
.requiredFeatureCount = 0, .requiredFeatureCount = required_features.len,
.requiredFeatures = null, .requiredFeatures = if (required_features.len > 0) required_features.ptr else null,
.requiredLimits = &supported_limits, .requiredLimits = &supported_limits,
}; };
_ = c.wgpuAdapterRequestDevice( _ = c.wgpuAdapterRequestDevice(
adapter, adapter,
&device_descriptor, &device_descriptor,
@@ -61,6 +105,7 @@ pub fn init() !@This() {
.device = device, .device = device,
.queue = c.wgpuDeviceGetQueue(device), .queue = c.wgpuDeviceGetQueue(device),
.limits = supported_limits, .limits = supported_limits,
.def = def,
}; };
} }
@@ -71,7 +116,8 @@ pub fn deinit(self: @This()) void {
c.wgpuInstanceRelease(self.instance); c.wgpuInstanceRelease(self.instance);
} }
pub fn poll(self: *@This()) void { /// Wait for thing to be done
pub fn poll(self: @This()) void {
_ = c.wgpuDevicePoll(self.device, 1, null); _ = c.wgpuDevicePoll(self.device, 1, null);
} }
@@ -105,6 +151,74 @@ fn onDevice(
ctx.device = device; ctx.device = device;
} }
fn sv(s: []const u8) c.WGPUStringView { // Allocation stuff
return .{ .data = s.ptr, .length = s.len };
/// Returns the type-erased immutable interface wrapper
pub fn gpuAllocator(self: *const @This()) GpuAllocator {
return .{
.device = self.*,
.ptr = @ptrCast(@constCast(self)),
.vtable = &.{
.allocBuffer = allocBuffer,
.freeBuffer = freeBuffer,
.allocTexture = allocTexture,
.freeTexture = freeTexture,
.allocTextureView = allocTextureView,
.freeTextureView = freeTextureView,
.allocRenderPipeline = allocRenderPipeline,
.freeRenderPipeline = freeRenderPipeline,
.allocComputePipeline = allocComputePipeline,
.freeComputePipeline = freeComputePipeline,
},
};
}
fn allocBuffer(ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (desc.size > self.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
return c.wgpuDeviceCreateBuffer(self.device, &desc) orelse return error.BufferAlloc;
}
fn freeBuffer(_: *anyopaque, raw: c.WGPUBuffer) void {
c.wgpuBufferDestroy(raw);
c.wgpuBufferRelease(raw);
}
fn allocTexture(ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture {
const self: *@This() = @ptrCast(@alignCast(ctx));
const format: GpuTextureFormat = @enumFromInt(desc.format);
if (desc.size.width * desc.size.height * format.bytesPerPixel() > self.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
return c.wgpuDeviceCreateTexture(self.device, &desc) orelse return error.Texture;
}
fn freeTexture(_: *anyopaque, raw: c.WGPUTexture) void {
c.wgpuTextureRelease(raw);
}
fn allocTextureView(_: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView {
return c.wgpuTextureCreateView(texture, &desc) orelse return error.View;
}
fn freeTextureView(_: *anyopaque, raw: c.WGPUTextureView) void {
c.wgpuTextureViewRelease(raw);
}
fn allocRenderPipeline(ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
return c.wgpuDeviceCreateRenderPipeline(self.device, &desc) orelse return error.Pipeline;
}
fn freeRenderPipeline(_: *anyopaque, raw: c.WGPURenderPipeline) void {
c.wgpuRenderPipelineRelease(raw);
}
fn allocComputePipeline(ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
return c.wgpuDeviceCreateComputePipeline(self.device, &desc) orelse return error.Pipeline;
}
fn freeComputePipeline(_: *anyopaque, raw: c.WGPUComputePipeline) void {
c.wgpuComputePipelineRelease(raw);
} }
-28
View File
@@ -1,28 +0,0 @@
const std = @import("std");
const GpuDevice = @import("GpuDevice.zig");
const c = @import("c.zig").c;
raw: c.WGPUComputePipeline,
pub fn init(device: GpuDevice, wgsl: []const u8) !@This() {
var wgsl_src = c.WGPUShaderSourceWGSL{
.chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL },
.code = sv(wgsl),
};
const shader = c.wgpuDeviceCreateShaderModule(device.device, &.{
.nextInChain = @ptrCast(&wgsl_src),
}) orelse return error.Shader;
defer c.wgpuShaderModuleRelease(shader);
return .{ .raw = c.wgpuDeviceCreateComputePipeline(device.device, &.{
.compute = .{ .module = shader, .entryPoint = sv("main") },
}) orelse return error.Pipeline };
}
pub fn deinit(self: @This()) void {
c.wgpuComputePipelineRelease(self.raw);
}
fn sv(s: []const u8) c.WGPUStringView {
return .{ .data = s.ptr, .length = s.len };
}
+184
View File
@@ -0,0 +1,184 @@
const std = @import("std");
const c = @import("utils.zig").c;
const sv = @import("utils.zig").sv;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig");
const GpuDevice = @import("GpuDevice.zig");
const GpuTextureView = @import("GpuTextureView.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
pub const Binding = struct {
element_size: u32 = 0,
};
pub const GpuRenderDef = struct {
label: ?[]const u8 = null,
bindings: []const Binding = &.{},
/// The surface texture format we are rendering to (e.g., BGRA8Unorm)
texture_format: GpuTextureFormat,
/// The names of the entry points inside your WGSL code
vertex_entry: []const u8 = "vs_main",
fragment_entry: []const u8 = "fs_main",
/// Primitive topology, default to triangle list
topology: GpuPrimitiveTopology = .TriangleList,
};
const GpuPrimitiveTopology = enum(c_uint) {
Undefined = 0x00000000,
PointList = 0x00000001,
LineList = 0x00000002,
LineStrip = 0x00000003,
TriangleList = 0x00000004,
TriangleStrip = 0x00000005,
Force32 = 0x7FFFFFFF,
};
gloc: GpuAllocator,
pip: c.WGPURenderPipeline,
def: GpuRenderDef,
pub fn init(gloc: GpuAllocator, wgsl: []const u8, def: GpuRenderDef) !@This() {
var wgsl_src = c.WGPUShaderSourceWGSL{
.chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL },
.code = sv(wgsl),
};
const shader = c.wgpuDeviceCreateShaderModule(gloc.device.device, &.{
.nextInChain = @ptrCast(&wgsl_src),
}) orelse return error.Shader;
defer c.wgpuShaderModuleRelease(shader);
// 1. Setup the Color Target State (where the fragment shader outputs)
const blend = c.WGPUBlendState{
.color = .{ .operation = c.WGPUBlendOperation_Add, .srcFactor = c.WGPUBlendFactor_SrcAlpha, .dstFactor = c.WGPUBlendFactor_OneMinusSrcAlpha },
.alpha = .{ .operation = c.WGPUBlendOperation_Add, .srcFactor = c.WGPUBlendFactor_One, .dstFactor = c.WGPUBlendFactor_Zero },
};
const color_target = c.WGPUColorTargetState{
.format = @intFromEnum(def.texture_format),
.blend = &blend,
.writeMask = c.WGPUColorWriteMask_All,
};
// 2. Setup the Fragment State
const fragment_state = c.WGPUFragmentState{
.module = shader,
.entryPoint = sv(def.fragment_entry),
.targetCount = 1,
.targets = &color_target,
};
// 3. Compile the Complete Render Pipeline
const pip = try gloc.allocRenderPipeline(.{
.label = svOpt(def.label),
.vertex = .{
.module = shader,
.entryPoint = sv(def.vertex_entry),
},
.primitive = .{
.topology = @intFromEnum(def.topology),
.stripIndexFormat = c.WGPUIndexFormat_Undefined,
.frontFace = c.WGPUFrontFace_CCW,
.cullMode = c.WGPUCullMode_None,
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alphaToCoverageEnabled = 0,
},
.fragment = &fragment_state,
});
return .{
.gloc = gloc,
.pip = pip,
.def = def,
};
}
pub fn deinit(self: @This()) void {
self.gloc.freeRenderPipeline(self.pip);
}
/// Execute the render pass targeting a specific frame texture view.
/// Passes bind groups via a tuple exactly like your original compute setup.
pub fn draw(
self: @This(),
gloc: GpuAllocator,
target_view: GpuTextureView,
vertex_count: u32,
args: anytype,
) !void {
const type_info = @typeInfo(@TypeOf(args));
if (type_info != .@"struct" or !type_info.@"struct".is_tuple)
@compileError("Expected a tuple of GpuBuffers for args. E.g. .{ uniform_buf }");
const fields = type_info.@"struct".fields;
if (fields.len != self.def.bindings.len)
return error.InvalidArgumentCount;
var entries_buf: [32]c.WGPUBindGroupEntry = undefined;
inline for (fields, 0..) |field, i| {
const buf = @field(args, field.name);
if (@TypeOf(buf) != GpuBuffer) {
@compileError("All arguments in the tuple must be of type GpuBuffer");
}
entries_buf[i] = .{
.binding = @intCast(i),
.buffer = buf.raw,
.offset = 0,
.size = buf.size,
};
}
const entries = entries_buf[0..fields.len];
// Create Render Bind Group from layout
const bgl = c.wgpuRenderPipelineGetBindGroupLayout(self.pip, 0);
defer c.wgpuBindGroupLayoutRelease(bgl);
const bg = c.wgpuDeviceCreateBindGroup(gloc.device.device, &.{
.layout = bgl,
.entries = entries.ptr,
.entryCount = @intCast(entries.len),
}) orelse return error.BindGroup;
defer c.wgpuBindGroupRelease(bg);
// Encode Render Command
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse return error.Encoder;
defer c.wgpuCommandEncoderRelease(enc);
const color_attachment = c.WGPURenderPassColorAttachment{
.view = target_view.raw,
.resolveTarget = null,
.loadOp = c.WGPULoadOp_Clear,
.storeOp = c.WGPUStoreOp_Store,
.clearValue = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 1.0 },
.depthSlice = c.WGPU_DEPTH_SLICE_UNDEFINED,
};
const pass_desc = c.WGPURenderPassDescriptor{
.colorAttachmentCount = 1,
.colorAttachments = &color_attachment,
.depthStencilAttachment = null,
};
const pass = c.wgpuCommandEncoderBeginRenderPass(enc, &pass_desc);
c.wgpuRenderPassEncoderSetPipeline(pass, self.pip);
if (fields.len > 0) {
c.wgpuRenderPassEncoderSetBindGroup(pass, 0, bg, 0, null);
}
// Draw! (Instead of Compute Dispatch)
c.wgpuRenderPassEncoderDraw(pass, vertex_count, 1, 0, 0);
c.wgpuRenderPassEncoderEnd(pass);
c.wgpuRenderPassEncoderRelease(pass);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
}
+189
View File
@@ -0,0 +1,189 @@
const std = @import("std");
const c = @import("utils.zig").c;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const GpuTextureUsage = @import("lib.zig").GpuTextureUsage;
pub const GpuTextureDef = struct {
label: ?[]const u8 = null,
size: c.WGPUExtent3D,
usage: std.EnumSet(GpuTextureUsage),
format: GpuTextureFormat,
};
raw: c.WGPUTexture,
gloc: GpuAllocator,
def: GpuTextureDef,
pub fn init(gloc: GpuAllocator, def: GpuTextureDef) !@This() {
var use: u64 = 0;
var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag);
const desc = c.WGPUTextureDescriptor{
.label = svOpt(def.label),
.usage = use,
.dimension = c.WGPUTextureDimension_2D,
.size = def.size,
.format = @intFromEnum(def.format),
.mipLevelCount = 1,
.sampleCount = 1,
};
const raw = try gloc.allocTexture(desc);
return .{ .gloc = gloc, .raw = raw, .def = def };
}
pub fn deinit(self: @This()) void {
self.gloc.freeTexture(self.raw);
}
pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque {
return c.wgpuBufferGetConstMappedRange(self.raw, offset, size);
}
pub fn bytesSize(self: @This()) u32 {
return self.bytesSizeRow() * self.def.size.height;
}
pub fn bytesSizeRow(self: @This()) u32 {
return self.def.size.width * self.def.format.bytesPerPixel();
}
/// Return a GpuBuffer containing a copy of the texture.
pub fn buffCopy(self: @This(), gloc: GpuAllocator) !GpuBuffer {
const buf = try GpuBuffer.init(gloc, .{
.size = self.bytesSize(),
.usage = .initMany(&.{ .CopyDst, .CopySrc }),
.label = "texture_copy_buffer",
});
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse return error.Encoder;
defer c.wgpuCommandEncoderRelease(enc);
const src_copy = c.WGPUTexelCopyTextureInfo{
.texture = self.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
};
const dst_copy = c.WGPUTexelCopyBufferInfo{
.buffer = buf.raw,
.layout = .{
.offset = 0,
.bytesPerRow = self.bytesSizeRow(),
.rowsPerImage = self.def.size.height,
},
};
c.wgpuCommandEncoderCopyTextureToBuffer(enc, &src_copy, &dst_copy, &self.def.size);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
return buf;
}
pub fn mapAsync(
self: @This(),
mode: c.WGPUMapMode,
offset: u64,
size: u64,
callback_info: c.WGPUBufferMapCallbackInfo,
) void {
_ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info);
}
pub fn unmap(self: @This()) void {
c.wgpuBufferUnmap(self.raw);
}
/// CPU to GPU
pub fn load(
self: @This(),
T: type,
data: []const T,
) !void {
const bytes = data.len * @sizeOf(T);
c.wgpuQueueWriteTexture(
self.gloc.device.queue,
&.{
.texture = self.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
},
data.ptr,
bytes,
&.{
.offset = 0,
.bytesPerRow = self.bytesSizeRow(),
.rowsPerImage = self.def.size.height,
},
&self.def.size,
);
}
// GPU to CPU
pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T {
const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T)));
const staging = try init(self.gloc, .{
.size = self.size,
.usage = .initMany(&.{ .MapRead, .CopyDst }),
.label = "texture_read_staging",
});
defer staging.deinit();
const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder;
const src_copy = c.WGPUTexelCopyTextureInfo{
.texture = self.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
};
const dst_copy = c.WGPUTexelCopyBufferInfo{
.buffer = staging.raw,
.layout = .{
.offset = 0,
.bytesPerRow = self.bytesSizeRow(),
.rowsPerImage = self.def.size.height,
},
};
c.wgpuCommandEncoderCopyTextureToBuffer(enc, &src_copy, &dst_copy, &self.def.size);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(self.gloc.device.queue, 1, &cmd);
var mapped = false;
staging.mapAsync(
c.WGPUMapMode_Read,
0,
self.size,
.{ .callback = onMapped, .userdata1 = &mapped },
);
while (!mapped) self.gloc.device.poll();
const ptr: [*]const T = @ptrCast(@alignCast(
staging.getConstMappedRange(0, self.size),
));
@memcpy(out[0..out.len], ptr[0..out.len]);
staging.unmap();
return out;
}
fn onMapped(
status: c.WGPUMapAsyncStatus,
_: c.WGPUStringView,
userdata1: ?*anyopaque,
_: ?*anyopaque,
) callconv(.c) void {
const flag: *bool = @ptrCast(@alignCast(userdata1.?));
flag.* = (status == c.WGPUMapAsyncStatus_Success);
}
+35
View File
@@ -0,0 +1,35 @@
const std = @import("std");
const c = @import("utils.zig").c;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTexture = @import("lib.zig").GpuTexture;
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const GpuTextureUsage = @import("lib.zig").GpuTextureUsage;
pub const GpuViewDef = struct {
label: ?[]const u8 = null,
usage: std.EnumSet(GpuTextureUsage) = .empty,
format: GpuTextureFormat = .Undefined,
};
raw: c.WGPUTextureView,
gloc: GpuAllocator,
pub fn init(gloc: GpuAllocator, texture: GpuTexture, def: GpuViewDef) !@This() {
var use: u64 = 0;
var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag);
const raw = try gloc.allocTextureView(texture.raw, .{
.label = svOpt(def.label),
.format = @intFromEnum(def.format),
.usage = use,
.mipLevelCount = 1,
.arrayLayerCount = 1,
});
return .{ .gloc = gloc, .raw = raw };
}
pub fn deinit(self: @This()) void {
self.gloc.freeTextureView(self.raw);
}
-192
View File
@@ -1,192 +0,0 @@
/// Dummy
const std = @import("std");
const c = @import("c.zig").c;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig");
const GpuDevice = @import("GpuDevice.zig");
const GpuPipeline = @import("GpuPipeline.zig");
const Vec = @This();
buf: GpuBuffer,
len: usize,
pub fn initZero(gloc: *GpuAllocator, len: usize) !Vec {
return .{
.buf = try GpuBuffer.init(
gloc,
len * @sizeOf(f32),
c.WGPUBufferUsage_Storage | c.WGPUBufferUsage_CopyDst | c.WGPUBufferUsage_CopySrc,
),
.len = len,
};
}
pub fn initLoad(gloc: *GpuAllocator, data: []const f32) !Vec {
var self = try initZero(gloc, data.len);
try self.load(gloc.device, data);
return self;
}
pub fn deinit(self: Vec) void {
self.buf.deinit();
}
/// CPU to GPU.
pub fn load(
self: Vec,
device: GpuDevice,
data: []const f32,
) !void {
std.debug.assert(data.len == self.len);
const bytes = data.len * @sizeOf(f32);
c.wgpuQueueWriteBuffer(device.queue, self.buf.raw, 0, data.ptr, bytes);
}
pub fn byteSize(self: Vec) u64 {
return @as(u64, self.len) * @sizeOf(f32);
}
pub fn run(self: Vec, gloc: *GpuAllocator, other: Vec, pip: GpuPipeline) !Vec {
std.debug.assert(self.len == other.len);
const result = try Vec.initZero(gloc, self.len);
errdefer result.deinit();
try dispatch2in1out(gloc, pip.raw, self.buf, other.buf, result.buf, self.byteSize());
return result;
}
/// GPU to CPU.
pub fn read(self: Vec, gloc: *GpuAllocator, alloc: std.mem.Allocator) ![]f32 {
const out = try alloc.alloc(f32, self.len);
const bytes = self.byteSize();
const staging = try GpuBuffer.init(
gloc,
bytes,
c.WGPUBufferUsage_MapRead | c.WGPUBufferUsage_CopyDst,
);
defer staging.deinit();
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse return error.Encoder;
c.wgpuCommandEncoderCopyBufferToBuffer(enc, self.buf.raw, 0, staging.raw, 0, bytes);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
var mapped = false;
staging.mapAsync(
c.WGPUMapMode_Read,
0,
bytes,
.{ .callback = onMapped, .userdata1 = &mapped },
);
while (!mapped) gloc.device.poll();
const ptr: [*]const f32 = @ptrCast(@alignCast(
staging.getConstMappedRange(0, bytes),
));
@memcpy(out[0..self.len], ptr[0..self.len]);
staging.unmap();
return out;
}
fn onMapped(
status: c.WGPUMapAsyncStatus,
_: c.WGPUStringView,
userdata1: ?*anyopaque,
_: ?*anyopaque,
) callconv(.c) void {
const flag: *bool = @ptrCast(@alignCast(userdata1.?));
flag.* = (status == c.WGPUMapAsyncStatus_Success);
}
/// Encode + submit a 2-input, 1-output compute pass (used by add).
fn dispatch2in1out(
gloc: *GpuAllocator,
pipeline: c.WGPUComputePipeline,
buf_a: GpuBuffer,
buf_b: GpuBuffer,
buf_out: GpuBuffer,
bytes: u64,
) !void {
const max_chunk_bytes: u64 = 1024 * 1024 * 1024; // 1 GB
var offset: u64 = 0;
while (offset < bytes) {
// Calculate bounds for the current chunk
const current_chunk_bytes = @min(max_chunk_bytes, bytes - offset);
const current_chunk_elements: u32 = @intCast(current_chunk_bytes / @sizeOf(f32));
// Create uniform buffer for this specific chunk's size
const info_buf = try GpuBuffer.init(
gloc,
@sizeOf(u32),
c.WGPUBufferUsage_Uniform | c.WGPUBufferUsage_CopyDst,
);
defer info_buf.deinit();
// Write the number of elements *in this chunk* to the uniform buffer
c.wgpuQueueWriteBuffer(gloc.device.queue, info_buf.raw, 0, &current_chunk_elements, @sizeOf(u32));
// Bind only the sub-slice for this chunk using `.offset` and `.size`
const entries = [_]c.WGPUBindGroupEntry{
.{ .binding = 0, .buffer = buf_a.raw, .offset = offset, .size = current_chunk_bytes },
.{ .binding = 1, .buffer = buf_b.raw, .offset = offset, .size = current_chunk_bytes },
.{ .binding = 2, .buffer = buf_out.raw, .offset = offset, .size = current_chunk_bytes },
.{ .binding = 3, .buffer = info_buf.raw, .offset = 0, .size = @sizeOf(u32) },
};
// Submit the pass for this specific chunk
try submitPass(gloc, pipeline, &entries, current_chunk_elements);
offset += current_chunk_bytes;
}
}
/// Create bind group, encode pass, submit.
fn submitPass(
gloc: *GpuAllocator,
pipeline: c.WGPUComputePipeline,
entries: []const c.WGPUBindGroupEntry,
n: usize,
) !void {
const bgl = c.wgpuComputePipelineGetBindGroupLayout(pipeline, 0);
defer c.wgpuBindGroupLayoutRelease(bgl);
const bg = c.wgpuDeviceCreateBindGroup(gloc.device.device, &.{
.layout = bgl,
.entries = entries.ptr,
.entryCount = entries.len,
}) orelse return error.BindGroup;
defer c.wgpuBindGroupRelease(bg);
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse
return error.Encoder;
const pass = c.wgpuCommandEncoderBeginComputePass(enc, null);
c.wgpuComputePassEncoderSetPipeline(pass, pipeline);
c.wgpuComputePassEncoderSetBindGroup(pass, 0, bg, 0, null);
const WORKGROUP_SIZE = 256;
const MAX_WORKGROUPS = 65535;
const desired_workgroups = ceilDiv(n, WORKGROUP_SIZE);
const dispatch_count = @min(desired_workgroups, MAX_WORKGROUPS);
c.wgpuComputePassEncoderDispatchWorkgroups(pass, @intCast(dispatch_count), 1, 1);
c.wgpuComputePassEncoderEnd(pass);
c.wgpuComputePassEncoderRelease(pass);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
}
fn ceilDiv(n: usize, d: usize) usize {
return (n + d - 1) / d;
}
-1
View File
@@ -1 +0,0 @@
pub const c = @cImport(@cInclude("wgpu.h"));
+184 -1
View File
@@ -1,4 +1,187 @@
pub const GpuAllocator = @import("GpuAllocator.zig"); pub const GpuAllocator = @import("GpuAllocator.zig");
pub const GpuArenaAllocator = @import("GpuArenaAllocator.zig");
pub const GpuBuffer = @import("GpuBuffer.zig"); pub const GpuBuffer = @import("GpuBuffer.zig");
pub const GpuDevice = @import("GpuDevice.zig"); pub const GpuDevice = @import("GpuDevice.zig");
pub const GpuPipeline = @import("GpuPipeline.zig"); pub const GpuCompute = @import("GpuCompute.zig");
pub const GpuRender = @import("GpuRender.zig");
pub const GpuTexture = @import("GpuTexture.zig");
pub const GpuTextureView = @import("GpuTextureView.zig");
pub const GpuTextureFormat = enum(c_uint) {
Undefined = 0,
R8Unorm = 1,
R8Snorm = 2,
R8Uint = 3,
R8Sint = 4,
R16Unorm = 5,
R16Snorm = 6,
R16Uint = 7,
R16Sint = 8,
R16Float = 9,
RG8Unorm = 10,
RG8Snorm = 11,
RG8Uint = 12,
RG8Sint = 13,
R32Float = 14,
R32Uint = 15,
R32Sint = 16,
RG16Unorm = 17,
RG16Snorm = 18,
RG16Uint = 19,
RG16Sint = 20,
RG16Float = 21,
RGBA8Unorm = 22,
RGBA8UnormSrgb = 23,
RGBA8Snorm = 24,
RGBA8Uint = 25,
RGBA8Sint = 26,
BGRA8Unorm = 27,
BGRA8UnormSrgb = 28,
RGB10A2Uint = 29,
RGB10A2Unorm = 30,
RG11B10Ufloat = 31,
RGB9E5Ufloat = 32,
RG32Float = 33,
RG32Uint = 34,
RG32Sint = 35,
RGBA16Unorm = 36,
RGBA16Snorm = 37,
RGBA16Uint = 38,
RGBA16Sint = 39,
RGBA16Float = 40,
RGBA32Float = 41,
RGBA32Uint = 42,
RGBA32Sint = 43,
Stencil8 = 44,
Depth16Unorm = 45,
Depth24Plus = 46,
Depth24PlusStencil8 = 47,
Depth32Float = 48,
Depth32FloatStencil8 = 49,
BC1RGBAUnorm = 50,
BC1RGBAUnormSrgb = 51,
BC2RGBAUnorm = 52,
BC2RGBAUnormSrgb = 53,
BC3RGBAUnorm = 54,
BC3RGBAUnormSrgb = 55,
BC4RUnorm = 56,
BC4RSnorm = 57,
BC5RGUnorm = 58,
BC5RGSnorm = 59,
BC6HRGBUfloat = 60,
BC6HRGBFloat = 61,
BC7RGBAUnorm = 62,
BC7RGBAUnormSrgb = 63,
ETC2RGB8Unorm = 64,
ETC2RGB8UnormSrgb = 65,
ETC2RGB8A1Unorm = 66,
ETC2RGB8A1UnormSrgb = 67,
ETC2RGBA8Unorm = 68,
ETC2RGBA8UnormSrgb = 69,
EACR11Unorm = 70,
EACR11Snorm = 71,
EACRG11Unorm = 72,
EACRG11Snorm = 73,
ASTC4x4Unorm = 74,
ASTC4x4UnormSrgb = 75,
ASTC5x4Unorm = 76,
ASTC5x4UnormSrgb = 77,
ASTC5x5Unorm = 78,
ASTC5x5UnormSrgb = 79,
ASTC6x5Unorm = 80,
ASTC6x5UnormSrgb = 81,
ASTC6x6Unorm = 82,
ASTC6x6UnormSrgb = 83,
ASTC8x5Unorm = 84,
ASTC8x5UnormSrgb = 85,
ASTC8x6Unorm = 86,
ASTC8x6UnormSrgb = 87,
ASTC8x8Unorm = 88,
ASTC8x8UnormSrgb = 89,
ASTC10x5Unorm = 90,
ASTC10x5UnormSrgb = 91,
ASTC10x6Unorm = 92,
ASTC10x6UnormSrgb = 93,
ASTC10x8Unorm = 94,
ASTC10x8UnormSrgb = 95,
ASTC10x10Unorm = 96,
ASTC10x10UnormSrgb = 97,
ASTC12x10Unorm = 98,
ASTC12x10UnormSrgb = 99,
ASTC12x12Unorm = 100,
ASTC12x12UnormSrgb = 101,
Force32 = 2147483647,
pub fn bytesPerPixel(format: GpuTextureFormat) u32 {
return switch (format) {
// 8-bit formats (1 byte)
.R8Unorm, .R8Snorm, .R8Uint, .R8Sint, .Stencil8 => 1,
// 16-bit formats (2 bytes)
.R16Unorm,
.R16Snorm,
.R16Uint,
.R16Sint,
.R16Float,
.RG8Unorm,
.RG8Snorm,
.RG8Uint,
.RG8Sint,
.Depth16Unorm,
=> 2,
// 32-bit formats (4 bytes)
.R32Float,
.R32Uint,
.R32Sint,
.RG16Unorm,
.RG16Snorm,
.RG16Uint,
.RG16Sint,
.RG16Float,
.RGBA8Unorm,
.RGBA8UnormSrgb,
.RGBA8Snorm,
.RGBA8Uint,
.RGBA8Sint,
.BGRA8Unorm,
.BGRA8UnormSrgb,
.RGB10A2Uint,
.RGB10A2Unorm,
.RG11B10Ufloat,
.RGB9E5Ufloat,
.Depth24Plus,
.Depth32Float,
=> 4,
// 64-bit formats (8 bytes)
.RG32Float,
.RG32Uint,
.RG32Sint,
.RGBA16Unorm,
.RGBA16Snorm,
.RGBA16Uint,
.RGBA16Sint,
.RGBA16Float,
.Depth24PlusStencil8, // 24-bit depth + 8-bit stencil layout padded to 4+4 or 1+3
.Depth32FloatStencil8, // 32-bit float depth + 8-bit stencil (padded to 8 bytes)
=> 8,
// 128-bit formats (16 bytes)
.RGBA32Float, .RGBA32Uint, .RGBA32Sint => 16,
// Block Compressed Formats (Handled separately)
else => 0,
};
}
};
pub const GpuTextureUsage = enum(u64) {
None = 0x0000000000000000,
CopySrc = 0x0000000000000001,
CopyDst = 0x0000000000000002,
TextureBinding = 0x0000000000000004,
StorageBinding = 0x0000000000000008,
RenderAttachment = 0x0000000000000010,
TransientAttachment = 0x0000000000000020,
};
+19
View File
@@ -0,0 +1,19 @@
pub const c = @cImport(@cInclude("wgpu.h"));
pub fn sv(s: []const u8) c.WGPUStringView {
return .{ .data = s.ptr, .length = s.len };
}
/// Allows safely passing an optional Zig string to a WebGPU string view.
pub fn svOpt(s: ?[]const u8) c.WGPUStringView {
if (s) |str| return sv(str);
return .{ .data = null, .length = 0 };
}
/// Helper to print a WGPUStringView in your logs.
pub fn viewStr(view: c.WGPUStringView) []const u8 {
if (view.data != null and view.length > 0) {
return view.data[0..view.length];
}
return "unnamed";
}