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