-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.c
More file actions
408 lines (349 loc) ยท 12.8 KB
/
main.c
File metadata and controls
408 lines (349 loc) ยท 12.8 KB
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
#include <stdio.h>
#include <stdbool.h>
#include <string.h> // strlen
// emscripten
#include "emscripten.h"
#include "emscripten/html5.h"
#include "webgpu/webgpu.h"
//--------------------------------------------------
// defines
//--------------------------------------------------
#define SHADER_SOURCE(...) #__VA_ARGS__
//--------------------------------------------------
// structs
//--------------------------------------------------
// global state
typedef struct state_t {
// canvas
struct {
const char* name;
int width, height;
} canvas;
// wgpu
struct {
WGPUInstance instance;
WGPUDevice device;
WGPUQueue queue;
WGPUSurface surface;
WGPURenderPipeline pipeline;
} wgpu;
// resources
struct {
WGPUBuffer vbuffer, ibuffer, ubuffer;
WGPUBindGroup bindgroup;
} res;
// vars
struct {
float rot;
} var;
} state_t;
// state
static state_t state;
//--------------------------------------------------
// callbacks and functions
//--------------------------------------------------
// callbacks
static int resize(int, const EmscriptenUiEvent*, void*);
static void frame();
// helper functions
static void create_surface();
static WGPUShaderModule create_shader(const char* code, const char* label);
static WGPUBuffer create_buffer(const void* data, size_t size, WGPUBufferUsage usage);
static WGPUStringView make_stringview(const char* str);
//--------------------------------------------------
// vertex and fragment shaders
//--------------------------------------------------
// triangle shader
static const char* wgsl_triangle = SHADER_SOURCE(
// attribute/uniform decls
struct VertexIn {
@location(0) aPos : vec2<f32>,
@location(1) aCol : vec3<f32>,
};
struct VertexOut {
@location(0) vCol : vec3<f32>,
@builtin(position) Position : vec4<f32>,
};
struct Rotation {
@location(0) degs : f32,
};
@group(0) @binding(0) var<uniform> uRot : Rotation;
// vertex shader
@vertex
fn vs_main(input : VertexIn) -> VertexOut {
var rads : f32 = radians(uRot.degs);
var cosA : f32 = cos(rads);
var sinA : f32 = sin(rads);
var rot : mat3x3<f32> = mat3x3<f32>(
vec3<f32>( cosA, sinA, 0.0),
vec3<f32>(-sinA, cosA, 0.0),
vec3<f32>( 0.0, 0.0, 1.0));
var output : VertexOut;
output.Position = vec4<f32>(rot * vec3<f32>(input.aPos, 1.0), 1.0);
output.vCol = input.aCol;
return output;
}
// fragment shader
@fragment
fn fs_main(@location(0) vCol : vec3<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(vCol, 1.0);
}
);
//--------------------------------------------------
//
// main
//
//--------------------------------------------------
int main(int argc, const char* argv[]) {
(void)argc, (void)argv; // unused
//-----------------
// init
//-----------------
state.canvas.name = "canvas";
state.wgpu.instance = wgpuCreateInstance(NULL);
state.wgpu.device = emscripten_webgpu_get_device();
state.wgpu.queue = wgpuDeviceGetQueue(state.wgpu.device);
resize(0, NULL, NULL); // set size and create surface
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, false, (em_ui_callback_func)resize);
//-----------------
// setup pipeline
//-----------------
// compile shaders
WGPUShaderModule shader_triangle = create_shader(wgsl_triangle, NULL);
// describe buffer layouts
WGPUVertexAttribute vertex_attributes[2] = {
// position: x, y
[0] = {
.format = WGPUVertexFormat_Float32x2,
.offset = 0,
.shaderLocation = 0,
},
// color: r, g, b
[1] = {
.format = WGPUVertexFormat_Float32x3,
.offset = 2 * sizeof(float),
.shaderLocation = 1,
}
};
WGPUVertexBufferLayout vertex_buffer_layout = {
.arrayStride = 5 * sizeof(float),
.attributeCount = 2,
.attributes = vertex_attributes,
};
// describe pipeline layout
WGPUBindGroupLayout bindgroup_layout = wgpuDeviceCreateBindGroupLayout(state.wgpu.device, &(WGPUBindGroupLayoutDescriptor){
.entryCount = 1,
// bind group layout entry
.entries = &(WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
// buffer binding layout
.buffer = {
.type = WGPUBufferBindingType_Uniform,
}
},
});
WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(state.wgpu.device, &(WGPUPipelineLayoutDescriptor){
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &bindgroup_layout,
});
// create pipeline
state.wgpu.pipeline = wgpuDeviceCreateRenderPipeline(state.wgpu.device, &(WGPURenderPipelineDescriptor){
// pipeline layout
.layout = pipeline_layout,
// vertex state
.vertex = {
.module = shader_triangle,
.entryPoint = make_stringview("vs_main"),
.bufferCount = 1,
.buffers = &vertex_buffer_layout,
},
// primitive state
.primitive = {
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
.topology = WGPUPrimitiveTopology_TriangleList,
.stripIndexFormat = WGPUIndexFormat_Undefined,
},
// fragment state
.fragment = &(WGPUFragmentState){
.module = shader_triangle,
.entryPoint = make_stringview("fs_main"),
.targetCount = 1,
// color target state
.targets = &(WGPUColorTargetState){
.format = WGPUTextureFormat_BGRA8Unorm,
.writeMask = WGPUColorWriteMask_All,
// blend state
.blend = &(WGPUBlendState){
.color = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_One,
.dstFactor = WGPUBlendFactor_One,
},
.alpha = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_One,
.dstFactor = WGPUBlendFactor_One,
},
},
},
},
// multi-sampling state
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
.alphaToCoverageEnabled = false,
},
// depth-stencil state
.depthStencil = NULL,
});
wgpuBindGroupLayoutRelease(bindgroup_layout);
wgpuPipelineLayoutRelease(pipeline_layout);
wgpuShaderModuleRelease(shader_triangle);
//-----------------
// setup
//-----------------
// create the vertex buffer (x, y, r, g, b) and index buffer
float const vertex_data[] = {
// x, y // r, g, b
-0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // bottom-left
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // top-right
-0.5f, 0.5f, 1.0f, 1.0f, 0.0f, // top-left
};
uint16_t index_data[] = {
0, 1, 2,
0, 2, 3,
};
state.res.vbuffer = create_buffer(vertex_data, sizeof(vertex_data), WGPUBufferUsage_Vertex);
state.res.ibuffer = create_buffer(index_data, sizeof(index_data), WGPUBufferUsage_Index);
// create the uniform bind group
state.res.ubuffer = create_buffer(&state.var.rot, sizeof(state.var.rot), WGPUBufferUsage_Uniform);
state.res.bindgroup = wgpuDeviceCreateBindGroup(state.wgpu.device, &(WGPUBindGroupDescriptor){
.layout = wgpuRenderPipelineGetBindGroupLayout(state.wgpu.pipeline, 0),
.entryCount = 1,
// bind group entry
.entries = &(WGPUBindGroupEntry){
.binding = 0,
.offset = 0,
.buffer = state.res.ubuffer,
.size = sizeof(state.var.rot),
},
});
//-----------------
// main loop
//-----------------
emscripten_set_main_loop(frame, 0, 1);
//-----------------
// quit
//-----------------
wgpuRenderPipelineRelease(state.wgpu.pipeline);
wgpuSurfaceRelease(state.wgpu.surface);
wgpuQueueRelease(state.wgpu.queue);
wgpuDeviceRelease(state.wgpu.device);
wgpuInstanceRelease(state.wgpu.instance);
return 0;
}
// frame callback
void frame() {
// update rotation
state.var.rot += 0.1f;
state.var.rot = state.var.rot >= 360.f ? 0.0f : state.var.rot;
wgpuQueueWriteBuffer(state.wgpu.queue, state.res.ubuffer, 0, &state.var.rot, sizeof(state.var.rot));
// create surface texture view
WGPUSurfaceTexture surface_texture;
wgpuSurfaceGetCurrentTexture(state.wgpu.surface, &surface_texture);
WGPUTextureView back_buffer = wgpuTextureCreateView(surface_texture.texture, NULL);
// create command encoder
WGPUCommandEncoder cmd_encoder = wgpuDeviceCreateCommandEncoder(state.wgpu.device, NULL);
// begin render pass
WGPURenderPassEncoder render_pass = wgpuCommandEncoderBeginRenderPass(cmd_encoder, &(WGPURenderPassDescriptor){
// color attachments
.colorAttachmentCount = 1,
.colorAttachments = &(WGPURenderPassColorAttachment){
.view = back_buffer,
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = (WGPUColor){ 0.2f, 0.2f, 0.3f, 1.0f },
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED
},
});
// draw quad (comment these five lines to simply clear the screen)
wgpuRenderPassEncoderSetPipeline(render_pass, state.wgpu.pipeline);
wgpuRenderPassEncoderSetBindGroup(render_pass, 0, state.res.bindgroup, 0, 0);
wgpuRenderPassEncoderSetVertexBuffer(render_pass, 0, state.res.vbuffer, 0, WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetIndexBuffer(render_pass, state.res.ibuffer, WGPUIndexFormat_Uint16, 0, WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderDrawIndexed(render_pass, 6, 1, 0, 0, 0);
// end render pass
wgpuRenderPassEncoderEnd(render_pass);
// create command buffer
WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(cmd_encoder, NULL); // after 'end render pass'
// submit commands
wgpuQueueSubmit(state.wgpu.queue, 1, &cmd_buffer);
// release all
wgpuRenderPassEncoderRelease(render_pass);
wgpuCommandEncoderRelease(cmd_encoder);
wgpuCommandBufferRelease(cmd_buffer);
wgpuTextureViewRelease(back_buffer);
wgpuTextureRelease(surface_texture.texture);
}
// resize callback
int resize(int event_type, const EmscriptenUiEvent* ui_event, void* user_data) {
(void)event_type, (void)ui_event, (void)user_data; // unused
double w, h;
emscripten_get_element_css_size(state.canvas.name, &w, &h);
state.canvas.width = (int)w;
state.canvas.height = (int)h;
emscripten_set_canvas_element_size(state.canvas.name, state.canvas.width, state.canvas.height);
if (state.wgpu.surface) {
wgpuSurfaceRelease(state.wgpu.surface);
state.wgpu.surface = NULL;
}
create_surface();
return 1;
}
// helper functions
void create_surface() {
state.wgpu.surface = wgpuInstanceCreateSurface(state.wgpu.instance, &(WGPUSurfaceDescriptor){
.nextInChain = (WGPUChainedStruct*)(&(WGPUEmscriptenSurfaceSourceCanvasHTMLSelector){
.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector,
.selector = make_stringview(state.canvas.name),
})
});
wgpuSurfaceConfigure(state.wgpu.surface, &(WGPUSurfaceConfiguration){
.device = state.wgpu.device,
.format = WGPUTextureFormat_BGRA8Unorm,
.usage = WGPUTextureUsage_RenderAttachment,
.width = state.canvas.width,
.height = state.canvas.height,
.presentMode = WGPUPresentMode_Fifo,
.alphaMode = WGPUCompositeAlphaMode_Auto,
});
}
WGPUShaderModule create_shader(const char* code, const char* label) {
WGPUShaderSourceWGSL wgsl = {
.chain.sType = WGPUSType_ShaderSourceWGSL,
.code = make_stringview(code),
};
return wgpuDeviceCreateShaderModule(state.wgpu.device, &(WGPUShaderModuleDescriptor){
.nextInChain = (WGPUChainedStruct*)(&wgsl),
.label = label,
});
}
WGPUBuffer create_buffer(const void* data, size_t size, WGPUBufferUsage usage) {
WGPUBuffer buffer = wgpuDeviceCreateBuffer(state.wgpu.device, &(WGPUBufferDescriptor){
.usage = WGPUBufferUsage_CopyDst | usage,
.size = size,
});
wgpuQueueWriteBuffer(state.wgpu.queue, buffer, 0, data, size);
return buffer;
}
WGPUStringView make_stringview(const char* str) {
WGPUStringView res = {0};
if (str) {
res.data = str;
res.length = strlen(str);
}
return res;
}