src/helpers.c
1#include "alba.h"
2#include "internal.h"
3
4#include <stdio.h>
5
6void alba_color_print(const AlbaColor *color) {
7 printf("AlbaColor{%f, %f, %f, %f}\n", color->r, color->g, color->b, color->a);
8}
9
10int alba_color_is_transparent(const AlbaColor *color) {
11 return color->r == 0 && color->g == 0 && color->b == 0 && color->a == 0;
12}
13
14void alba_vector_print(const AlbaVector *vector) {
15 printf("AlbaVector{%f, %f}\n", vector->x, vector->y);
16}
17
18void alba_attribute_print(const AlbaAttribute *attribute) {
19 printf("AlbaAttribute{\n ");
20 alba_color_print(&attribute->color);
21 printf(" ");
22 alba_vector_print(&attribute->uv);
23 printf("}\n");
24}
25
26WGPUBuffer create_buffer(
27 const AlbaWindow *window,
28 const uint64_t size, const void *data,
29 const WGPUBufferUsageFlags flags
30) {
31 WGPUBufferDescriptor buffer_options = {0};
32 buffer_options.usage = WGPUBufferUsage_CopyDst | flags;
33 buffer_options.size = size;
34 const WGPUBuffer buffer = wgpuDeviceCreateBuffer(window->device, &buffer_options);
35 wgpuQueueWriteBuffer(window->queue, buffer, 0, data, size);
36 return buffer;
37}
38
39void release_buffer(const WGPUBuffer buffer) {
40 if (buffer != NULL) {
41 wgpuBufferDestroy(buffer);
42 wgpuBufferRelease(buffer);
43 }
44}
45
46WGPUBuffer update_buffer(
47 const AlbaWindow *window, WGPUBuffer buffer, const WGPUBufferUsage usage, AlbaArray data
48) {
49 // Deallocate old buffer if any
50 release_buffer(buffer);
51 // Copy data to new buffer
52 buffer = create_buffer(window, data.length * data.element_size, data.data, usage);
53 // Clear local copy for next frame
54 alba_array_clear(&data);
55 return buffer;
56}
57
58WGPUTexture create_texture(
59 const AlbaWindow *window,
60 const WGPUTextureUsage usage,
61 const AlbaVector size,
62 const WGPUTextureFormat format,
63 const uint8_t samples,
64 const void *data
65) {
66 WGPUTextureDescriptor texture_options = {0};
67 texture_options.usage = usage;
68 texture_options.format = format;
69 texture_options.dimension = WGPUTextureDimension_2D;
70 texture_options.size.width = size.x;
71 texture_options.size.height = size.y;
72 texture_options.size.depthOrArrayLayers = 1;
73 texture_options.sampleCount = samples;
74 texture_options.mipLevelCount = 1;
75
76 const WGPUTexture texture = wgpuDeviceCreateTexture(window->device, &texture_options);
77
78 if (data != NULL) {
79 const uint64_t bpp = format == WGPUTextureFormat_R8Unorm ? 1 : 4;
80
81 WGPUImageCopyTexture destination = {0};
82 destination.texture = texture;
83 destination.aspect = WGPUTextureAspect_All;
84
85 WGPUTextureDataLayout source = {0};
86 source.bytesPerRow = size.x * bpp;
87 source.rowsPerImage = size.y;
88
89 wgpuQueueWriteTexture(
90 window->queue,
91 &destination, data,
92 size.x * size.y * bpp,
93 &source,
94 &texture_options.size
95 );
96 }
97
98 return texture;
99}
100
101void release_texture(const WGPUTexture texture) {
102 wgpuTextureDestroy(texture);
103 wgpuTextureRelease(texture);
104}