1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
|
//! pardes's cell renderer on SDL_GPU: the shaders' instance ABI
//! (src/gpu/shaders/*.glsl), the pipelines over it, the glyph atlas's
//! texture and its upload, the pictures' textures and their draws, the
//! overlay's triangles, a frame's uploads and its render pass, and the
//! resource helpers, moved from pardes's
//! gui.zig as they were. `c` is the embedder's own SDL translation (pardes's:
//! SDL3 and font.h), so the embedder's SDL is the one linked; the SPIR-V is
//! the build's (`<name>.spv` imports, from src/gpu/shaders/).
const std = @import("std");
const c = @import("c");
const Atlas = @import("font_atlas");
const Cells = @This();
/// The embedder's device (Present's), which everything here is made on.
device: *c.SDL_GPUDevice,
/// What every pipeline draws into: the swapchain's format.
format: c.SDL_GPUTextureFormat,
pipeline: *c.SDL_GPUGraphicsPipeline,
decor_pipeline: *c.SDL_GPUGraphicsPipeline,
overlay_pipeline: *c.SDL_GPUGraphicsPipeline,
image_pipeline: *c.SDL_GPUGraphicsPipeline,
/// Premultiplied pictures' (an addon's), made on first use
/// (makeAddonPipeline).
addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null,
atlas_tex: *c.SDL_GPUTexture,
atlas_sampler: *c.SDL_GPUSampler,
linear_sampler: *c.SDL_GPUSampler,
atlas_xfer: *c.SDL_GPUTransferBuffer,
vbuf: ?*c.SDL_GPUBuffer = null,
vxfer: ?*c.SDL_GPUTransferBuffer = null,
vbuf_cells: u32 = 0,
overlay_vbuf: *c.SDL_GPUBuffer,
overlay_vxfer: *c.SDL_GPUTransferBuffer,
image_vbuf: ?*c.SDL_GPUBuffer = null,
image_vxfer: ?*c.SDL_GPUTransferBuffer = null,
image_capacity: u32 = 0,
/// The textures of the pictures shown, by key (image).
native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty,
/// The frame's pictures, instance by instance (mapImages, drawImages).
images: std.ArrayListUnmanaged(ImageDraw) = .empty,
const vert_spv = @embedFile("ui.vert.spv");
const frag_spv = @embedFile("ui.frag.spv");
const decor_frag_spv = @embedFile("decor.frag.spv");
const overlay_vert_spv = @embedFile("overlay.vert.spv");
const overlay_frag_spv = @embedFile("overlay.frag.spv");
const image_vert_spv = @embedFile("image.vert.spv");
const image_frag_spv = @embedFile("image.frag.spv");
/// The atlas's texture, sampler and upload buffer, the pictures' sampler,
/// the four pipelines drawing into `swapchain_format`, and the overlay's
/// buffers, `max_overlay_vertices` long, made on `device`.
pub fn init(device: *c.SDL_GPUDevice, swapchain_format: c.SDL_GPUTextureFormat, max_overlay_vertices: usize) !Cells {
const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, Atlas.atlas_w, Atlas.atlas_h) orelse return error.GpuCreate;
var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo);
samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST;
samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST;
samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST;
samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR;
samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR;
samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR;
const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = Atlas.atlas_w * Atlas.atlas_h, .props = 0 };
const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate;
const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState));
const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend());
const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend());
const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend());
const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex));
var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 };
const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate;
var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 };
const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate;
return .{
.device = device,
.format = swapchain_format,
.pipeline = pipeline,
.decor_pipeline = decor_pipeline,
.overlay_pipeline = overlay_pipeline,
.image_pipeline = image_pipeline,
.atlas_tex = atlas_tex,
.atlas_sampler = atlas_sampler,
.linear_sampler = linear_sampler,
.atlas_xfer = atlas_xfer,
.overlay_vbuf = overlay_vbuf,
.overlay_vxfer = overlay_vxfer,
};
}
/// The pipelines, textures and buffers, whatever they were regrown to, and
/// the pictures' textures let go (the device stays: Present's).
pub fn deinit(cells: *Cells, gpa: std.mem.Allocator) void {
const device = cells.device;
c.SDL_ReleaseGPUGraphicsPipeline(device, cells.image_pipeline);
if (cells.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_);
cells.clearImages();
cells.native_images.deinit(gpa);
cells.images.deinit(gpa);
c.SDL_ReleaseGPUGraphicsPipeline(device, cells.pipeline);
c.SDL_ReleaseGPUGraphicsPipeline(device, cells.decor_pipeline);
c.SDL_ReleaseGPUGraphicsPipeline(device, cells.overlay_pipeline);
c.SDL_ReleaseGPUTexture(device, cells.atlas_tex);
c.SDL_ReleaseGPUSampler(device, cells.atlas_sampler);
c.SDL_ReleaseGPUSampler(device, cells.linear_sampler);
c.SDL_ReleaseGPUTransferBuffer(device, cells.atlas_xfer);
c.SDL_ReleaseGPUBuffer(device, cells.overlay_vbuf);
c.SDL_ReleaseGPUTransferBuffer(device, cells.overlay_vxfer);
if (cells.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
if (cells.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
if (cells.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
if (cells.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
}
/// The pipeline of premultiplied pictures (an addon's GPU scene), made the
/// first time one is drawn.
pub fn makeAddonPipeline(cells: *Cells) !void {
if (cells.addon_pipeline != null) return;
var blend = backgroundLayerBlend();
blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
cells.addon_pipeline = try makePipeline(cells.device, cells.format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend);
}
/// What one group draws, in this order: its cells, its images, then its
/// decor.
pub const Group = struct {
cell_start: u32 = 0,
cell_count: u32 = 0,
image_start: u32 = 0,
image_count: u32 = 0,
decor_start: u32 = 0,
decor_count: u32 = 0,
};
/// The frame's command buffer: null when the device gives none.
pub fn begin(cells: *Cells) ?*c.SDL_GPUCommandBuffer {
return c.SDL_AcquireGPUCommandBuffer(cells.device);
}
/// A frame given up: what it recorded so far is submitted, nothing drawn.
pub fn submit(cmd: *c.SDL_GPUCommandBuffer) void {
_ = c.SDL_SubmitGPUCommandBuffer(cmd);
}
/// The frame's cell and decor instances, room for `n`, mapped for the
/// caller to write; uploadCells sends them. Null when the buffer will not
/// map.
pub fn mapCells(cells: *Cells, n: u32) !?[*]CellInstance {
try growInstances(cells.device, &cells.vbuf, &cells.vxfer, &cells.vbuf_cells, n, @sizeOf(CellInstance));
const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, cells.vxfer.?, false) orelse return null);
return @ptrCast(@alignCast(vptr));
}
/// The first `n` instances mapCells gave, sent after the atlas's rows drawn
/// since the last upload (uploadAtlas).
pub fn uploadCells(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, n: u32, atlas: *Atlas) void {
c.SDL_UnmapGPUTransferBuffer(cells.device, cells.vxfer.?);
if (atlas.atlas_dirty_top < atlas.atlas_dirty_bottom) cells.uploadAtlas(cmd, atlas);
const copy = c.SDL_BeginGPUCopyPass(cmd);
const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.vxfer.?, .offset = 0 };
const dst = c.SDL_GPUBufferRegion{ .buffer = cells.vbuf.?, .offset = 0, .size = n * @sizeOf(CellInstance) };
c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
c.SDL_EndGPUCopyPass(copy);
}
/// The frame's render pass into `target`, `sw` by `sh`, cleared to `clear`:
/// group by group, bottom to top, its cells (the first group's followed by
/// a scroll's `shifted` rows, after the `cell_total` instances, clipped to
/// `scroll_clip`), its pictures and its decor (after the shifted rows), at
/// the layer opacity `opacity`, the `ink` group's decor at 1; then the
/// overlay's first `overlay_count` vertices.
pub fn record(
cells: *Cells,
cmd: *c.SDL_GPUCommandBuffer,
target: *c.SDL_GPUTexture,
sw: u32,
sh: u32,
clear: c.SDL_FColor,
opacity: f32,
groups: []const Group,
ink: usize,
cell_total: u32,
shifted: u32,
scroll_clip: c.SDL_Rect,
overlay_count: u32,
) void {
var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo);
color_target.texture = target;
color_target.clear_color = clear;
color_target.load_op = c.SDL_GPU_LOADOP_CLEAR;
color_target.store_op = c.SDL_GPU_STOREOP_STORE;
const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null);
pushLayerOpacity(cmd, rp, opacity);
const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) };
const decor_base = cell_total + shifted;
for (groups, 0..) |group, index| {
const has_shifted = index == 0 and shifted != 0;
if ((group.cell_count != 0 or has_shifted) and cells.vbuf != null) {
c.SDL_BindGPUGraphicsPipeline(rp, cells.pipeline);
const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = cells.atlas_tex, .sampler = cells.atlas_sampler };
c.SDL_BindGPUFragmentSamplers(rp, 0, &samp_binding, 1);
if (group.cell_count != 0) {
const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = group.cell_start * @sizeOf(CellInstance) };
c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
c.SDL_DrawGPUPrimitives(rp, 6, group.cell_count, 0, 0);
}
if (has_shifted) {
c.SDL_SetGPUScissor(rp, &scroll_clip);
const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = cell_total * @sizeOf(CellInstance) };
c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
c.SDL_DrawGPUPrimitives(rp, 6, shifted, 0, 0);
c.SDL_SetGPUScissor(rp, &whole);
}
}
if (group.image_count != 0) cells.drawImages(rp, group.image_start, group.image_count, whole);
if (group.decor_count != 0 and cells.vbuf != null) {
c.SDL_BindGPUGraphicsPipeline(rp, cells.decor_pipeline);
// Ink keeps its colour at any WindowOpacity.
pushLayerOpacity(cmd, rp, if (index == ink) 1 else opacity);
const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = (decor_base + group.decor_start) * @sizeOf(CellInstance) };
c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
c.SDL_DrawGPUPrimitives(rp, 6, group.decor_count, 0, 0);
}
}
cells.drawOverlay(cmd, rp, overlay_count, opacity);
c.SDL_EndGPURenderPass(rp);
}
/// Uploads only the atlas rows drawn into since the last upload. Glyphs fill
/// the atlas pen-style, a band of rows at a time, so new glyphs are a band a
/// cell or two tall, not the whole 4 MB texture. The band sits at the same
/// offset in the transfer buffer as in the stage, and the texture keeps the
/// rows outside it.
fn uploadAtlas(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, atlas: *Atlas) void {
const atlas_w = Atlas.atlas_w;
const top = atlas.atlas_dirty_top;
const rows = atlas.atlas_dirty_bottom - top;
const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.atlas_xfer, false) orelse return;
const dst: [*]u8 = @ptrCast(ptr);
@memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], atlas.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]);
c.SDL_UnmapGPUTransferBuffer(cells.device, cells.atlas_xfer);
const copy = c.SDL_BeginGPUCopyPass(cmd);
const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = cells.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows };
const dstregion = c.SDL_GPUTextureRegion{ .texture = cells.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 };
c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false);
c.SDL_EndGPUCopyPass(copy);
atlas.atlas_dirty_top = Atlas.atlas_h;
atlas.atlas_dirty_bottom = 0;
}
/// A picture of the frame: its texture (one of `native_images`, or the
/// caller's, borrowed: an addon's, premultiplied) and the target rectangle
/// it is clipped to.
pub const ImageDraw = struct {
premultiplied: bool = false,
texture: *c.SDL_GPUTexture,
clip: c.SDL_Rect,
};
/// Rows of a picture that alone differ from the picture under the key
/// `from` (image).
pub const Dirty = struct { from: u64, y: u32, h: u32 };
pub fn releaseImage(cells: *Cells, key: u64) void {
if (cells.native_images.fetchRemove(key)) |removed|
c.SDL_ReleaseGPUTexture(cells.device, removed.value);
}
pub fn clearImages(cells: *Cells) void {
var iterator = cells.native_images.valueIterator();
while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(cells.device, texture.*);
cells.native_images.clearRetainingCapacity();
}
/// The texture of the picture `key`, `w` by `h` RGBA pixels in `rgba`, a
/// row `stride` bytes: uploaded unless it is held already, or, where
/// `dirty_rows` names a picture held, only those rows written into that
/// picture's texture, which takes the new key.
pub fn image(
cells: *Cells,
gpa: std.mem.Allocator,
cmd: *c.SDL_GPUCommandBuffer,
key: u64,
rgba: []const u8,
w: u32,
h: u32,
stride: u32,
dirty_rows: ?Dirty,
) !void {
if (cells.native_images.contains(key)) return;
const row = stride;
if (dirty_rows) |dirty| dirty: {
// The core changed only these rows since a picture we still hold:
// write them into that texture rather than sending the whole page.
if (dirty.y + dirty.h > h) break :dirty;
const texture = cells.native_images.get(dirty.from) orelse break :dirty;
try uploadTextureRows(cells, cmd, texture, rgba[dirty.y * row ..][0 .. dirty.h * row], w, dirty.y, dirty.h);
try cells.native_images.put(gpa, key, texture);
_ = cells.native_images.remove(dirty.from);
return;
}
const texture = texture2d(cells.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, w, h) orelse return error.GpuCreate;
errdefer c.SDL_ReleaseGPUTexture(cells.device, texture);
try uploadTextureRows(cells, cmd, texture, rgba, w, 0, h);
try cells.native_images.put(gpa, key, texture);
}
/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`.
fn uploadTextureRows(
cells: *Cells,
cmd: *c.SDL_GPUCommandBuffer,
texture: *c.SDL_GPUTexture,
rgba: []const u8,
width: usize,
y: usize,
rows: usize,
) !void {
var xf_info = c.SDL_GPUTransferBufferCreateInfo{
.usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
.size = @intCast(rgba.len),
.props = 0,
};
const transfer = c.SDL_CreateGPUTransferBuffer(cells.device, &xf_info) orelse return error.GpuCreate;
defer c.SDL_ReleaseGPUTransferBuffer(cells.device, transfer);
const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, transfer, false) orelse return error.GpuMap);
@memcpy(mapped[0..rgba.len], rgba);
c.SDL_UnmapGPUTransferBuffer(cells.device, transfer);
const copy = c.SDL_BeginGPUCopyPass(cmd);
const src = c.SDL_GPUTextureTransferInfo{
.transfer_buffer = transfer,
.offset = 0,
.pixels_per_row = @intCast(width),
.rows_per_layer = @intCast(rows),
};
const dst = c.SDL_GPUTextureRegion{
.texture = texture,
.mip_level = 0,
.layer = 0,
.x = 0,
.y = @intCast(y),
.z = 0,
.w = @intCast(width),
.h = @intCast(rows),
.d = 1,
};
c.SDL_UploadToGPUTexture(copy, &src, &dst, false);
c.SDL_EndGPUCopyPass(copy);
}
/// The frame's `n` picture instances, mapped for the caller to write, and
/// `images` emptied with room for as many draws; uploadImages sends them.
/// Null when the buffers will not grow or map.
pub fn mapImages(cells: *Cells, gpa: std.mem.Allocator, n: u32) ?[*]ImageInstance {
growInstances(cells.device, &cells.image_vbuf, &cells.image_vxfer, &cells.image_capacity, n, @sizeOf(ImageInstance)) catch return null;
cells.images.clearRetainingCapacity();
cells.images.ensureTotalCapacity(gpa, n) catch return null;
const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, cells.image_vxfer.?, false) orelse return null);
return @ptrCast(@alignCast(ptr));
}
/// The first `n` instances mapImages gave, sent.
pub fn uploadImages(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, n: u32) void {
c.SDL_UnmapGPUTransferBuffer(cells.device, cells.image_vxfer.?);
const copy = c.SDL_BeginGPUCopyPass(cmd);
const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.image_vxfer.?, .offset = 0 };
const dst = c.SDL_GPUBufferRegion{ .buffer = cells.image_vbuf.?, .offset = 0, .size = n * @sizeOf(ImageInstance) };
c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
c.SDL_EndGPUCopyPass(copy);
}
/// Draws `count` of the frame's pictures from `start`, each clipped to its
/// rectangle; the scissor is the whole target, `whole`, after.
fn drawImages(cells: *Cells, rp: ?*c.SDL_GPURenderPass, start: u32, count: u32, whole: c.SDL_Rect) void {
const pass = rp orelse return;
c.SDL_BindGPUGraphicsPipeline(pass, cells.image_pipeline);
var idx = start;
const end = start + count;
for (cells.images.items[start..end]) |prepared| {
c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) cells.addon_pipeline.? else cells.image_pipeline);
const clip = prepared.clip;
if (clip.w > 0 and clip.h > 0) {
c.SDL_SetGPUScissor(pass, &clip);
const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = cells.linear_sampler };
c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1);
const binding = c.SDL_GPUBufferBinding{ .buffer = cells.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) };
c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0);
}
idx += 1;
}
std.debug.assert(idx == start + count);
// Back to the whole target: what draws after a picture may run on past
// the grid, as a rule and a band do.
c.SDL_SetGPUScissor(pass, &whole);
}
/// The overlay's triangles, `vertices`, sent.
pub fn uploadOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, vertices: []const OverlayVertex) bool {
const vertex_count: u32 = @intCast(vertices.len);
const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex);
const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.overlay_vxfer, false) orelse return false;
const dst: [*]u8 = @ptrCast(ptr);
const src: [*]const u8 = @ptrCast(vertices.ptr);
@memcpy(dst[0..byte_len], src[0..byte_len]);
c.SDL_UnmapGPUTransferBuffer(cells.device, cells.overlay_vxfer);
const copy = c.SDL_BeginGPUCopyPass(cmd);
const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.overlay_vxfer, .offset = 0 };
const dst_region = c.SDL_GPUBufferRegion{ .buffer = cells.overlay_vbuf, .offset = 0, .size = byte_len };
c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false);
c.SDL_EndGPUCopyPass(copy);
return true;
}
fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void {
const uniforms = [4]f32{ opacity, 0, 0, 0 };
c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms)));
// The source alpha is geometric/image coverage, not window opacity. Its
// alpha contribution is multiplied by this constant separately, so a
// rail repainted over a gutter still has alpha p, not p + p*(1-p).
c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity });
}
/// The overlay's first `vertex_count` vertices (uploadOverlay), drawn at
/// the layer opacity `opacity`.
fn drawOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32, opacity: f32) void {
if (vertex_count == 0) return;
const pass = rp orelse return;
c.SDL_BindGPUGraphicsPipeline(pass, cells.overlay_pipeline);
const binding = c.SDL_GPUBufferBinding{ .buffer = cells.overlay_vbuf, .offset = 0 };
c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
pushLayerOpacity(cmd, pass, opacity);
c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0);
}
pub const CellInstance = extern struct {
x0: f32,
y0: f32,
x1: f32,
y1: f32,
u0: f32,
v0: f32,
u1: f32,
v1: f32,
fr: f32,
fg: f32,
fb: f32,
br: f32,
bg: f32,
bb: f32,
/// The flags (the high bits, ui.vert.glsl).
effect: u32 = 0,
/// A clip rectangle in target pixels; x1 < x0 is none (ui.vert.glsl).
clip_x0: f32 = 0,
clip_y0: f32 = 0,
clip_x1: f32 = -1,
clip_y1: f32 = -1,
};
pub const OverlayVertex = extern struct {
x: f32,
y: f32,
r: f32,
g: f32,
b: f32,
a: f32,
};
pub const ImageInstance = extern struct {
x0: f32,
y0: f32,
x1: f32,
y1: f32,
u0: f32,
v0: f32,
u1: f32,
v1: f32,
};
pub const opaque_bg_bit: u32 = 0x2000_0000;
/// A vertex buffer and its upload buffer holding at least `needed`
/// elements of `stride` bytes: those there when they do, else twice as
/// many again until they would (the old ones let go).
pub fn growInstances(device: *c.SDL_GPUDevice, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void {
if (needed <= capacity.* and buffer.* != null and transfer.* != null) return;
var grown = @max(@as(u32, 1), capacity.*);
while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity;
const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity;
var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 };
const next_buffer = c.SDL_CreateGPUBuffer(device, &vb_info) orelse return error.GpuCreate;
errdefer c.SDL_ReleaseGPUBuffer(device, next_buffer);
var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 };
const next_transfer = c.SDL_CreateGPUTransferBuffer(device, &xf_info) orelse return error.GpuCreate;
if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(device, old);
if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(device, old);
buffer.* = next_buffer;
transfer.* = next_transfer;
capacity.* = grown;
}
/// One vertex buffer of a pipeline: `pitch` bytes an element, read per
/// vertex or per instance through `attrs`.
pub const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute };
/// The cells' and the decor's instances (ui.vert.glsl).
pub const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
.{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") },
.{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") },
.{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") },
.{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") },
.{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") },
.{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") },
} };
pub const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{
.{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") },
.{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") },
} };
pub const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
.{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") },
.{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") },
} };
/// A pipeline drawing triangles into `color_format`: `vert`, and `frag`
/// with its samplers and uniform buffers, over one vertex buffer of
/// `input` (none: the post chain's triangle over the whole frame).
pub fn makePipeline(
device: *c.SDL_GPUDevice,
color_format: c.SDL_GPUTextureFormat,
vert: []const u8,
frag: []const u8,
samplers: u32,
uniforms: u32,
input: ?VertexInput,
blend: c.SDL_GPUColorTargetBlendState,
) !*c.SDL_GPUGraphicsPipeline {
const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
defer c.SDL_ReleaseGPUShader(device, vs);
const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms);
defer c.SDL_ReleaseGPUShader(device, fs);
var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend };
var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined;
var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo);
info.vertex_shader = vs;
info.fragment_shader = fs;
info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
if (input) |in| {
vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 };
info.vertex_input_state = .{
.vertex_buffer_descriptions = &vbuf_desc,
.num_vertex_buffers = 1,
.vertex_attributes = in.attrs.ptr,
.num_vertex_attributes = @intCast(in.attrs.len),
};
}
info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL;
info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE;
info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 };
return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate;
}
pub fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState {
var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState);
blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA;
blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD;
blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR;
blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD;
blend.enable_blend = true;
return blend;
}
fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader {
var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo);
info.code = code.ptr;
info.code_size = code.len;
info.entrypoint = "main";
info.format = c.SDL_GPU_SHADERFORMAT_SPIRV;
info.stage = stage;
info.num_samplers = n_samplers;
info.num_uniform_buffers = n_uniform_buffers;
return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate;
}
/// A 2D texture of one level, one layer and one sample.
pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture {
var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo);
info.type = c.SDL_GPU_TEXTURETYPE_2D;
info.format = format;
info.usage = usage;
info.width = width;
info.height = height;
info.layer_count_or_depth = 1;
info.num_levels = 1;
info.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
return c.SDL_CreateGPUTexture(device, &info);
}
test "the shader instance ABI: the flags after the colours, the clip after them" {
try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance));
try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect"));
try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0"));
try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance));
}
|