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
|
// This file is part of the 64k demo project.
// It implements the TextureManager.
#include "gpu/texture_manager.h"
#include "gpu/effects/shader_composer.h"
#include "platform/platform.h"
#include <cstdio>
#include <cstring>
#include <vector>
#if defined(DEMO_CROSS_COMPILE_WIN32)
// Old API
#define WGPU_TEX_COPY_INFO WGPUImageCopyTexture
#define WGPU_TEX_DATA_LAYOUT WGPUTextureDataLayout
#else
// New API
#define WGPU_TEX_COPY_INFO WGPUTexelCopyTextureInfo
#define WGPU_TEX_DATA_LAYOUT WGPUTexelCopyBufferLayout
#endif
void TextureManager::init(WGPUDevice device, WGPUQueue queue) {
device_ = device;
queue_ = queue;
}
void TextureManager::shutdown() {
for (auto& pair : textures_) {
wgpuTextureViewRelease(pair.second.view);
wgpuTextureRelease(pair.second.texture);
}
textures_.clear();
for (auto& pair : compute_pipelines_) {
if (pair.second.pipeline) {
wgpuComputePipelineRelease(pair.second.pipeline);
}
}
compute_pipelines_.clear();
}
void TextureManager::create_procedural_texture(
const std::string& name, const ProceduralTextureDef& def) {
// 1. Generate Data on CPU
std::vector<uint8_t> pixel_data;
pixel_data.resize(def.width * def.height * 4);
if (!def.gen_func(pixel_data.data(), def.width, def.height, def.params.data(),
(int)def.params.size())) {
fprintf(stderr, "Error: Procedural texture generation failed for: %s\n",
name.c_str());
return;
}
create_texture(name, def.width, def.height, pixel_data.data());
#if !defined(STRIP_ALL)
printf("Generated procedural texture: %s (%dx%d)\n", name.c_str(), def.width,
def.height);
#endif
}
void TextureManager::create_texture(const std::string& name, int width,
int height, const uint8_t* data) {
WGPUExtent3D tex_size = {(uint32_t)width, (uint32_t)height, 1};
// 2. Create GPU Texture
WGPUTextureDescriptor tex_desc = {};
tex_desc.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
tex_desc.dimension = WGPUTextureDimension_2D;
tex_desc.size = tex_size;
tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
tex_desc.mipLevelCount = 1;
tex_desc.sampleCount = 1;
#if defined(DEMO_CROSS_COMPILE_WIN32)
tex_desc.label = nullptr;
#else
tex_desc.label = {nullptr, 0};
#endif
WGPUTexture texture = wgpuDeviceCreateTexture(device_, &tex_desc);
// 3. Upload Data
WGPU_TEX_COPY_INFO destination = {};
destination.texture = texture;
destination.mipLevel = 0;
destination.origin = {0, 0, 0};
destination.aspect = WGPUTextureAspect_All;
WGPU_TEX_DATA_LAYOUT source_layout = {};
source_layout.offset = 0;
source_layout.bytesPerRow = width * 4;
source_layout.rowsPerImage = height;
wgpuQueueWriteTexture(queue_, &destination, data, width * height * 4,
&source_layout, &tex_size);
// 4. Create View
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_RGBA8Unorm;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.baseMipLevel = 0;
view_desc.mipLevelCount = 1;
view_desc.baseArrayLayer = 0;
view_desc.arrayLayerCount = 1;
view_desc.aspect = WGPUTextureAspect_All;
WGPUTextureView view = wgpuTextureCreateView(texture, &view_desc);
// 5. Store
GpuTexture gpu_tex;
gpu_tex.texture = texture;
gpu_tex.view = view;
gpu_tex.width = width;
gpu_tex.height = height;
textures_[name] = gpu_tex;
}
WGPUTextureView TextureManager::get_texture_view(const std::string& name) {
auto it = textures_.find(name);
if (it != textures_.end()) {
return it->second.view;
}
return nullptr;
}
WGPUComputePipeline TextureManager::get_or_create_compute_pipeline(
const std::string& func_name, const char* shader_code,
size_t uniform_size) {
auto it = compute_pipelines_.find(func_name);
if (it != compute_pipelines_.end()) {
return it->second.pipeline;
}
// Create new pipeline
ShaderComposer& composer = ShaderComposer::Get();
std::string resolved_shader = composer.Compose({}, shader_code);
WGPUShaderSourceWGSL wgsl_src = {};
wgsl_src.chain.sType = WGPUSType_ShaderSourceWGSL;
wgsl_src.code = str_view(resolved_shader.c_str());
WGPUShaderModuleDescriptor shader_desc = {};
shader_desc.nextInChain = &wgsl_src.chain;
WGPUShaderModule shader_module =
wgpuDeviceCreateShaderModule(device_, &shader_desc);
// Bind group layout (storage texture + uniform)
WGPUBindGroupLayoutEntry bgl_entries[2] = {};
bgl_entries[0].binding = 0;
bgl_entries[0].visibility = WGPUShaderStage_Compute;
bgl_entries[0].storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
bgl_entries[0].storageTexture.format = WGPUTextureFormat_RGBA8Unorm;
bgl_entries[0].storageTexture.viewDimension = WGPUTextureViewDimension_2D;
bgl_entries[1].binding = 1;
bgl_entries[1].visibility = WGPUShaderStage_Compute;
bgl_entries[1].buffer.type = WGPUBufferBindingType_Uniform;
bgl_entries[1].buffer.minBindingSize = uniform_size;
WGPUBindGroupLayoutDescriptor bgl_desc = {};
bgl_desc.entryCount = 2;
bgl_desc.entries = bgl_entries;
WGPUBindGroupLayout bind_group_layout =
wgpuDeviceCreateBindGroupLayout(device_, &bgl_desc);
WGPUPipelineLayoutDescriptor pl_desc = {};
pl_desc.bindGroupLayoutCount = 1;
pl_desc.bindGroupLayouts = &bind_group_layout;
WGPUPipelineLayout pipeline_layout =
wgpuDeviceCreatePipelineLayout(device_, &pl_desc);
WGPUComputePipelineDescriptor pipeline_desc = {};
pipeline_desc.layout = pipeline_layout;
pipeline_desc.compute.module = shader_module;
pipeline_desc.compute.entryPoint = str_view("main");
WGPUComputePipeline pipeline =
wgpuDeviceCreateComputePipeline(device_, &pipeline_desc);
wgpuPipelineLayoutRelease(pipeline_layout);
wgpuBindGroupLayoutRelease(bind_group_layout);
wgpuShaderModuleRelease(shader_module);
// Cache pipeline
ComputePipelineInfo info = {pipeline, shader_code, uniform_size};
compute_pipelines_[func_name] = info;
return pipeline;
}
void TextureManager::dispatch_compute(const std::string& func_name,
WGPUTexture target,
const GpuProceduralParams& params,
const void* uniform_data,
size_t uniform_size) {
auto it = compute_pipelines_.find(func_name);
if (it == compute_pipelines_.end()) {
return; // Pipeline not created yet
}
WGPUComputePipeline pipeline = it->second.pipeline;
// Create uniform buffer
WGPUBufferDescriptor buf_desc = {};
buf_desc.size = uniform_size;
buf_desc.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst;
buf_desc.mappedAtCreation = WGPUOptionalBool_True;
WGPUBuffer uniform_buf = wgpuDeviceCreateBuffer(device_, &buf_desc);
void* mapped = wgpuBufferGetMappedRange(uniform_buf, 0, uniform_size);
memcpy(mapped, uniform_data, uniform_size);
wgpuBufferUnmap(uniform_buf);
// Create storage texture view
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_RGBA8Unorm;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.mipLevelCount = 1;
view_desc.arrayLayerCount = 1;
WGPUTextureView target_view = wgpuTextureCreateView(target, &view_desc);
// Create bind group layout entries (must match pipeline)
WGPUBindGroupLayoutEntry bgl_entries[2] = {};
bgl_entries[0].binding = 0;
bgl_entries[0].visibility = WGPUShaderStage_Compute;
bgl_entries[0].storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
bgl_entries[0].storageTexture.format = WGPUTextureFormat_RGBA8Unorm;
bgl_entries[0].storageTexture.viewDimension = WGPUTextureViewDimension_2D;
bgl_entries[1].binding = 1;
bgl_entries[1].visibility = WGPUShaderStage_Compute;
bgl_entries[1].buffer.type = WGPUBufferBindingType_Uniform;
bgl_entries[1].buffer.minBindingSize = uniform_size;
WGPUBindGroupLayoutDescriptor bgl_desc = {};
bgl_desc.entryCount = 2;
bgl_desc.entries = bgl_entries;
WGPUBindGroupLayout bind_group_layout =
wgpuDeviceCreateBindGroupLayout(device_, &bgl_desc);
// Create bind group
WGPUBindGroupEntry bg_entries[2] = {};
bg_entries[0].binding = 0;
bg_entries[0].textureView = target_view;
bg_entries[1].binding = 1;
bg_entries[1].buffer = uniform_buf;
bg_entries[1].size = uniform_size;
WGPUBindGroupDescriptor bg_desc = {};
bg_desc.layout = bind_group_layout;
bg_desc.entryCount = 2;
bg_desc.entries = bg_entries;
WGPUBindGroup bind_group = wgpuDeviceCreateBindGroup(device_, &bg_desc);
// Dispatch compute
WGPUCommandEncoderDescriptor enc_desc = {};
WGPUCommandEncoder encoder =
wgpuDeviceCreateCommandEncoder(device_, &enc_desc);
WGPUComputePassEncoder pass =
wgpuCommandEncoderBeginComputePass(encoder, nullptr);
wgpuComputePassEncoderSetPipeline(pass, pipeline);
wgpuComputePassEncoderSetBindGroup(pass, 0, bind_group, 0, nullptr);
wgpuComputePassEncoderDispatchWorkgroups(pass, (params.width + 7) / 8,
(params.height + 7) / 8, 1);
wgpuComputePassEncoderEnd(pass);
WGPUCommandBufferDescriptor cmd_desc = {};
WGPUCommandBuffer cmd = wgpuCommandEncoderFinish(encoder, &cmd_desc);
wgpuQueueSubmit(queue_, 1, &cmd);
// Cleanup
wgpuCommandBufferRelease(cmd);
wgpuCommandEncoderRelease(encoder);
wgpuComputePassEncoderRelease(pass);
wgpuBindGroupRelease(bind_group);
wgpuBindGroupLayoutRelease(bind_group_layout);
wgpuBufferRelease(uniform_buf);
wgpuTextureViewRelease(target_view);
}
void TextureManager::create_gpu_noise_texture(
const std::string& name, const GpuProceduralParams& params) {
extern const char* gen_noise_compute_wgsl;
get_or_create_compute_pipeline("gen_noise", gen_noise_compute_wgsl, 16);
WGPUTextureDescriptor tex_desc = {};
tex_desc.usage =
WGPUTextureUsage_StorageBinding | WGPUTextureUsage_TextureBinding;
tex_desc.dimension = WGPUTextureDimension_2D;
tex_desc.size = {(uint32_t)params.width, (uint32_t)params.height, 1};
tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
tex_desc.mipLevelCount = 1;
tex_desc.sampleCount = 1;
WGPUTexture texture = wgpuDeviceCreateTexture(device_, &tex_desc);
struct NoiseParams {
uint32_t width;
uint32_t height;
float seed;
float frequency;
};
NoiseParams uniforms = {(uint32_t)params.width, (uint32_t)params.height,
params.params[0], params.params[1]};
dispatch_compute("gen_noise", texture, params, &uniforms, sizeof(NoiseParams));
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_RGBA8Unorm;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.mipLevelCount = 1;
view_desc.arrayLayerCount = 1;
WGPUTextureView view = wgpuTextureCreateView(texture, &view_desc);
GpuTexture gpu_tex;
gpu_tex.texture = texture;
gpu_tex.view = view;
gpu_tex.width = params.width;
gpu_tex.height = params.height;
textures_[name] = gpu_tex;
#if !defined(STRIP_ALL)
printf("Generated GPU noise texture: %s (%dx%d)\n", name.c_str(),
params.width, params.height);
#endif
}
void TextureManager::create_gpu_perlin_texture(
const std::string& name, const GpuProceduralParams& params) {
extern const char* gen_perlin_compute_wgsl;
get_or_create_compute_pipeline("gen_perlin", gen_perlin_compute_wgsl, 32);
WGPUTextureDescriptor tex_desc = {};
tex_desc.usage =
WGPUTextureUsage_StorageBinding | WGPUTextureUsage_TextureBinding;
tex_desc.dimension = WGPUTextureDimension_2D;
tex_desc.size = {(uint32_t)params.width, (uint32_t)params.height, 1};
tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
tex_desc.mipLevelCount = 1;
tex_desc.sampleCount = 1;
WGPUTexture texture = wgpuDeviceCreateTexture(device_, &tex_desc);
struct PerlinParams {
uint32_t width;
uint32_t height;
float seed;
float frequency;
float amplitude;
float amplitude_decay;
uint32_t octaves;
float _pad0;
};
PerlinParams uniforms = {
(uint32_t)params.width,
(uint32_t)params.height,
params.params[0],
params.params[1],
params.num_params > 2 ? params.params[2] : 1.0f,
params.num_params > 3 ? params.params[3] : 0.5f,
params.num_params > 4 ? (uint32_t)params.params[4] : 4u,
0.0f};
dispatch_compute("gen_perlin", texture, params, &uniforms,
sizeof(PerlinParams));
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_RGBA8Unorm;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.mipLevelCount = 1;
view_desc.arrayLayerCount = 1;
WGPUTextureView view = wgpuTextureCreateView(texture, &view_desc);
GpuTexture gpu_tex;
gpu_tex.texture = texture;
gpu_tex.view = view;
gpu_tex.width = params.width;
gpu_tex.height = params.height;
textures_[name] = gpu_tex;
#if !defined(STRIP_ALL)
printf("Generated GPU perlin texture: %s (%dx%d)\n", name.c_str(),
params.width, params.height);
#endif
}
void TextureManager::create_gpu_grid_texture(
const std::string& name, const GpuProceduralParams& params) {
extern const char* gen_grid_compute_wgsl;
get_or_create_compute_pipeline("gen_grid", gen_grid_compute_wgsl, 16);
WGPUTextureDescriptor tex_desc = {};
tex_desc.usage =
WGPUTextureUsage_StorageBinding | WGPUTextureUsage_TextureBinding;
tex_desc.dimension = WGPUTextureDimension_2D;
tex_desc.size = {(uint32_t)params.width, (uint32_t)params.height, 1};
tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
tex_desc.mipLevelCount = 1;
tex_desc.sampleCount = 1;
WGPUTexture texture = wgpuDeviceCreateTexture(device_, &tex_desc);
struct GridParams {
uint32_t width;
uint32_t height;
uint32_t grid_size;
uint32_t thickness;
};
GridParams uniforms = {
(uint32_t)params.width, (uint32_t)params.height,
params.num_params > 0 ? (uint32_t)params.params[0] : 32u,
params.num_params > 1 ? (uint32_t)params.params[1] : 2u};
dispatch_compute("gen_grid", texture, params, &uniforms, sizeof(GridParams));
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_RGBA8Unorm;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.mipLevelCount = 1;
view_desc.arrayLayerCount = 1;
WGPUTextureView view = wgpuTextureCreateView(texture, &view_desc);
GpuTexture gpu_tex;
gpu_tex.texture = texture;
gpu_tex.view = view;
gpu_tex.width = params.width;
gpu_tex.height = params.height;
textures_[name] = gpu_tex;
#if !defined(STRIP_ALL)
printf("Generated GPU grid texture: %s (%dx%d)\n", name.c_str(),
params.width, params.height);
#endif
}
#if !defined(STRIP_ALL)
WGPUTextureView TextureManager::get_or_generate_gpu_texture(
const std::string& name, const GpuProceduralParams& params) {
auto it = textures_.find(name);
if (it != textures_.end()) {
return it->second.view;
}
create_gpu_noise_texture(name, params);
return textures_[name].view;
}
#endif
|