shaderexp: port to new API

This commit is contained in:
iddev5 2022-04-29 18:35:30 +05:30 committed by Stephen Gutekanst
parent 218a6a5c08
commit 7c518f7bd6
2 changed files with 89 additions and 89 deletions

View file

@ -59,19 +59,24 @@ pub fn build(b: *std.build.Builder) void {
example_run_step.dependOn(&example_run_cmd.step); example_run_step.dependOn(&example_run_cmd.step);
} }
//const shaderexp_exe = b.addExecutable("shaderexp", "shaderexp/main.zig"); const shaderexp_app = App.init(
//shaderexp_exe.setTarget(target); b,
//shaderexp_exe.setBuildMode(mode); .{
//shaderexp_exe.addPackage(pkg); .name = "shaderexp",
//shaderexp_exe.addPackage(gpu.pkg); .src = "shaderexp/main.zig",
//shaderexp_exe.addPackage(glfw.pkg); .deps = &.{ glfw.pkg, gpu.pkg, pkg },
//link(b, shaderexp_exe, options); },
//shaderexp_exe.install(); );
const shaderexp_exe = shaderexp_app.step;
shaderexp_exe.setTarget(target);
shaderexp_exe.setBuildMode(mode);
shaderexp_app.link(options);
shaderexp_exe.install();
//const shaderexp_run_cmd = shaderexp_exe.run(); const shaderexp_run_cmd = shaderexp_exe.run();
//shaderexp_run_cmd.step.dependOn(b.getInstallStep()); shaderexp_run_cmd.step.dependOn(b.getInstallStep());
//const shaderexp_run_step = b.step("run-shaderexp", "Run shaderexp"); const shaderexp_run_step = b.step("run-shaderexp", "Run shaderexp");
//shaderexp_run_step.dependOn(&shaderexp_run_cmd.step); shaderexp_run_step.dependOn(&shaderexp_run_cmd.step);
} }
pub const Options = struct { pub const Options = struct {

View file

@ -3,7 +3,7 @@ const mach = @import("mach");
const gpu = @import("gpu"); const gpu = @import("gpu");
const glfw = @import("glfw"); const glfw = @import("glfw");
const App = mach.App(*FrameParams, .{}); const App = @This();
const Vertex = struct { const Vertex = struct {
pos: @Vector(4, f32), pos: @Vector(4, f32),
@ -25,15 +25,21 @@ const UniformBufferObject = struct {
var timer: std.time.Timer = undefined; var timer: std.time.Timer = undefined;
pub fn main() !void { pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
vertex_buffer: gpu.Buffer,
index_buffer: gpu.Buffer,
uniform_buffer: gpu.Buffer,
bind_group: gpu.BindGroup,
fragment_shader_file: std.fs.File,
fragment_shader_code: [:0]const u8,
last_mtime: i128,
pub fn init(app: *App, engine: *mach.Engine) !void {
timer = try std.time.Timer.start(); timer = try std.time.Timer.start();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
const ctx = try allocator.create(FrameParams); engine.core.internal.window.setKeyCallback(struct {
var app = try App.init(allocator, ctx, .{});
app.window.setKeyCallback(struct {
fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void { fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void {
_ = scancode; _ = scancode;
_ = mods; _ = mods;
@ -48,7 +54,7 @@ pub fn main() !void {
// On linux if we don't set a minimum size, you can squish the window to 0 pixels of width and height, // On linux if we don't set a minimum size, you can squish the window to 0 pixels of width and height,
// this makes some strange effects when that happens, so it's better to leave a minimum size to avoid that, // this makes some strange effects when that happens, so it's better to leave a minimum size to avoid that,
// this doesn't prevent you from minimizing the window. // this doesn't prevent you from minimizing the window.
try app.window.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null }); try engine.core.internal.window.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null });
var fragment_file: std.fs.File = undefined; var fragment_file: std.fs.File = undefined;
var last_mtime: i128 = undefined; var last_mtime: i128 = undefined;
@ -64,13 +70,11 @@ pub fn main() !void {
std.debug.print("Something went wrong when attempting to open file: {}\n", .{e}); std.debug.print("Something went wrong when attempting to open file: {}\n", .{e});
return; return;
} }
defer fragment_file.close(); var code = try fragment_file.readToEndAllocOptions(engine.allocator, std.math.maxInt(u16), null, 1, 0);
var code = try fragment_file.readToEndAllocOptions(allocator, std.math.maxInt(u16), null, 1, 0);
defer allocator.free(code);
const queue = app.device.getQueue(); const queue = engine.gpu_driver.device.getQueue();
const vertex_buffer = app.device.createBuffer(&.{ const vertex_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .vertex = true }, .usage = .{ .vertex = true },
.size = @sizeOf(Vertex) * vertices.len, .size = @sizeOf(Vertex) * vertices.len,
.mapped_at_creation = true, .mapped_at_creation = true,
@ -78,9 +82,8 @@ pub fn main() !void {
var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len); var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len);
std.mem.copy(Vertex, vertex_mapped, vertices[0..]); std.mem.copy(Vertex, vertex_mapped, vertices[0..]);
vertex_buffer.unmap(); vertex_buffer.unmap();
defer vertex_buffer.release();
const index_buffer = app.device.createBuffer(&.{ const index_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .index = true }, .usage = .{ .index = true },
.size = @sizeOf(u16) * indices.len, .size = @sizeOf(u16) * indices.len,
.mapped_at_creation = true, .mapped_at_creation = true,
@ -88,20 +91,18 @@ pub fn main() !void {
var index_mapped = index_buffer.getMappedRange(@TypeOf(indices[0]), 0, indices.len); var index_mapped = index_buffer.getMappedRange(@TypeOf(indices[0]), 0, indices.len);
std.mem.copy(u16, index_mapped, indices[0..]); std.mem.copy(u16, index_mapped, indices[0..]);
index_buffer.unmap(); index_buffer.unmap();
defer index_buffer.release();
// We need a bgl to bind the UniformBufferObject, but it is also needed for creating // We need a bgl to bind the UniformBufferObject, but it is also needed for creating
// the RenderPipeline, so we pass it to recreatePipeline as a pointer // the RenderPipeline, so we pass it to recreatePipeline as a pointer
var bgl: gpu.BindGroupLayout = undefined; var bgl: gpu.BindGroupLayout = undefined;
const pipeline = recreatePipeline(&app, code, &bgl); const pipeline = recreatePipeline(engine, code, &bgl);
const uniform_buffer = app.device.createBuffer(&.{ const uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true }, .usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(UniformBufferObject), .size = @sizeOf(UniformBufferObject),
.mapped_at_creation = false, .mapped_at_creation = false,
}); });
defer uniform_buffer.release(); const bind_group = engine.gpu_driver.device.createBindGroup(
const bind_group = app.device.createBindGroup(
&gpu.BindGroup.Descriptor{ &gpu.BindGroup.Descriptor{
.layout = bgl, .layout = bgl,
.entries = &.{ .entries = &.{
@ -109,56 +110,48 @@ pub fn main() !void {
}, },
}, },
); );
defer bind_group.release();
ctx.* = FrameParams{ app.pipeline = pipeline;
.pipeline = pipeline, app.queue = queue;
.queue = queue, app.vertex_buffer = vertex_buffer;
.vertex_buffer = vertex_buffer, app.index_buffer = index_buffer;
.index_buffer = index_buffer, app.uniform_buffer = uniform_buffer;
.uniform_buffer = uniform_buffer, app.bind_group = bind_group;
.bind_group = bind_group,
.fragment_shader_file = fragment_file, app.fragment_shader_file = fragment_file;
.fragment_shader_code = code, app.fragment_shader_code = code;
.last_mtime = last_mtime, app.last_mtime = last_mtime;
};
bgl.release(); bgl.release();
try app.run(.{ .frame = frame });
} }
const FrameParams = struct { pub fn deinit(app: *App, engine: *mach.Engine) void {
pipeline: gpu.RenderPipeline, app.fragment_shader_file.close();
queue: gpu.Queue, engine.allocator.free(app.fragment_shader_code);
vertex_buffer: gpu.Buffer,
index_buffer: gpu.Buffer,
uniform_buffer: gpu.Buffer,
bind_group: gpu.BindGroup,
fragment_shader_file: std.fs.File, app.vertex_buffer.release();
fragment_shader_code: [:0]const u8, app.index_buffer.release();
last_mtime: i128, app.uniform_buffer.release();
}; app.bind_group.release();
}
fn frame(app: *App, params: *FrameParams) !void { pub fn update(app: *App, engine: *mach.Engine) !bool {
if (params.fragment_shader_file.stat()) |stat| { if (app.fragment_shader_file.stat()) |stat| {
if (params.last_mtime < stat.mtime) { if (app.last_mtime < stat.mtime) {
std.log.info("The fragment shader has been changed", .{}); std.log.info("The fragment shader has been changed", .{});
params.last_mtime = stat.mtime; app.last_mtime = stat.mtime;
params.fragment_shader_file.seekTo(0) catch unreachable; app.fragment_shader_file.seekTo(0) catch unreachable;
params.fragment_shader_code = params.fragment_shader_file.readToEndAllocOptions(app.allocator, std.math.maxInt(u32), null, 1, 0) catch |err| { app.fragment_shader_code = app.fragment_shader_file.readToEndAllocOptions(engine.allocator, std.math.maxInt(u32), null, 1, 0) catch |err| {
std.log.err("Err: {}", .{err}); std.log.err("Err: {}", .{err});
return; return false;
}; };
params.pipeline = recreatePipeline(app, params.fragment_shader_code, null); app.pipeline = recreatePipeline(engine, app.fragment_shader_code, null);
} }
} else |err| { } else |err| {
std.log.err("Something went wrong when attempting to stat file: {}\n", .{err}); std.log.err("Something went wrong when attempting to stat file: {}\n", .{err});
} }
const back_buffer_view = app.swap_chain.?.getCurrentTextureView(); const back_buffer_view = engine.gpu_driver.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{ const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view, .view = back_buffer_view,
.resolve_target = null, .resolve_target = null,
@ -167,7 +160,7 @@ fn frame(app: *App, params: *FrameParams) !void {
.store_op = .store, .store_op = .store,
}; };
const encoder = app.device.createCommandEncoder(null); const encoder = engine.gpu_driver.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{ const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment}, .color_attachments = &.{color_attachment},
.depth_stencil_attachment = null, .depth_stencil_attachment = null,
@ -175,16 +168,16 @@ fn frame(app: *App, params: *FrameParams) !void {
const time = @intToFloat(f32, timer.read()) / @as(f32, std.time.ns_per_s); const time = @intToFloat(f32, timer.read()) / @as(f32, std.time.ns_per_s);
const ubo = UniformBufferObject{ const ubo = UniformBufferObject{
.resolution = .{ @intToFloat(f32, app.current_desc.width), @intToFloat(f32, app.current_desc.height) }, .resolution = .{ @intToFloat(f32, engine.gpu_driver.current_desc.width), @intToFloat(f32, engine.gpu_driver.current_desc.height) },
.time = time, .time = time,
}; };
encoder.writeBuffer(params.uniform_buffer, 0, UniformBufferObject, &.{ubo}); encoder.writeBuffer(app.uniform_buffer, 0, UniformBufferObject, &.{ubo});
const pass = encoder.beginRenderPass(&render_pass_info); const pass = encoder.beginRenderPass(&render_pass_info);
pass.setVertexBuffer(0, params.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len); pass.setVertexBuffer(0, app.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len);
pass.setIndexBuffer(params.index_buffer, .uint16, 0, @sizeOf(u16) * indices.len); pass.setIndexBuffer(app.index_buffer, .uint16, 0, @sizeOf(u16) * indices.len);
pass.setPipeline(params.pipeline); pass.setPipeline(app.pipeline);
pass.setBindGroup(0, params.bind_group, &.{0}); pass.setBindGroup(0, app.bind_group, &.{0});
pass.drawIndexed(indices.len, 1, 0, 0, 0); pass.drawIndexed(indices.len, 1, 0, 0, 0);
pass.end(); pass.end();
pass.release(); pass.release();
@ -192,14 +185,16 @@ fn frame(app: *App, params: *FrameParams) !void {
var command = encoder.finish(null); var command = encoder.finish(null);
encoder.release(); encoder.release();
params.queue.submit(&.{command}); app.queue.submit(&.{command});
command.release(); command.release();
app.swap_chain.?.present(); engine.gpu_driver.swap_chain.?.present();
back_buffer_view.release(); back_buffer_view.release();
return true;
} }
fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*gpu.BindGroupLayout) gpu.RenderPipeline { fn recreatePipeline(engine: *mach.Engine, fragment_shader_code: [:0]const u8, bgl: ?*gpu.BindGroupLayout) gpu.RenderPipeline {
const vs_module = app.device.createShaderModule(&.{ const vs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my vertex shader", .label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") }, .code = .{ .wgsl = @embedFile("vert.wgsl") },
}); });
@ -217,14 +212,14 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
// Check wether the fragment shader code compiled successfully, if not // Check wether the fragment shader code compiled successfully, if not
// print the validation layer error and show a black screen // print the validation layer error and show a black screen
app.device.pushErrorScope(.validation); engine.gpu_driver.device.pushErrorScope(.validation);
var fs_module = app.device.createShaderModule(&gpu.ShaderModule.Descriptor{ var fs_module = engine.gpu_driver.device.createShaderModule(&gpu.ShaderModule.Descriptor{
.label = "my fragment shader", .label = "my fragment shader",
.code = .{ .wgsl = fragment_shader_code }, .code = .{ .wgsl = fragment_shader_code },
}); });
var error_occurred: bool = false; var error_occurred: bool = false;
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?) // popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = app.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct { _ = engine.gpu_driver.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct {
fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void { fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .noError) { if (typ != .noError) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message}); std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
@ -233,7 +228,7 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
} }
}.callback)); }.callback));
if (error_occurred) { if (error_occurred) {
fs_module = app.device.createShaderModule(&gpu.ShaderModule.Descriptor{ fs_module = engine.gpu_driver.device.createShaderModule(&gpu.ShaderModule.Descriptor{
.label = "my fragment shader", .label = "my fragment shader",
.code = .{ .wgsl = @embedFile("black_screen_frag.wgsl") }, .code = .{ .wgsl = @embedFile("black_screen_frag.wgsl") },
}); });
@ -253,7 +248,7 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
}, },
}; };
const color_target = gpu.ColorTargetState{ const color_target = gpu.ColorTargetState{
.format = app.swap_chain_format, .format = engine.gpu_driver.swap_chain_format,
.blend = &blend, .blend = &blend,
.write_mask = gpu.ColorWriteMask.all, .write_mask = gpu.ColorWriteMask.all,
}; };
@ -266,7 +261,7 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .fragment = true }, .uniform, true, 0); const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .fragment = true }, .uniform, true, 0);
// bgl is needed outside, for the creation of the uniform_buffer in main // bgl is needed outside, for the creation of the uniform_buffer in main
const bgl_tmp = app.device.createBindGroupLayout( const bgl_tmp = engine.gpu_driver.device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor{ &gpu.BindGroupLayout.Descriptor{
.entries = &.{bgle}, .entries = &.{bgle},
}, },
@ -281,7 +276,7 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
} }
const bind_group_layouts = [_]gpu.BindGroupLayout{bgl_tmp}; const bind_group_layouts = [_]gpu.BindGroupLayout{bgl_tmp};
const pipeline_layout = app.device.createPipelineLayout(&.{ const pipeline_layout = engine.gpu_driver.device.createPipelineLayout(&.{
.bind_group_layouts = &bind_group_layouts, .bind_group_layouts = &bind_group_layouts,
}); });
defer pipeline_layout.release(); defer pipeline_layout.release();
@ -310,10 +305,10 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
// Create the render pipeline. Even if the shader compilation succeeded, this could fail if the // Create the render pipeline. Even if the shader compilation succeeded, this could fail if the
// shader is missing a `main` entrypoint. // shader is missing a `main` entrypoint.
app.device.pushErrorScope(.validation); engine.gpu_driver.device.pushErrorScope(.validation);
const pipeline = app.device.createRenderPipeline(&pipeline_descriptor); const pipeline = engine.gpu_driver.device.createRenderPipeline(&pipeline_descriptor);
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?) // popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = app.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct { _ = engine.gpu_driver.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct {
fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void { fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .noError) { if (typ != .noError) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message}); std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
@ -323,7 +318,7 @@ fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*
}.callback)); }.callback));
if (error_occurred) { if (error_occurred) {
// Retry with black_screen_frag which we know will work. // Retry with black_screen_frag which we know will work.
return recreatePipeline(app, @embedFile("black_screen_frag.wgsl"), bgl); return recreatePipeline(engine, @embedFile("black_screen_frag.wgsl"), bgl);
} }
return pipeline; return pipeline;
} }