@vunk/plus 1.11.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2143 +0,0 @@
1
- import { g as getTextureBatchBindGroup, E as ExtensionType, f as fastCopy, D as DOMAdapter, S as STENCIL_MODES, B as BufferUsage, b as Buffer, c as BindGroup, d as createIdFromString, w as warn, h as CLEAR, i as CanvasSource, j as TextureSource, k as UniformGroup, l as CanvasPool, M as Matrix, m as compileHighShaderGpuProgram, n as colorBit, o as generateTextureBatchBit, p as roundPixelsBit, q as Shader, s as Texture, e as extensions, A as AbstractRenderer, R as RendererType } from './index2.mjs';
2
- import { S as State, l as localUniformBitGroup2, a as localUniformBit } from './colorToUniform.mjs';
3
- import { c as createUboSyncFunction, u as uboSyncFunctionsWGSL, U as UboSystem, B as BufferResource, G as GpuStencilModesToPixi, e as ensureAttributes, R as RenderTargetSystem, t as textureBit, S as SharedSystems, a as SharedRenderPipes } from './SharedSystems.mjs';
4
- import 'vue';
5
- import '@vunk/shared/enum';
6
- import '@vunk/shared/promise';
7
- import './_commonjsHelpers.mjs';
8
- import './_plugin-vue_export-helper.mjs';
9
- import '@vunk/shared/object';
10
- import '@vunk/core/composables';
11
-
12
- const tempState = State.for2d();
13
- class GpuBatchAdaptor {
14
- start(batchPipe, geometry, shader) {
15
- const renderer = batchPipe.renderer;
16
- const encoder = renderer.encoder;
17
- const program = shader.gpuProgram;
18
- this._shader = shader;
19
- this._geometry = geometry;
20
- encoder.setGeometry(geometry, program);
21
- tempState.blendMode = "normal";
22
- renderer.pipeline.getPipeline(
23
- geometry,
24
- program,
25
- tempState
26
- );
27
- const globalUniformsBindGroup = renderer.globalUniforms.bindGroup;
28
- encoder.resetBindGroup(1);
29
- encoder.setBindGroup(0, globalUniformsBindGroup, program);
30
- }
31
- execute(batchPipe, batch) {
32
- const program = this._shader.gpuProgram;
33
- const renderer = batchPipe.renderer;
34
- const encoder = renderer.encoder;
35
- if (!batch.bindGroup) {
36
- const textureBatch = batch.textures;
37
- batch.bindGroup = getTextureBatchBindGroup(
38
- textureBatch.textures,
39
- textureBatch.count,
40
- renderer.limits.maxBatchableTextures
41
- );
42
- }
43
- tempState.blendMode = batch.blendMode;
44
- const gpuBindGroup = renderer.bindGroup.getBindGroup(
45
- batch.bindGroup,
46
- program,
47
- 1
48
- );
49
- const pipeline = renderer.pipeline.getPipeline(
50
- this._geometry,
51
- program,
52
- tempState,
53
- batch.topology
54
- );
55
- batch.bindGroup._touch(renderer.textureGC.count);
56
- encoder.setPipeline(pipeline);
57
- encoder.renderPassEncoder.setBindGroup(1, gpuBindGroup);
58
- encoder.renderPassEncoder.drawIndexed(batch.size, 1, batch.start);
59
- }
60
- }
61
- /** @ignore */
62
- GpuBatchAdaptor.extension = {
63
- type: [
64
- ExtensionType.WebGPUPipesAdaptor
65
- ],
66
- name: "batch"
67
- };
68
-
69
- class BindGroupSystem {
70
- constructor(renderer) {
71
- this._hash = /* @__PURE__ */ Object.create(null);
72
- this._renderer = renderer;
73
- this._renderer.renderableGC.addManagedHash(this, "_hash");
74
- }
75
- contextChange(gpu) {
76
- this._gpu = gpu;
77
- }
78
- getBindGroup(bindGroup, program, groupIndex) {
79
- bindGroup._updateKey();
80
- const gpuBindGroup = this._hash[bindGroup._key] || this._createBindGroup(bindGroup, program, groupIndex);
81
- return gpuBindGroup;
82
- }
83
- _createBindGroup(group, program, groupIndex) {
84
- const device = this._gpu.device;
85
- const groupLayout = program.layout[groupIndex];
86
- const entries = [];
87
- const renderer = this._renderer;
88
- for (const j in groupLayout) {
89
- const resource = group.resources[j] ?? group.resources[groupLayout[j]];
90
- let gpuResource;
91
- if (resource._resourceType === "uniformGroup") {
92
- const uniformGroup = resource;
93
- renderer.ubo.updateUniformGroup(uniformGroup);
94
- const buffer = uniformGroup.buffer;
95
- gpuResource = {
96
- buffer: renderer.buffer.getGPUBuffer(buffer),
97
- offset: 0,
98
- size: buffer.descriptor.size
99
- };
100
- } else if (resource._resourceType === "buffer") {
101
- const buffer = resource;
102
- gpuResource = {
103
- buffer: renderer.buffer.getGPUBuffer(buffer),
104
- offset: 0,
105
- size: buffer.descriptor.size
106
- };
107
- } else if (resource._resourceType === "bufferResource") {
108
- const bufferResource = resource;
109
- gpuResource = {
110
- buffer: renderer.buffer.getGPUBuffer(bufferResource.buffer),
111
- offset: bufferResource.offset,
112
- size: bufferResource.size
113
- };
114
- } else if (resource._resourceType === "textureSampler") {
115
- const sampler = resource;
116
- gpuResource = renderer.texture.getGpuSampler(sampler);
117
- } else if (resource._resourceType === "textureSource") {
118
- const texture = resource;
119
- gpuResource = renderer.texture.getGpuSource(texture).createView({});
120
- }
121
- entries.push({
122
- binding: groupLayout[j],
123
- resource: gpuResource
124
- });
125
- }
126
- const layout = renderer.shader.getProgramData(program).bindGroups[groupIndex];
127
- const gpuBindGroup = device.createBindGroup({
128
- layout,
129
- entries
130
- });
131
- this._hash[group._key] = gpuBindGroup;
132
- return gpuBindGroup;
133
- }
134
- destroy() {
135
- for (const key of Object.keys(this._hash)) {
136
- this._hash[key] = null;
137
- }
138
- this._hash = null;
139
- this._renderer = null;
140
- }
141
- }
142
- /** @ignore */
143
- BindGroupSystem.extension = {
144
- type: [
145
- ExtensionType.WebGPUSystem
146
- ],
147
- name: "bindGroup"
148
- };
149
-
150
- class GpuBufferSystem {
151
- constructor(renderer) {
152
- this._gpuBuffers = /* @__PURE__ */ Object.create(null);
153
- this._managedBuffers = [];
154
- renderer.renderableGC.addManagedHash(this, "_gpuBuffers");
155
- }
156
- contextChange(gpu) {
157
- this._gpu = gpu;
158
- }
159
- getGPUBuffer(buffer) {
160
- return this._gpuBuffers[buffer.uid] || this.createGPUBuffer(buffer);
161
- }
162
- updateBuffer(buffer) {
163
- const gpuBuffer = this._gpuBuffers[buffer.uid] || this.createGPUBuffer(buffer);
164
- const data = buffer.data;
165
- if (buffer._updateID && data) {
166
- buffer._updateID = 0;
167
- this._gpu.device.queue.writeBuffer(
168
- gpuBuffer,
169
- 0,
170
- data.buffer,
171
- 0,
172
- // round to the nearest 4 bytes
173
- (buffer._updateSize || data.byteLength) + 3 & ~3
174
- );
175
- }
176
- return gpuBuffer;
177
- }
178
- /** dispose all WebGL resources of all managed buffers */
179
- destroyAll() {
180
- for (const id in this._gpuBuffers) {
181
- this._gpuBuffers[id].destroy();
182
- }
183
- this._gpuBuffers = {};
184
- }
185
- createGPUBuffer(buffer) {
186
- if (!this._gpuBuffers[buffer.uid]) {
187
- buffer.on("update", this.updateBuffer, this);
188
- buffer.on("change", this.onBufferChange, this);
189
- buffer.on("destroy", this.onBufferDestroy, this);
190
- this._managedBuffers.push(buffer);
191
- }
192
- const gpuBuffer = this._gpu.device.createBuffer(buffer.descriptor);
193
- buffer._updateID = 0;
194
- if (buffer.data) {
195
- fastCopy(buffer.data.buffer, gpuBuffer.getMappedRange());
196
- gpuBuffer.unmap();
197
- }
198
- this._gpuBuffers[buffer.uid] = gpuBuffer;
199
- return gpuBuffer;
200
- }
201
- onBufferChange(buffer) {
202
- const gpuBuffer = this._gpuBuffers[buffer.uid];
203
- gpuBuffer.destroy();
204
- buffer._updateID = 0;
205
- this._gpuBuffers[buffer.uid] = this.createGPUBuffer(buffer);
206
- }
207
- /**
208
- * Disposes buffer
209
- * @param buffer - buffer with data
210
- */
211
- onBufferDestroy(buffer) {
212
- this._managedBuffers.splice(this._managedBuffers.indexOf(buffer), 1);
213
- this._destroyBuffer(buffer);
214
- }
215
- destroy() {
216
- this._managedBuffers.forEach((buffer) => this._destroyBuffer(buffer));
217
- this._managedBuffers = null;
218
- this._gpuBuffers = null;
219
- }
220
- _destroyBuffer(buffer) {
221
- const gpuBuffer = this._gpuBuffers[buffer.uid];
222
- gpuBuffer.destroy();
223
- buffer.off("update", this.updateBuffer, this);
224
- buffer.off("change", this.onBufferChange, this);
225
- buffer.off("destroy", this.onBufferDestroy, this);
226
- this._gpuBuffers[buffer.uid] = null;
227
- }
228
- }
229
- /** @ignore */
230
- GpuBufferSystem.extension = {
231
- type: [
232
- ExtensionType.WebGPUSystem
233
- ],
234
- name: "buffer"
235
- };
236
-
237
- class UboBatch {
238
- constructor({ minUniformOffsetAlignment }) {
239
- this._minUniformOffsetAlignment = 256;
240
- this.byteIndex = 0;
241
- this._minUniformOffsetAlignment = minUniformOffsetAlignment;
242
- this.data = new Float32Array(65535);
243
- }
244
- clear() {
245
- this.byteIndex = 0;
246
- }
247
- addEmptyGroup(size) {
248
- if (size > this._minUniformOffsetAlignment / 4) {
249
- throw new Error(`UniformBufferBatch: array is too large: ${size * 4}`);
250
- }
251
- const start = this.byteIndex;
252
- let newSize = start + size * 4;
253
- newSize = Math.ceil(newSize / this._minUniformOffsetAlignment) * this._minUniformOffsetAlignment;
254
- if (newSize > this.data.length * 4) {
255
- throw new Error("UniformBufferBatch: ubo batch got too big");
256
- }
257
- this.byteIndex = newSize;
258
- return start;
259
- }
260
- addGroup(array) {
261
- const offset = this.addEmptyGroup(array.length);
262
- for (let i = 0; i < array.length; i++) {
263
- this.data[offset / 4 + i] = array[i];
264
- }
265
- return offset;
266
- }
267
- destroy() {
268
- this.data = null;
269
- }
270
- }
271
-
272
- class GpuColorMaskSystem {
273
- constructor(renderer) {
274
- this._colorMaskCache = 15;
275
- this._renderer = renderer;
276
- }
277
- setMask(colorMask) {
278
- if (this._colorMaskCache === colorMask)
279
- return;
280
- this._colorMaskCache = colorMask;
281
- this._renderer.pipeline.setColorMask(colorMask);
282
- }
283
- destroy() {
284
- this._renderer = null;
285
- this._colorMaskCache = null;
286
- }
287
- }
288
- /** @ignore */
289
- GpuColorMaskSystem.extension = {
290
- type: [
291
- ExtensionType.WebGPUSystem
292
- ],
293
- name: "colorMask"
294
- };
295
-
296
- class GpuDeviceSystem {
297
- /**
298
- * @param {WebGPURenderer} renderer - The renderer this System works for.
299
- */
300
- constructor(renderer) {
301
- this._renderer = renderer;
302
- }
303
- async init(options) {
304
- if (this._initPromise)
305
- return this._initPromise;
306
- this._initPromise = this._createDeviceAndAdaptor(options).then((gpu) => {
307
- this.gpu = gpu;
308
- this._renderer.runners.contextChange.emit(this.gpu);
309
- });
310
- return this._initPromise;
311
- }
312
- /**
313
- * Handle the context change event
314
- * @param gpu
315
- */
316
- contextChange(gpu) {
317
- this._renderer.gpu = gpu;
318
- }
319
- /**
320
- * Helper class to create a WebGL Context
321
- * @param {object} options - An options object that gets passed in to the canvas element containing the
322
- * context attributes
323
- * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext
324
- * @returns {WebGLRenderingContext} the WebGL context
325
- */
326
- async _createDeviceAndAdaptor(options) {
327
- const adapter = await DOMAdapter.get().getNavigator().gpu.requestAdapter({
328
- powerPreference: options.powerPreference,
329
- forceFallbackAdapter: options.forceFallbackAdapter
330
- });
331
- const requiredFeatures = [
332
- "texture-compression-bc",
333
- "texture-compression-astc",
334
- "texture-compression-etc2"
335
- ].filter((feature) => adapter.features.has(feature));
336
- const device = await adapter.requestDevice({
337
- requiredFeatures
338
- });
339
- return { adapter, device };
340
- }
341
- destroy() {
342
- this.gpu = null;
343
- this._renderer = null;
344
- }
345
- }
346
- /** @ignore */
347
- GpuDeviceSystem.extension = {
348
- type: [
349
- ExtensionType.WebGPUSystem
350
- ],
351
- name: "device"
352
- };
353
- /** The default options for the GpuDeviceSystem. */
354
- GpuDeviceSystem.defaultOptions = {
355
- /**
356
- * {@link WebGPUOptions.powerPreference}
357
- * @default default
358
- */
359
- powerPreference: void 0,
360
- /**
361
- * Force the use of the fallback adapter
362
- * @default false
363
- */
364
- forceFallbackAdapter: false
365
- };
366
-
367
- class GpuEncoderSystem {
368
- constructor(renderer) {
369
- this._boundBindGroup = /* @__PURE__ */ Object.create(null);
370
- this._boundVertexBuffer = /* @__PURE__ */ Object.create(null);
371
- this._renderer = renderer;
372
- }
373
- renderStart() {
374
- this.commandFinished = new Promise((resolve) => {
375
- this._resolveCommandFinished = resolve;
376
- });
377
- this.commandEncoder = this._renderer.gpu.device.createCommandEncoder();
378
- }
379
- beginRenderPass(gpuRenderTarget) {
380
- this.endRenderPass();
381
- this._clearCache();
382
- this.renderPassEncoder = this.commandEncoder.beginRenderPass(gpuRenderTarget.descriptor);
383
- }
384
- endRenderPass() {
385
- if (this.renderPassEncoder) {
386
- this.renderPassEncoder.end();
387
- }
388
- this.renderPassEncoder = null;
389
- }
390
- setViewport(viewport) {
391
- this.renderPassEncoder.setViewport(viewport.x, viewport.y, viewport.width, viewport.height, 0, 1);
392
- }
393
- setPipelineFromGeometryProgramAndState(geometry, program, state, topology) {
394
- const pipeline = this._renderer.pipeline.getPipeline(geometry, program, state, topology);
395
- this.setPipeline(pipeline);
396
- }
397
- setPipeline(pipeline) {
398
- if (this._boundPipeline === pipeline)
399
- return;
400
- this._boundPipeline = pipeline;
401
- this.renderPassEncoder.setPipeline(pipeline);
402
- }
403
- _setVertexBuffer(index, buffer) {
404
- if (this._boundVertexBuffer[index] === buffer)
405
- return;
406
- this._boundVertexBuffer[index] = buffer;
407
- this.renderPassEncoder.setVertexBuffer(index, this._renderer.buffer.updateBuffer(buffer));
408
- }
409
- _setIndexBuffer(buffer) {
410
- if (this._boundIndexBuffer === buffer)
411
- return;
412
- this._boundIndexBuffer = buffer;
413
- const indexFormat = buffer.data.BYTES_PER_ELEMENT === 2 ? "uint16" : "uint32";
414
- this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(buffer), indexFormat);
415
- }
416
- resetBindGroup(index) {
417
- this._boundBindGroup[index] = null;
418
- }
419
- setBindGroup(index, bindGroup, program) {
420
- if (this._boundBindGroup[index] === bindGroup)
421
- return;
422
- this._boundBindGroup[index] = bindGroup;
423
- bindGroup._touch(this._renderer.textureGC.count);
424
- const gpuBindGroup = this._renderer.bindGroup.getBindGroup(bindGroup, program, index);
425
- this.renderPassEncoder.setBindGroup(index, gpuBindGroup);
426
- }
427
- setGeometry(geometry, program) {
428
- const buffersToBind = this._renderer.pipeline.getBufferNamesToBind(geometry, program);
429
- for (const i in buffersToBind) {
430
- this._setVertexBuffer(i, geometry.attributes[buffersToBind[i]].buffer);
431
- }
432
- if (geometry.indexBuffer) {
433
- this._setIndexBuffer(geometry.indexBuffer);
434
- }
435
- }
436
- _setShaderBindGroups(shader, skipSync) {
437
- for (const i in shader.groups) {
438
- const bindGroup = shader.groups[i];
439
- if (!skipSync) {
440
- this._syncBindGroup(bindGroup);
441
- }
442
- this.setBindGroup(i, bindGroup, shader.gpuProgram);
443
- }
444
- }
445
- _syncBindGroup(bindGroup) {
446
- for (const j in bindGroup.resources) {
447
- const resource = bindGroup.resources[j];
448
- if (resource.isUniformGroup) {
449
- this._renderer.ubo.updateUniformGroup(resource);
450
- }
451
- }
452
- }
453
- draw(options) {
454
- const { geometry, shader, state, topology, size, start, instanceCount, skipSync } = options;
455
- this.setPipelineFromGeometryProgramAndState(geometry, shader.gpuProgram, state, topology);
456
- this.setGeometry(geometry, shader.gpuProgram);
457
- this._setShaderBindGroups(shader, skipSync);
458
- if (geometry.indexBuffer) {
459
- this.renderPassEncoder.drawIndexed(
460
- size || geometry.indexBuffer.data.length,
461
- instanceCount ?? geometry.instanceCount,
462
- start || 0
463
- );
464
- } else {
465
- this.renderPassEncoder.draw(size || geometry.getSize(), instanceCount ?? geometry.instanceCount, start || 0);
466
- }
467
- }
468
- finishRenderPass() {
469
- if (this.renderPassEncoder) {
470
- this.renderPassEncoder.end();
471
- this.renderPassEncoder = null;
472
- }
473
- }
474
- postrender() {
475
- this.finishRenderPass();
476
- this._gpu.device.queue.submit([this.commandEncoder.finish()]);
477
- this._resolveCommandFinished();
478
- this.commandEncoder = null;
479
- }
480
- // restores a render pass if finishRenderPass was called
481
- // not optimised as really used for debugging!
482
- // used when we want to stop drawing and log a texture..
483
- restoreRenderPass() {
484
- const descriptor = this._renderer.renderTarget.adaptor.getDescriptor(
485
- this._renderer.renderTarget.renderTarget,
486
- false,
487
- [0, 0, 0, 1]
488
- );
489
- this.renderPassEncoder = this.commandEncoder.beginRenderPass(descriptor);
490
- const boundPipeline = this._boundPipeline;
491
- const boundVertexBuffer = { ...this._boundVertexBuffer };
492
- const boundIndexBuffer = this._boundIndexBuffer;
493
- const boundBindGroup = { ...this._boundBindGroup };
494
- this._clearCache();
495
- const viewport = this._renderer.renderTarget.viewport;
496
- this.renderPassEncoder.setViewport(viewport.x, viewport.y, viewport.width, viewport.height, 0, 1);
497
- this.setPipeline(boundPipeline);
498
- for (const i in boundVertexBuffer) {
499
- this._setVertexBuffer(i, boundVertexBuffer[i]);
500
- }
501
- for (const i in boundBindGroup) {
502
- this.setBindGroup(i, boundBindGroup[i], null);
503
- }
504
- this._setIndexBuffer(boundIndexBuffer);
505
- }
506
- _clearCache() {
507
- for (let i = 0; i < 16; i++) {
508
- this._boundBindGroup[i] = null;
509
- this._boundVertexBuffer[i] = null;
510
- }
511
- this._boundIndexBuffer = null;
512
- this._boundPipeline = null;
513
- }
514
- destroy() {
515
- this._renderer = null;
516
- this._gpu = null;
517
- this._boundBindGroup = null;
518
- this._boundVertexBuffer = null;
519
- this._boundIndexBuffer = null;
520
- this._boundPipeline = null;
521
- }
522
- contextChange(gpu) {
523
- this._gpu = gpu;
524
- }
525
- }
526
- /** @ignore */
527
- GpuEncoderSystem.extension = {
528
- type: [ExtensionType.WebGPUSystem],
529
- name: "encoder",
530
- priority: 1
531
- };
532
-
533
- class GpuLimitsSystem {
534
- constructor(renderer) {
535
- this._renderer = renderer;
536
- }
537
- contextChange() {
538
- this.maxTextures = this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage;
539
- this.maxBatchableTextures = this.maxTextures;
540
- }
541
- destroy() {
542
- }
543
- }
544
- /** @ignore */
545
- GpuLimitsSystem.extension = {
546
- type: [
547
- ExtensionType.WebGPUSystem
548
- ],
549
- name: "limits"
550
- };
551
-
552
- class GpuStencilSystem {
553
- constructor(renderer) {
554
- this._renderTargetStencilState = /* @__PURE__ */ Object.create(null);
555
- this._renderer = renderer;
556
- renderer.renderTarget.onRenderTargetChange.add(this);
557
- }
558
- onRenderTargetChange(renderTarget) {
559
- let stencilState = this._renderTargetStencilState[renderTarget.uid];
560
- if (!stencilState) {
561
- stencilState = this._renderTargetStencilState[renderTarget.uid] = {
562
- stencilMode: STENCIL_MODES.DISABLED,
563
- stencilReference: 0
564
- };
565
- }
566
- this._activeRenderTarget = renderTarget;
567
- this.setStencilMode(stencilState.stencilMode, stencilState.stencilReference);
568
- }
569
- setStencilMode(stencilMode, stencilReference) {
570
- const stencilState = this._renderTargetStencilState[this._activeRenderTarget.uid];
571
- stencilState.stencilMode = stencilMode;
572
- stencilState.stencilReference = stencilReference;
573
- const renderer = this._renderer;
574
- renderer.pipeline.setStencilMode(stencilMode);
575
- renderer.encoder.renderPassEncoder.setStencilReference(stencilReference);
576
- }
577
- destroy() {
578
- this._renderer.renderTarget.onRenderTargetChange.remove(this);
579
- this._renderer = null;
580
- this._activeRenderTarget = null;
581
- this._renderTargetStencilState = null;
582
- }
583
- }
584
- /** @ignore */
585
- GpuStencilSystem.extension = {
586
- type: [
587
- ExtensionType.WebGPUSystem
588
- ],
589
- name: "stencil"
590
- };
591
-
592
- const WGSL_ALIGN_SIZE_DATA = {
593
- i32: { align: 4, size: 4 },
594
- u32: { align: 4, size: 4 },
595
- f32: { align: 4, size: 4 },
596
- f16: { align: 2, size: 2 },
597
- "vec2<i32>": { align: 8, size: 8 },
598
- "vec2<u32>": { align: 8, size: 8 },
599
- "vec2<f32>": { align: 8, size: 8 },
600
- "vec2<f16>": { align: 4, size: 4 },
601
- "vec3<i32>": { align: 16, size: 12 },
602
- "vec3<u32>": { align: 16, size: 12 },
603
- "vec3<f32>": { align: 16, size: 12 },
604
- "vec3<f16>": { align: 8, size: 6 },
605
- "vec4<i32>": { align: 16, size: 16 },
606
- "vec4<u32>": { align: 16, size: 16 },
607
- "vec4<f32>": { align: 16, size: 16 },
608
- "vec4<f16>": { align: 8, size: 8 },
609
- "mat2x2<f32>": { align: 8, size: 16 },
610
- "mat2x2<f16>": { align: 4, size: 8 },
611
- "mat3x2<f32>": { align: 8, size: 24 },
612
- "mat3x2<f16>": { align: 4, size: 12 },
613
- "mat4x2<f32>": { align: 8, size: 32 },
614
- "mat4x2<f16>": { align: 4, size: 16 },
615
- "mat2x3<f32>": { align: 16, size: 32 },
616
- "mat2x3<f16>": { align: 8, size: 16 },
617
- "mat3x3<f32>": { align: 16, size: 48 },
618
- "mat3x3<f16>": { align: 8, size: 24 },
619
- "mat4x3<f32>": { align: 16, size: 64 },
620
- "mat4x3<f16>": { align: 8, size: 32 },
621
- "mat2x4<f32>": { align: 16, size: 32 },
622
- "mat2x4<f16>": { align: 8, size: 16 },
623
- "mat3x4<f32>": { align: 16, size: 48 },
624
- "mat3x4<f16>": { align: 8, size: 24 },
625
- "mat4x4<f32>": { align: 16, size: 64 },
626
- "mat4x4<f16>": { align: 8, size: 32 }
627
- };
628
- function createUboElementsWGSL(uniformData) {
629
- const uboElements = uniformData.map((data) => ({
630
- data,
631
- offset: 0,
632
- size: 0
633
- }));
634
- let offset = 0;
635
- for (let i = 0; i < uboElements.length; i++) {
636
- const uboElement = uboElements[i];
637
- let size = WGSL_ALIGN_SIZE_DATA[uboElement.data.type].size;
638
- const align = WGSL_ALIGN_SIZE_DATA[uboElement.data.type].align;
639
- if (!WGSL_ALIGN_SIZE_DATA[uboElement.data.type]) {
640
- throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${uboElement.data.type}`);
641
- }
642
- if (uboElement.data.size > 1) {
643
- size = Math.max(size, align) * uboElement.data.size;
644
- }
645
- offset = Math.ceil(offset / align) * align;
646
- uboElement.size = size;
647
- uboElement.offset = offset;
648
- offset += size;
649
- }
650
- offset = Math.ceil(offset / 16) * 16;
651
- return { uboElements, size: offset };
652
- }
653
-
654
- function generateArraySyncWGSL(uboElement, offsetToAdd) {
655
- const { size, align } = WGSL_ALIGN_SIZE_DATA[uboElement.data.type];
656
- const remainder = (align - size) / 4;
657
- const data = uboElement.data.type.indexOf("i32") >= 0 ? "dataInt32" : "data";
658
- return `
659
- v = uv.${uboElement.data.name};
660
- ${offsetToAdd !== 0 ? `offset += ${offsetToAdd};` : ""}
661
-
662
- arrayOffset = offset;
663
-
664
- t = 0;
665
-
666
- for(var i=0; i < ${uboElement.data.size * (size / 4)}; i++)
667
- {
668
- for(var j = 0; j < ${size / 4}; j++)
669
- {
670
- ${data}[arrayOffset++] = v[t++];
671
- }
672
- ${remainder !== 0 ? `arrayOffset += ${remainder};` : ""}
673
- }
674
- `;
675
- }
676
-
677
- function createUboSyncFunctionWGSL(uboElements) {
678
- return createUboSyncFunction(
679
- uboElements,
680
- "uboWgsl",
681
- generateArraySyncWGSL,
682
- uboSyncFunctionsWGSL
683
- );
684
- }
685
-
686
- class GpuUboSystem extends UboSystem {
687
- constructor() {
688
- super({
689
- createUboElements: createUboElementsWGSL,
690
- generateUboSync: createUboSyncFunctionWGSL
691
- });
692
- }
693
- }
694
- /** @ignore */
695
- GpuUboSystem.extension = {
696
- type: [ExtensionType.WebGPUSystem],
697
- name: "ubo"
698
- };
699
-
700
- const minUniformOffsetAlignment = 128;
701
- class GpuUniformBatchPipe {
702
- constructor(renderer) {
703
- this._bindGroupHash = /* @__PURE__ */ Object.create(null);
704
- // number of buffers..
705
- this._buffers = [];
706
- this._bindGroups = [];
707
- this._bufferResources = [];
708
- this._renderer = renderer;
709
- this._renderer.renderableGC.addManagedHash(this, "_bindGroupHash");
710
- this._batchBuffer = new UboBatch({ minUniformOffsetAlignment });
711
- const totalBuffers = 256 / minUniformOffsetAlignment;
712
- for (let i = 0; i < totalBuffers; i++) {
713
- let usage = BufferUsage.UNIFORM | BufferUsage.COPY_DST;
714
- if (i === 0)
715
- usage |= BufferUsage.COPY_SRC;
716
- this._buffers.push(new Buffer({
717
- data: this._batchBuffer.data,
718
- usage
719
- }));
720
- }
721
- }
722
- renderEnd() {
723
- this._uploadBindGroups();
724
- this._resetBindGroups();
725
- }
726
- _resetBindGroups() {
727
- for (const i in this._bindGroupHash) {
728
- this._bindGroupHash[i] = null;
729
- }
730
- this._batchBuffer.clear();
731
- }
732
- // just works for single bind groups for now
733
- getUniformBindGroup(group, duplicate) {
734
- if (!duplicate && this._bindGroupHash[group.uid]) {
735
- return this._bindGroupHash[group.uid];
736
- }
737
- this._renderer.ubo.ensureUniformGroup(group);
738
- const data = group.buffer.data;
739
- const offset = this._batchBuffer.addEmptyGroup(data.length);
740
- this._renderer.ubo.syncUniformGroup(group, this._batchBuffer.data, offset / 4);
741
- this._bindGroupHash[group.uid] = this._getBindGroup(offset / minUniformOffsetAlignment);
742
- return this._bindGroupHash[group.uid];
743
- }
744
- getUboResource(group) {
745
- this._renderer.ubo.updateUniformGroup(group);
746
- const data = group.buffer.data;
747
- const offset = this._batchBuffer.addGroup(data);
748
- return this._getBufferResource(offset / minUniformOffsetAlignment);
749
- }
750
- getArrayBindGroup(data) {
751
- const offset = this._batchBuffer.addGroup(data);
752
- return this._getBindGroup(offset / minUniformOffsetAlignment);
753
- }
754
- getArrayBufferResource(data) {
755
- const offset = this._batchBuffer.addGroup(data);
756
- const index = offset / minUniformOffsetAlignment;
757
- return this._getBufferResource(index);
758
- }
759
- _getBufferResource(index) {
760
- if (!this._bufferResources[index]) {
761
- const buffer = this._buffers[index % 2];
762
- this._bufferResources[index] = new BufferResource({
763
- buffer,
764
- offset: (index / 2 | 0) * 256,
765
- size: minUniformOffsetAlignment
766
- });
767
- }
768
- return this._bufferResources[index];
769
- }
770
- _getBindGroup(index) {
771
- if (!this._bindGroups[index]) {
772
- const bindGroup = new BindGroup({
773
- 0: this._getBufferResource(index)
774
- });
775
- this._bindGroups[index] = bindGroup;
776
- }
777
- return this._bindGroups[index];
778
- }
779
- _uploadBindGroups() {
780
- const bufferSystem = this._renderer.buffer;
781
- const firstBuffer = this._buffers[0];
782
- firstBuffer.update(this._batchBuffer.byteIndex);
783
- bufferSystem.updateBuffer(firstBuffer);
784
- const commandEncoder = this._renderer.gpu.device.createCommandEncoder();
785
- for (let i = 1; i < this._buffers.length; i++) {
786
- const buffer = this._buffers[i];
787
- commandEncoder.copyBufferToBuffer(
788
- bufferSystem.getGPUBuffer(firstBuffer),
789
- minUniformOffsetAlignment,
790
- bufferSystem.getGPUBuffer(buffer),
791
- 0,
792
- this._batchBuffer.byteIndex
793
- );
794
- }
795
- this._renderer.gpu.device.queue.submit([commandEncoder.finish()]);
796
- }
797
- destroy() {
798
- for (let i = 0; i < this._bindGroups.length; i++) {
799
- this._bindGroups[i].destroy();
800
- }
801
- this._bindGroups = null;
802
- this._bindGroupHash = null;
803
- for (let i = 0; i < this._buffers.length; i++) {
804
- this._buffers[i].destroy();
805
- }
806
- this._buffers = null;
807
- for (let i = 0; i < this._bufferResources.length; i++) {
808
- this._bufferResources[i].destroy();
809
- }
810
- this._bufferResources = null;
811
- this._batchBuffer.destroy();
812
- this._bindGroupHash = null;
813
- this._renderer = null;
814
- }
815
- }
816
- /** @ignore */
817
- GpuUniformBatchPipe.extension = {
818
- type: [
819
- ExtensionType.WebGPUPipes
820
- ],
821
- name: "uniformBatch"
822
- };
823
-
824
- const topologyStringToId = {
825
- "point-list": 0,
826
- "line-list": 1,
827
- "line-strip": 2,
828
- "triangle-list": 3,
829
- "triangle-strip": 4
830
- };
831
- function getGraphicsStateKey(geometryLayout, shaderKey, state, blendMode, topology) {
832
- return geometryLayout << 24 | shaderKey << 16 | state << 10 | blendMode << 5 | topology;
833
- }
834
- function getGlobalStateKey(stencilStateId, multiSampleCount, colorMask, renderTarget) {
835
- return colorMask << 6 | stencilStateId << 3 | renderTarget << 1 | multiSampleCount;
836
- }
837
- class PipelineSystem {
838
- constructor(renderer) {
839
- this._moduleCache = /* @__PURE__ */ Object.create(null);
840
- this._bufferLayoutsCache = /* @__PURE__ */ Object.create(null);
841
- this._bindingNamesCache = /* @__PURE__ */ Object.create(null);
842
- this._pipeCache = /* @__PURE__ */ Object.create(null);
843
- this._pipeStateCaches = /* @__PURE__ */ Object.create(null);
844
- this._colorMask = 15;
845
- this._multisampleCount = 1;
846
- this._renderer = renderer;
847
- }
848
- contextChange(gpu) {
849
- this._gpu = gpu;
850
- this.setStencilMode(STENCIL_MODES.DISABLED);
851
- this._updatePipeHash();
852
- }
853
- setMultisampleCount(multisampleCount) {
854
- if (this._multisampleCount === multisampleCount)
855
- return;
856
- this._multisampleCount = multisampleCount;
857
- this._updatePipeHash();
858
- }
859
- setRenderTarget(renderTarget) {
860
- this._multisampleCount = renderTarget.msaaSamples;
861
- this._depthStencilAttachment = renderTarget.descriptor.depthStencilAttachment ? 1 : 0;
862
- this._updatePipeHash();
863
- }
864
- setColorMask(colorMask) {
865
- if (this._colorMask === colorMask)
866
- return;
867
- this._colorMask = colorMask;
868
- this._updatePipeHash();
869
- }
870
- setStencilMode(stencilMode) {
871
- if (this._stencilMode === stencilMode)
872
- return;
873
- this._stencilMode = stencilMode;
874
- this._stencilState = GpuStencilModesToPixi[stencilMode];
875
- this._updatePipeHash();
876
- }
877
- setPipeline(geometry, program, state, passEncoder) {
878
- const pipeline = this.getPipeline(geometry, program, state);
879
- passEncoder.setPipeline(pipeline);
880
- }
881
- getPipeline(geometry, program, state, topology) {
882
- if (!geometry._layoutKey) {
883
- ensureAttributes(geometry, program.attributeData);
884
- this._generateBufferKey(geometry);
885
- }
886
- topology || (topology = geometry.topology);
887
- const key = getGraphicsStateKey(
888
- geometry._layoutKey,
889
- program._layoutKey,
890
- state.data,
891
- state._blendModeId,
892
- topologyStringToId[topology]
893
- );
894
- if (this._pipeCache[key])
895
- return this._pipeCache[key];
896
- this._pipeCache[key] = this._createPipeline(geometry, program, state, topology);
897
- return this._pipeCache[key];
898
- }
899
- _createPipeline(geometry, program, state, topology) {
900
- const device = this._gpu.device;
901
- const buffers = this._createVertexBufferLayouts(geometry, program);
902
- const blendModes = this._renderer.state.getColorTargets(state);
903
- blendModes[0].writeMask = this._stencilMode === STENCIL_MODES.RENDERING_MASK_ADD ? 0 : this._colorMask;
904
- const layout = this._renderer.shader.getProgramData(program).pipeline;
905
- const descriptor = {
906
- // TODO later check if its helpful to create..
907
- // layout,
908
- vertex: {
909
- module: this._getModule(program.vertex.source),
910
- entryPoint: program.vertex.entryPoint,
911
- // geometry..
912
- buffers
913
- },
914
- fragment: {
915
- module: this._getModule(program.fragment.source),
916
- entryPoint: program.fragment.entryPoint,
917
- targets: blendModes
918
- },
919
- primitive: {
920
- topology,
921
- cullMode: state.cullMode
922
- },
923
- layout,
924
- multisample: {
925
- count: this._multisampleCount
926
- },
927
- // depthStencil,
928
- label: `PIXI Pipeline`
929
- };
930
- if (this._depthStencilAttachment) {
931
- descriptor.depthStencil = {
932
- ...this._stencilState,
933
- format: "depth24plus-stencil8",
934
- depthWriteEnabled: state.depthTest,
935
- depthCompare: state.depthTest ? "less" : "always"
936
- };
937
- }
938
- const pipeline = device.createRenderPipeline(descriptor);
939
- return pipeline;
940
- }
941
- _getModule(code) {
942
- return this._moduleCache[code] || this._createModule(code);
943
- }
944
- _createModule(code) {
945
- const device = this._gpu.device;
946
- this._moduleCache[code] = device.createShaderModule({
947
- code
948
- });
949
- return this._moduleCache[code];
950
- }
951
- _generateBufferKey(geometry) {
952
- const keyGen = [];
953
- let index = 0;
954
- const attributeKeys = Object.keys(geometry.attributes).sort();
955
- for (let i = 0; i < attributeKeys.length; i++) {
956
- const attribute = geometry.attributes[attributeKeys[i]];
957
- keyGen[index++] = attribute.offset;
958
- keyGen[index++] = attribute.format;
959
- keyGen[index++] = attribute.stride;
960
- keyGen[index++] = attribute.instance;
961
- }
962
- const stringKey = keyGen.join("|");
963
- geometry._layoutKey = createIdFromString(stringKey, "geometry");
964
- return geometry._layoutKey;
965
- }
966
- _generateAttributeLocationsKey(program) {
967
- const keyGen = [];
968
- let index = 0;
969
- const attributeKeys = Object.keys(program.attributeData).sort();
970
- for (let i = 0; i < attributeKeys.length; i++) {
971
- const attribute = program.attributeData[attributeKeys[i]];
972
- keyGen[index++] = attribute.location;
973
- }
974
- const stringKey = keyGen.join("|");
975
- program._attributeLocationsKey = createIdFromString(stringKey, "programAttributes");
976
- return program._attributeLocationsKey;
977
- }
978
- /**
979
- * Returns a hash of buffer names mapped to bind locations.
980
- * This is used to bind the correct buffer to the correct location in the shader.
981
- * @param geometry - The geometry where to get the buffer names
982
- * @param program - The program where to get the buffer names
983
- * @returns An object of buffer names mapped to the bind location.
984
- */
985
- getBufferNamesToBind(geometry, program) {
986
- const key = geometry._layoutKey << 16 | program._attributeLocationsKey;
987
- if (this._bindingNamesCache[key])
988
- return this._bindingNamesCache[key];
989
- const data = this._createVertexBufferLayouts(geometry, program);
990
- const bufferNamesToBind = /* @__PURE__ */ Object.create(null);
991
- const attributeData = program.attributeData;
992
- for (let i = 0; i < data.length; i++) {
993
- const attributes = Object.values(data[i].attributes);
994
- const shaderLocation = attributes[0].shaderLocation;
995
- for (const j in attributeData) {
996
- if (attributeData[j].location === shaderLocation) {
997
- bufferNamesToBind[i] = j;
998
- break;
999
- }
1000
- }
1001
- }
1002
- this._bindingNamesCache[key] = bufferNamesToBind;
1003
- return bufferNamesToBind;
1004
- }
1005
- _createVertexBufferLayouts(geometry, program) {
1006
- if (!program._attributeLocationsKey)
1007
- this._generateAttributeLocationsKey(program);
1008
- const key = geometry._layoutKey << 16 | program._attributeLocationsKey;
1009
- if (this._bufferLayoutsCache[key]) {
1010
- return this._bufferLayoutsCache[key];
1011
- }
1012
- const vertexBuffersLayout = [];
1013
- geometry.buffers.forEach((buffer) => {
1014
- const bufferEntry = {
1015
- arrayStride: 0,
1016
- stepMode: "vertex",
1017
- attributes: []
1018
- };
1019
- const bufferEntryAttributes = bufferEntry.attributes;
1020
- for (const i in program.attributeData) {
1021
- const attribute = geometry.attributes[i];
1022
- if ((attribute.divisor ?? 1) !== 1) {
1023
- warn(`Attribute ${i} has an invalid divisor value of '${attribute.divisor}'. WebGPU only supports a divisor value of 1`);
1024
- }
1025
- if (attribute.buffer === buffer) {
1026
- bufferEntry.arrayStride = attribute.stride;
1027
- bufferEntry.stepMode = attribute.instance ? "instance" : "vertex";
1028
- bufferEntryAttributes.push({
1029
- shaderLocation: program.attributeData[i].location,
1030
- offset: attribute.offset,
1031
- format: attribute.format
1032
- });
1033
- }
1034
- }
1035
- if (bufferEntryAttributes.length) {
1036
- vertexBuffersLayout.push(bufferEntry);
1037
- }
1038
- });
1039
- this._bufferLayoutsCache[key] = vertexBuffersLayout;
1040
- return vertexBuffersLayout;
1041
- }
1042
- _updatePipeHash() {
1043
- const key = getGlobalStateKey(
1044
- this._stencilMode,
1045
- this._multisampleCount,
1046
- this._colorMask,
1047
- this._depthStencilAttachment
1048
- );
1049
- if (!this._pipeStateCaches[key]) {
1050
- this._pipeStateCaches[key] = /* @__PURE__ */ Object.create(null);
1051
- }
1052
- this._pipeCache = this._pipeStateCaches[key];
1053
- }
1054
- destroy() {
1055
- this._renderer = null;
1056
- this._bufferLayoutsCache = null;
1057
- }
1058
- }
1059
- /** @ignore */
1060
- PipelineSystem.extension = {
1061
- type: [ExtensionType.WebGPUSystem],
1062
- name: "pipeline"
1063
- };
1064
-
1065
- class GpuRenderTarget {
1066
- constructor() {
1067
- this.contexts = [];
1068
- this.msaaTextures = [];
1069
- this.msaaSamples = 1;
1070
- }
1071
- }
1072
-
1073
- class GpuRenderTargetAdaptor {
1074
- init(renderer, renderTargetSystem) {
1075
- this._renderer = renderer;
1076
- this._renderTargetSystem = renderTargetSystem;
1077
- }
1078
- copyToTexture(sourceRenderSurfaceTexture, destinationTexture, originSrc, size, originDest) {
1079
- const renderer = this._renderer;
1080
- const baseGpuTexture = this._getGpuColorTexture(
1081
- sourceRenderSurfaceTexture
1082
- );
1083
- const backGpuTexture = renderer.texture.getGpuSource(
1084
- destinationTexture.source
1085
- );
1086
- renderer.encoder.commandEncoder.copyTextureToTexture(
1087
- {
1088
- texture: baseGpuTexture,
1089
- origin: originSrc
1090
- },
1091
- {
1092
- texture: backGpuTexture,
1093
- origin: originDest
1094
- },
1095
- size
1096
- );
1097
- return destinationTexture;
1098
- }
1099
- startRenderPass(renderTarget, clear = true, clearColor, viewport) {
1100
- const renderTargetSystem = this._renderTargetSystem;
1101
- const gpuRenderTarget = renderTargetSystem.getGpuRenderTarget(renderTarget);
1102
- const descriptor = this.getDescriptor(renderTarget, clear, clearColor);
1103
- gpuRenderTarget.descriptor = descriptor;
1104
- this._renderer.pipeline.setRenderTarget(gpuRenderTarget);
1105
- this._renderer.encoder.beginRenderPass(gpuRenderTarget);
1106
- this._renderer.encoder.setViewport(viewport);
1107
- }
1108
- finishRenderPass() {
1109
- this._renderer.encoder.endRenderPass();
1110
- }
1111
- /**
1112
- * returns the gpu texture for the first color texture in the render target
1113
- * mainly used by the filter manager to get copy the texture for blending
1114
- * @param renderTarget
1115
- * @returns a gpu texture
1116
- */
1117
- _getGpuColorTexture(renderTarget) {
1118
- const gpuRenderTarget = this._renderTargetSystem.getGpuRenderTarget(renderTarget);
1119
- if (gpuRenderTarget.contexts[0]) {
1120
- return gpuRenderTarget.contexts[0].getCurrentTexture();
1121
- }
1122
- return this._renderer.texture.getGpuSource(
1123
- renderTarget.colorTextures[0].source
1124
- );
1125
- }
1126
- getDescriptor(renderTarget, clear, clearValue) {
1127
- if (typeof clear === "boolean") {
1128
- clear = clear ? CLEAR.ALL : CLEAR.NONE;
1129
- }
1130
- const renderTargetSystem = this._renderTargetSystem;
1131
- const gpuRenderTarget = renderTargetSystem.getGpuRenderTarget(renderTarget);
1132
- const colorAttachments = renderTarget.colorTextures.map(
1133
- (texture, i) => {
1134
- const context = gpuRenderTarget.contexts[i];
1135
- let view;
1136
- let resolveTarget;
1137
- if (context) {
1138
- const currentTexture = context.getCurrentTexture();
1139
- const canvasTextureView = currentTexture.createView();
1140
- view = canvasTextureView;
1141
- } else {
1142
- view = this._renderer.texture.getGpuSource(texture).createView({
1143
- mipLevelCount: 1
1144
- });
1145
- }
1146
- if (gpuRenderTarget.msaaTextures[i]) {
1147
- resolveTarget = view;
1148
- view = this._renderer.texture.getTextureView(
1149
- gpuRenderTarget.msaaTextures[i]
1150
- );
1151
- }
1152
- const loadOp = clear & CLEAR.COLOR ? "clear" : "load";
1153
- clearValue ?? (clearValue = renderTargetSystem.defaultClearColor);
1154
- return {
1155
- view,
1156
- resolveTarget,
1157
- clearValue,
1158
- storeOp: "store",
1159
- loadOp
1160
- };
1161
- }
1162
- );
1163
- let depthStencilAttachment;
1164
- if ((renderTarget.stencil || renderTarget.depth) && !renderTarget.depthStencilTexture) {
1165
- renderTarget.ensureDepthStencilTexture();
1166
- renderTarget.depthStencilTexture.source.sampleCount = gpuRenderTarget.msaa ? 4 : 1;
1167
- }
1168
- if (renderTarget.depthStencilTexture) {
1169
- const stencilLoadOp = clear & CLEAR.STENCIL ? "clear" : "load";
1170
- const depthLoadOp = clear & CLEAR.DEPTH ? "clear" : "load";
1171
- depthStencilAttachment = {
1172
- view: this._renderer.texture.getGpuSource(renderTarget.depthStencilTexture.source).createView(),
1173
- stencilStoreOp: "store",
1174
- stencilLoadOp,
1175
- depthClearValue: 1,
1176
- depthLoadOp,
1177
- depthStoreOp: "store"
1178
- };
1179
- }
1180
- const descriptor = {
1181
- colorAttachments,
1182
- depthStencilAttachment
1183
- };
1184
- return descriptor;
1185
- }
1186
- clear(renderTarget, clear = true, clearColor, viewport) {
1187
- if (!clear)
1188
- return;
1189
- const { gpu, encoder } = this._renderer;
1190
- const device = gpu.device;
1191
- const standAlone = encoder.commandEncoder === null;
1192
- if (standAlone) {
1193
- const commandEncoder = device.createCommandEncoder();
1194
- const renderPassDescriptor = this.getDescriptor(renderTarget, clear, clearColor);
1195
- const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
1196
- passEncoder.setViewport(viewport.x, viewport.y, viewport.width, viewport.height, 0, 1);
1197
- passEncoder.end();
1198
- const gpuCommands = commandEncoder.finish();
1199
- device.queue.submit([gpuCommands]);
1200
- } else {
1201
- this.startRenderPass(renderTarget, clear, clearColor, viewport);
1202
- }
1203
- }
1204
- initGpuRenderTarget(renderTarget) {
1205
- renderTarget.isRoot = true;
1206
- const gpuRenderTarget = new GpuRenderTarget();
1207
- renderTarget.colorTextures.forEach((colorTexture, i) => {
1208
- if (colorTexture instanceof CanvasSource) {
1209
- const context = colorTexture.resource.getContext(
1210
- "webgpu"
1211
- );
1212
- const alphaMode = colorTexture.transparent ? "premultiplied" : "opaque";
1213
- try {
1214
- context.configure({
1215
- device: this._renderer.gpu.device,
1216
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
1217
- format: "bgra8unorm",
1218
- alphaMode
1219
- });
1220
- } catch (e) {
1221
- console.error(e);
1222
- }
1223
- gpuRenderTarget.contexts[i] = context;
1224
- }
1225
- gpuRenderTarget.msaa = colorTexture.source.antialias;
1226
- if (colorTexture.source.antialias) {
1227
- const msaaTexture = new TextureSource({
1228
- width: 0,
1229
- height: 0,
1230
- sampleCount: 4
1231
- });
1232
- gpuRenderTarget.msaaTextures[i] = msaaTexture;
1233
- }
1234
- });
1235
- if (gpuRenderTarget.msaa) {
1236
- gpuRenderTarget.msaaSamples = 4;
1237
- if (renderTarget.depthStencilTexture) {
1238
- renderTarget.depthStencilTexture.source.sampleCount = 4;
1239
- }
1240
- }
1241
- return gpuRenderTarget;
1242
- }
1243
- destroyGpuRenderTarget(gpuRenderTarget) {
1244
- gpuRenderTarget.contexts.forEach((context) => {
1245
- context.unconfigure();
1246
- });
1247
- gpuRenderTarget.msaaTextures.forEach((texture) => {
1248
- texture.destroy();
1249
- });
1250
- gpuRenderTarget.msaaTextures.length = 0;
1251
- gpuRenderTarget.contexts.length = 0;
1252
- }
1253
- ensureDepthStencilTexture(renderTarget) {
1254
- const gpuRenderTarget = this._renderTargetSystem.getGpuRenderTarget(renderTarget);
1255
- if (renderTarget.depthStencilTexture && gpuRenderTarget.msaa) {
1256
- renderTarget.depthStencilTexture.source.sampleCount = 4;
1257
- }
1258
- }
1259
- resizeGpuRenderTarget(renderTarget) {
1260
- const gpuRenderTarget = this._renderTargetSystem.getGpuRenderTarget(renderTarget);
1261
- gpuRenderTarget.width = renderTarget.width;
1262
- gpuRenderTarget.height = renderTarget.height;
1263
- if (gpuRenderTarget.msaa) {
1264
- renderTarget.colorTextures.forEach((colorTexture, i) => {
1265
- const msaaTexture = gpuRenderTarget.msaaTextures[i];
1266
- msaaTexture?.resize(
1267
- colorTexture.source.width,
1268
- colorTexture.source.height,
1269
- colorTexture.source._resolution
1270
- );
1271
- });
1272
- }
1273
- }
1274
- }
1275
-
1276
- class GpuRenderTargetSystem extends RenderTargetSystem {
1277
- constructor(renderer) {
1278
- super(renderer);
1279
- this.adaptor = new GpuRenderTargetAdaptor();
1280
- this.adaptor.init(renderer, this);
1281
- }
1282
- }
1283
- /** @ignore */
1284
- GpuRenderTargetSystem.extension = {
1285
- type: [ExtensionType.WebGPUSystem],
1286
- name: "renderTarget"
1287
- };
1288
-
1289
- class GpuShaderSystem {
1290
- constructor() {
1291
- this._gpuProgramData = /* @__PURE__ */ Object.create(null);
1292
- }
1293
- contextChange(gpu) {
1294
- this._gpu = gpu;
1295
- }
1296
- getProgramData(program) {
1297
- return this._gpuProgramData[program._layoutKey] || this._createGPUProgramData(program);
1298
- }
1299
- _createGPUProgramData(program) {
1300
- const device = this._gpu.device;
1301
- const bindGroups = program.gpuLayout.map((group) => device.createBindGroupLayout({ entries: group }));
1302
- const pipelineLayoutDesc = { bindGroupLayouts: bindGroups };
1303
- this._gpuProgramData[program._layoutKey] = {
1304
- bindGroups,
1305
- pipeline: device.createPipelineLayout(pipelineLayoutDesc)
1306
- };
1307
- return this._gpuProgramData[program._layoutKey];
1308
- }
1309
- destroy() {
1310
- this._gpu = null;
1311
- this._gpuProgramData = null;
1312
- }
1313
- }
1314
- /** @ignore */
1315
- GpuShaderSystem.extension = {
1316
- type: [
1317
- ExtensionType.WebGPUSystem
1318
- ],
1319
- name: "shader"
1320
- };
1321
-
1322
- const GpuBlendModesToPixi = {};
1323
- GpuBlendModesToPixi.normal = {
1324
- alpha: {
1325
- srcFactor: "one",
1326
- dstFactor: "one-minus-src-alpha",
1327
- operation: "add"
1328
- },
1329
- color: {
1330
- srcFactor: "one",
1331
- dstFactor: "one-minus-src-alpha",
1332
- operation: "add"
1333
- }
1334
- };
1335
- GpuBlendModesToPixi.add = {
1336
- alpha: {
1337
- srcFactor: "src-alpha",
1338
- dstFactor: "one-minus-src-alpha",
1339
- operation: "add"
1340
- },
1341
- color: {
1342
- srcFactor: "one",
1343
- dstFactor: "one",
1344
- operation: "add"
1345
- }
1346
- };
1347
- GpuBlendModesToPixi.multiply = {
1348
- alpha: {
1349
- srcFactor: "one",
1350
- dstFactor: "one-minus-src-alpha",
1351
- operation: "add"
1352
- },
1353
- color: {
1354
- srcFactor: "dst",
1355
- dstFactor: "one-minus-src-alpha",
1356
- operation: "add"
1357
- }
1358
- };
1359
- GpuBlendModesToPixi.screen = {
1360
- alpha: {
1361
- srcFactor: "one",
1362
- dstFactor: "one-minus-src-alpha",
1363
- operation: "add"
1364
- },
1365
- color: {
1366
- srcFactor: "one",
1367
- dstFactor: "one-minus-src",
1368
- operation: "add"
1369
- }
1370
- };
1371
- GpuBlendModesToPixi.overlay = {
1372
- alpha: {
1373
- srcFactor: "one",
1374
- dstFactor: "one-minus-src-alpha",
1375
- operation: "add"
1376
- },
1377
- color: {
1378
- srcFactor: "one",
1379
- dstFactor: "one-minus-src",
1380
- operation: "add"
1381
- }
1382
- };
1383
- GpuBlendModesToPixi.none = {
1384
- alpha: {
1385
- srcFactor: "one",
1386
- dstFactor: "one-minus-src-alpha",
1387
- operation: "add"
1388
- },
1389
- color: {
1390
- srcFactor: "zero",
1391
- dstFactor: "zero",
1392
- operation: "add"
1393
- }
1394
- };
1395
- GpuBlendModesToPixi["normal-npm"] = {
1396
- alpha: {
1397
- srcFactor: "one",
1398
- dstFactor: "one-minus-src-alpha",
1399
- operation: "add"
1400
- },
1401
- color: {
1402
- srcFactor: "src-alpha",
1403
- dstFactor: "one-minus-src-alpha",
1404
- operation: "add"
1405
- }
1406
- };
1407
- GpuBlendModesToPixi["add-npm"] = {
1408
- alpha: {
1409
- srcFactor: "one",
1410
- dstFactor: "one",
1411
- operation: "add"
1412
- },
1413
- color: {
1414
- srcFactor: "src-alpha",
1415
- dstFactor: "one",
1416
- operation: "add"
1417
- }
1418
- };
1419
- GpuBlendModesToPixi["screen-npm"] = {
1420
- alpha: {
1421
- srcFactor: "one",
1422
- dstFactor: "one-minus-src-alpha",
1423
- operation: "add"
1424
- },
1425
- color: {
1426
- srcFactor: "src-alpha",
1427
- dstFactor: "one-minus-src",
1428
- operation: "add"
1429
- }
1430
- };
1431
- GpuBlendModesToPixi.erase = {
1432
- alpha: {
1433
- srcFactor: "zero",
1434
- dstFactor: "one-minus-src-alpha",
1435
- operation: "add"
1436
- },
1437
- color: {
1438
- srcFactor: "zero",
1439
- dstFactor: "one-minus-src",
1440
- operation: "add"
1441
- }
1442
- };
1443
- GpuBlendModesToPixi.min = {
1444
- alpha: {
1445
- srcFactor: "one",
1446
- dstFactor: "one",
1447
- operation: "min"
1448
- },
1449
- color: {
1450
- srcFactor: "one",
1451
- dstFactor: "one",
1452
- operation: "min"
1453
- }
1454
- };
1455
- GpuBlendModesToPixi.max = {
1456
- alpha: {
1457
- srcFactor: "one",
1458
- dstFactor: "one",
1459
- operation: "max"
1460
- },
1461
- color: {
1462
- srcFactor: "one",
1463
- dstFactor: "one",
1464
- operation: "max"
1465
- }
1466
- };
1467
-
1468
- class GpuStateSystem {
1469
- constructor() {
1470
- this.defaultState = new State();
1471
- this.defaultState.blend = true;
1472
- }
1473
- contextChange(gpu) {
1474
- this.gpu = gpu;
1475
- }
1476
- /**
1477
- * Gets the blend mode data for the current state
1478
- * @param state - The state to get the blend mode from
1479
- */
1480
- getColorTargets(state) {
1481
- const blend = GpuBlendModesToPixi[state.blendMode] || GpuBlendModesToPixi.normal;
1482
- return [
1483
- {
1484
- format: "bgra8unorm",
1485
- writeMask: 0,
1486
- blend
1487
- }
1488
- ];
1489
- }
1490
- destroy() {
1491
- this.gpu = null;
1492
- }
1493
- }
1494
- /** @ignore */
1495
- GpuStateSystem.extension = {
1496
- type: [
1497
- ExtensionType.WebGPUSystem
1498
- ],
1499
- name: "state"
1500
- };
1501
-
1502
- const gpuUploadBufferImageResource = {
1503
- type: "image",
1504
- upload(source, gpuTexture, gpu) {
1505
- const resource = source.resource;
1506
- const total = (source.pixelWidth | 0) * (source.pixelHeight | 0);
1507
- const bytesPerPixel = resource.byteLength / total;
1508
- gpu.device.queue.writeTexture(
1509
- { texture: gpuTexture },
1510
- resource,
1511
- {
1512
- offset: 0,
1513
- rowsPerImage: source.pixelHeight,
1514
- bytesPerRow: source.pixelHeight * bytesPerPixel
1515
- },
1516
- {
1517
- width: source.pixelWidth,
1518
- height: source.pixelHeight,
1519
- depthOrArrayLayers: 1
1520
- }
1521
- );
1522
- }
1523
- };
1524
-
1525
- const blockDataMap = {
1526
- "bc1-rgba-unorm": { blockBytes: 8, blockWidth: 4, blockHeight: 4 },
1527
- "bc2-rgba-unorm": { blockBytes: 16, blockWidth: 4, blockHeight: 4 },
1528
- "bc3-rgba-unorm": { blockBytes: 16, blockWidth: 4, blockHeight: 4 },
1529
- "bc7-rgba-unorm": { blockBytes: 16, blockWidth: 4, blockHeight: 4 },
1530
- "etc1-rgb-unorm": { blockBytes: 8, blockWidth: 4, blockHeight: 4 },
1531
- "etc2-rgba8unorm": { blockBytes: 16, blockWidth: 4, blockHeight: 4 },
1532
- "astc-4x4-unorm": { blockBytes: 16, blockWidth: 4, blockHeight: 4 }
1533
- };
1534
- const defaultBlockData = { blockBytes: 4, blockWidth: 1, blockHeight: 1 };
1535
- const gpuUploadCompressedTextureResource = {
1536
- type: "compressed",
1537
- upload(source, gpuTexture, gpu) {
1538
- let mipWidth = source.pixelWidth;
1539
- let mipHeight = source.pixelHeight;
1540
- const blockData = blockDataMap[source.format] || defaultBlockData;
1541
- for (let i = 0; i < source.resource.length; i++) {
1542
- const levelBuffer = source.resource[i];
1543
- const bytesPerRow = Math.ceil(mipWidth / blockData.blockWidth) * blockData.blockBytes;
1544
- gpu.device.queue.writeTexture(
1545
- {
1546
- texture: gpuTexture,
1547
- mipLevel: i
1548
- },
1549
- levelBuffer,
1550
- {
1551
- offset: 0,
1552
- bytesPerRow
1553
- },
1554
- {
1555
- width: Math.ceil(mipWidth / blockData.blockWidth) * blockData.blockWidth,
1556
- height: Math.ceil(mipHeight / blockData.blockHeight) * blockData.blockHeight,
1557
- depthOrArrayLayers: 1
1558
- }
1559
- );
1560
- mipWidth = Math.max(mipWidth >> 1, 1);
1561
- mipHeight = Math.max(mipHeight >> 1, 1);
1562
- }
1563
- }
1564
- };
1565
-
1566
- const gpuUploadImageResource = {
1567
- type: "image",
1568
- upload(source, gpuTexture, gpu) {
1569
- const resource = source.resource;
1570
- if (!resource)
1571
- return;
1572
- if (globalThis.HTMLImageElement && resource instanceof HTMLImageElement) {
1573
- const canvas = DOMAdapter.get().createCanvas(resource.width, resource.height);
1574
- const context = canvas.getContext("2d");
1575
- context.drawImage(resource, 0, 0, resource.width, resource.height);
1576
- source.resource = canvas;
1577
- warn("ImageSource: Image element passed, converting to canvas and replacing resource.");
1578
- }
1579
- const width = Math.min(gpuTexture.width, source.resourceWidth || source.pixelWidth);
1580
- const height = Math.min(gpuTexture.height, source.resourceHeight || source.pixelHeight);
1581
- const premultipliedAlpha = source.alphaMode === "premultiply-alpha-on-upload";
1582
- gpu.device.queue.copyExternalImageToTexture(
1583
- { source: resource },
1584
- { texture: gpuTexture, premultipliedAlpha },
1585
- {
1586
- width,
1587
- height
1588
- }
1589
- );
1590
- }
1591
- };
1592
-
1593
- const gpuUploadVideoResource = {
1594
- type: "video",
1595
- upload(source, gpuTexture, gpu) {
1596
- gpuUploadImageResource.upload(source, gpuTexture, gpu);
1597
- }
1598
- };
1599
-
1600
- class GpuMipmapGenerator {
1601
- constructor(device) {
1602
- this.device = device;
1603
- this.sampler = device.createSampler({ minFilter: "linear" });
1604
- this.pipelines = {};
1605
- }
1606
- _getMipmapPipeline(format) {
1607
- let pipeline = this.pipelines[format];
1608
- if (!pipeline) {
1609
- if (!this.mipmapShaderModule) {
1610
- this.mipmapShaderModule = this.device.createShaderModule({
1611
- code: (
1612
- /* wgsl */
1613
- `
1614
- var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
1615
- vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
1616
-
1617
- struct VertexOutput {
1618
- @builtin(position) position : vec4<f32>,
1619
- @location(0) texCoord : vec2<f32>,
1620
- };
1621
-
1622
- @vertex
1623
- fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
1624
- var output : VertexOutput;
1625
- output.texCoord = pos[vertexIndex] * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);
1626
- output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
1627
- return output;
1628
- }
1629
-
1630
- @group(0) @binding(0) var imgSampler : sampler;
1631
- @group(0) @binding(1) var img : texture_2d<f32>;
1632
-
1633
- @fragment
1634
- fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
1635
- return textureSample(img, imgSampler, texCoord);
1636
- }
1637
- `
1638
- )
1639
- });
1640
- }
1641
- pipeline = this.device.createRenderPipeline({
1642
- layout: "auto",
1643
- vertex: {
1644
- module: this.mipmapShaderModule,
1645
- entryPoint: "vertexMain"
1646
- },
1647
- fragment: {
1648
- module: this.mipmapShaderModule,
1649
- entryPoint: "fragmentMain",
1650
- targets: [{ format }]
1651
- }
1652
- });
1653
- this.pipelines[format] = pipeline;
1654
- }
1655
- return pipeline;
1656
- }
1657
- /**
1658
- * Generates mipmaps for the given GPUTexture from the data in level 0.
1659
- * @param {module:External.GPUTexture} texture - Texture to generate mipmaps for.
1660
- * @returns {module:External.GPUTexture} - The originally passed texture
1661
- */
1662
- generateMipmap(texture) {
1663
- const pipeline = this._getMipmapPipeline(texture.format);
1664
- if (texture.dimension === "3d" || texture.dimension === "1d") {
1665
- throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");
1666
- }
1667
- let mipTexture = texture;
1668
- const arrayLayerCount = texture.depthOrArrayLayers || 1;
1669
- const renderToSource = texture.usage & GPUTextureUsage.RENDER_ATTACHMENT;
1670
- if (!renderToSource) {
1671
- const mipTextureDescriptor = {
1672
- size: {
1673
- width: Math.ceil(texture.width / 2),
1674
- height: Math.ceil(texture.height / 2),
1675
- depthOrArrayLayers: arrayLayerCount
1676
- },
1677
- format: texture.format,
1678
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
1679
- mipLevelCount: texture.mipLevelCount - 1
1680
- };
1681
- mipTexture = this.device.createTexture(mipTextureDescriptor);
1682
- }
1683
- const commandEncoder = this.device.createCommandEncoder({});
1684
- const bindGroupLayout = pipeline.getBindGroupLayout(0);
1685
- for (let arrayLayer = 0; arrayLayer < arrayLayerCount; ++arrayLayer) {
1686
- let srcView = texture.createView({
1687
- baseMipLevel: 0,
1688
- mipLevelCount: 1,
1689
- dimension: "2d",
1690
- baseArrayLayer: arrayLayer,
1691
- arrayLayerCount: 1
1692
- });
1693
- let dstMipLevel = renderToSource ? 1 : 0;
1694
- for (let i = 1; i < texture.mipLevelCount; ++i) {
1695
- const dstView = mipTexture.createView({
1696
- baseMipLevel: dstMipLevel++,
1697
- mipLevelCount: 1,
1698
- dimension: "2d",
1699
- baseArrayLayer: arrayLayer,
1700
- arrayLayerCount: 1
1701
- });
1702
- const passEncoder = commandEncoder.beginRenderPass({
1703
- colorAttachments: [{
1704
- view: dstView,
1705
- storeOp: "store",
1706
- loadOp: "clear",
1707
- clearValue: { r: 0, g: 0, b: 0, a: 0 }
1708
- }]
1709
- });
1710
- const bindGroup = this.device.createBindGroup({
1711
- layout: bindGroupLayout,
1712
- entries: [{
1713
- binding: 0,
1714
- resource: this.sampler
1715
- }, {
1716
- binding: 1,
1717
- resource: srcView
1718
- }]
1719
- });
1720
- passEncoder.setPipeline(pipeline);
1721
- passEncoder.setBindGroup(0, bindGroup);
1722
- passEncoder.draw(3, 1, 0, 0);
1723
- passEncoder.end();
1724
- srcView = dstView;
1725
- }
1726
- }
1727
- if (!renderToSource) {
1728
- const mipLevelSize = {
1729
- width: Math.ceil(texture.width / 2),
1730
- height: Math.ceil(texture.height / 2),
1731
- depthOrArrayLayers: arrayLayerCount
1732
- };
1733
- for (let i = 1; i < texture.mipLevelCount; ++i) {
1734
- commandEncoder.copyTextureToTexture({
1735
- texture: mipTexture,
1736
- mipLevel: i - 1
1737
- }, {
1738
- texture,
1739
- mipLevel: i
1740
- }, mipLevelSize);
1741
- mipLevelSize.width = Math.ceil(mipLevelSize.width / 2);
1742
- mipLevelSize.height = Math.ceil(mipLevelSize.height / 2);
1743
- }
1744
- }
1745
- this.device.queue.submit([commandEncoder.finish()]);
1746
- if (!renderToSource) {
1747
- mipTexture.destroy();
1748
- }
1749
- return texture;
1750
- }
1751
- }
1752
-
1753
- class GpuTextureSystem {
1754
- constructor(renderer) {
1755
- this.managedTextures = [];
1756
- this._gpuSources = /* @__PURE__ */ Object.create(null);
1757
- this._gpuSamplers = /* @__PURE__ */ Object.create(null);
1758
- this._bindGroupHash = /* @__PURE__ */ Object.create(null);
1759
- this._textureViewHash = /* @__PURE__ */ Object.create(null);
1760
- this._uploads = {
1761
- image: gpuUploadImageResource,
1762
- buffer: gpuUploadBufferImageResource,
1763
- video: gpuUploadVideoResource,
1764
- compressed: gpuUploadCompressedTextureResource
1765
- };
1766
- this._renderer = renderer;
1767
- renderer.renderableGC.addManagedHash(this, "_gpuSources");
1768
- renderer.renderableGC.addManagedHash(this, "_gpuSamplers");
1769
- renderer.renderableGC.addManagedHash(this, "_bindGroupHash");
1770
- renderer.renderableGC.addManagedHash(this, "_textureViewHash");
1771
- }
1772
- contextChange(gpu) {
1773
- this._gpu = gpu;
1774
- }
1775
- initSource(source) {
1776
- if (source.autoGenerateMipmaps) {
1777
- const biggestDimension = Math.max(source.pixelWidth, source.pixelHeight);
1778
- source.mipLevelCount = Math.floor(Math.log2(biggestDimension)) + 1;
1779
- }
1780
- let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;
1781
- if (source.uploadMethodId !== "compressed") {
1782
- usage |= GPUTextureUsage.RENDER_ATTACHMENT;
1783
- usage |= GPUTextureUsage.COPY_SRC;
1784
- }
1785
- const blockData = blockDataMap[source.format] || { blockBytes: 4, blockWidth: 1, blockHeight: 1 };
1786
- const width = Math.ceil(source.pixelWidth / blockData.blockWidth) * blockData.blockWidth;
1787
- const height = Math.ceil(source.pixelHeight / blockData.blockHeight) * blockData.blockHeight;
1788
- const textureDescriptor = {
1789
- label: source.label,
1790
- size: { width, height },
1791
- format: source.format,
1792
- sampleCount: source.sampleCount,
1793
- mipLevelCount: source.mipLevelCount,
1794
- dimension: source.dimension,
1795
- usage
1796
- };
1797
- const gpuTexture = this._gpu.device.createTexture(textureDescriptor);
1798
- this._gpuSources[source.uid] = gpuTexture;
1799
- if (!this.managedTextures.includes(source)) {
1800
- source.on("update", this.onSourceUpdate, this);
1801
- source.on("resize", this.onSourceResize, this);
1802
- source.on("destroy", this.onSourceDestroy, this);
1803
- source.on("unload", this.onSourceUnload, this);
1804
- source.on("updateMipmaps", this.onUpdateMipmaps, this);
1805
- this.managedTextures.push(source);
1806
- }
1807
- this.onSourceUpdate(source);
1808
- return gpuTexture;
1809
- }
1810
- onSourceUpdate(source) {
1811
- const gpuTexture = this.getGpuSource(source);
1812
- if (!gpuTexture)
1813
- return;
1814
- if (this._uploads[source.uploadMethodId]) {
1815
- this._uploads[source.uploadMethodId].upload(source, gpuTexture, this._gpu);
1816
- }
1817
- if (source.autoGenerateMipmaps && source.mipLevelCount > 1) {
1818
- this.onUpdateMipmaps(source);
1819
- }
1820
- }
1821
- onSourceUnload(source) {
1822
- const gpuTexture = this._gpuSources[source.uid];
1823
- if (gpuTexture) {
1824
- this._gpuSources[source.uid] = null;
1825
- gpuTexture.destroy();
1826
- }
1827
- }
1828
- onUpdateMipmaps(source) {
1829
- if (!this._mipmapGenerator) {
1830
- this._mipmapGenerator = new GpuMipmapGenerator(this._gpu.device);
1831
- }
1832
- const gpuTexture = this.getGpuSource(source);
1833
- this._mipmapGenerator.generateMipmap(gpuTexture);
1834
- }
1835
- onSourceDestroy(source) {
1836
- source.off("update", this.onSourceUpdate, this);
1837
- source.off("unload", this.onSourceUnload, this);
1838
- source.off("destroy", this.onSourceDestroy, this);
1839
- source.off("resize", this.onSourceResize, this);
1840
- source.off("updateMipmaps", this.onUpdateMipmaps, this);
1841
- this.managedTextures.splice(this.managedTextures.indexOf(source), 1);
1842
- this.onSourceUnload(source);
1843
- }
1844
- onSourceResize(source) {
1845
- const gpuTexture = this._gpuSources[source.uid];
1846
- if (!gpuTexture) {
1847
- this.initSource(source);
1848
- } else if (gpuTexture.width !== source.pixelWidth || gpuTexture.height !== source.pixelHeight) {
1849
- this._textureViewHash[source.uid] = null;
1850
- this._bindGroupHash[source.uid] = null;
1851
- this.onSourceUnload(source);
1852
- this.initSource(source);
1853
- }
1854
- }
1855
- _initSampler(sampler) {
1856
- this._gpuSamplers[sampler._resourceId] = this._gpu.device.createSampler(sampler);
1857
- return this._gpuSamplers[sampler._resourceId];
1858
- }
1859
- getGpuSampler(sampler) {
1860
- return this._gpuSamplers[sampler._resourceId] || this._initSampler(sampler);
1861
- }
1862
- getGpuSource(source) {
1863
- return this._gpuSources[source.uid] || this.initSource(source);
1864
- }
1865
- /**
1866
- * this returns s bind group for a specific texture, the bind group contains
1867
- * - the texture source
1868
- * - the texture style
1869
- * - the texture matrix
1870
- * This is cached so the bind group should only be created once per texture
1871
- * @param texture - the texture you want the bindgroup for
1872
- * @returns the bind group for the texture
1873
- */
1874
- getTextureBindGroup(texture) {
1875
- return this._bindGroupHash[texture.uid] ?? this._createTextureBindGroup(texture);
1876
- }
1877
- _createTextureBindGroup(texture) {
1878
- const source = texture.source;
1879
- this._bindGroupHash[texture.uid] = new BindGroup({
1880
- 0: source,
1881
- 1: source.style,
1882
- 2: new UniformGroup({
1883
- uTextureMatrix: { type: "mat3x3<f32>", value: texture.textureMatrix.mapCoord }
1884
- })
1885
- });
1886
- return this._bindGroupHash[texture.uid];
1887
- }
1888
- getTextureView(texture) {
1889
- const source = texture.source;
1890
- return this._textureViewHash[source.uid] ?? this._createTextureView(source);
1891
- }
1892
- _createTextureView(texture) {
1893
- this._textureViewHash[texture.uid] = this.getGpuSource(texture).createView();
1894
- return this._textureViewHash[texture.uid];
1895
- }
1896
- generateCanvas(texture) {
1897
- const renderer = this._renderer;
1898
- const commandEncoder = renderer.gpu.device.createCommandEncoder();
1899
- const canvas = DOMAdapter.get().createCanvas();
1900
- canvas.width = texture.source.pixelWidth;
1901
- canvas.height = texture.source.pixelHeight;
1902
- const context = canvas.getContext("webgpu");
1903
- context.configure({
1904
- device: renderer.gpu.device,
1905
- usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC,
1906
- format: DOMAdapter.get().getNavigator().gpu.getPreferredCanvasFormat(),
1907
- alphaMode: "premultiplied"
1908
- });
1909
- commandEncoder.copyTextureToTexture({
1910
- texture: renderer.texture.getGpuSource(texture.source),
1911
- origin: {
1912
- x: 0,
1913
- y: 0
1914
- }
1915
- }, {
1916
- texture: context.getCurrentTexture()
1917
- }, {
1918
- width: canvas.width,
1919
- height: canvas.height
1920
- });
1921
- renderer.gpu.device.queue.submit([commandEncoder.finish()]);
1922
- return canvas;
1923
- }
1924
- getPixels(texture) {
1925
- const webGPUCanvas = this.generateCanvas(texture);
1926
- const canvasAndContext = CanvasPool.getOptimalCanvasAndContext(webGPUCanvas.width, webGPUCanvas.height);
1927
- const context = canvasAndContext.context;
1928
- context.drawImage(webGPUCanvas, 0, 0);
1929
- const { width, height } = webGPUCanvas;
1930
- const imageData = context.getImageData(0, 0, width, height);
1931
- const pixels = new Uint8ClampedArray(imageData.data.buffer);
1932
- CanvasPool.returnCanvasAndContext(canvasAndContext);
1933
- return { pixels, width, height };
1934
- }
1935
- destroy() {
1936
- this.managedTextures.slice().forEach((source) => this.onSourceDestroy(source));
1937
- this.managedTextures = null;
1938
- for (const k of Object.keys(this._bindGroupHash)) {
1939
- const key = Number(k);
1940
- const bindGroup = this._bindGroupHash[key];
1941
- bindGroup?.destroy();
1942
- this._bindGroupHash[key] = null;
1943
- }
1944
- this._gpu = null;
1945
- this._mipmapGenerator = null;
1946
- this._gpuSources = null;
1947
- this._bindGroupHash = null;
1948
- this._textureViewHash = null;
1949
- this._gpuSamplers = null;
1950
- }
1951
- }
1952
- /** @ignore */
1953
- GpuTextureSystem.extension = {
1954
- type: [
1955
- ExtensionType.WebGPUSystem
1956
- ],
1957
- name: "texture"
1958
- };
1959
-
1960
- class GpuGraphicsAdaptor {
1961
- constructor() {
1962
- this._maxTextures = 0;
1963
- }
1964
- contextChange(renderer) {
1965
- const localUniforms = new UniformGroup({
1966
- uTransformMatrix: { value: new Matrix(), type: "mat3x3<f32>" },
1967
- uColor: { value: new Float32Array([1, 1, 1, 1]), type: "vec4<f32>" },
1968
- uRound: { value: 0, type: "f32" }
1969
- });
1970
- this._maxTextures = renderer.limits.maxBatchableTextures;
1971
- const gpuProgram = compileHighShaderGpuProgram({
1972
- name: "graphics",
1973
- bits: [
1974
- colorBit,
1975
- generateTextureBatchBit(this._maxTextures),
1976
- localUniformBitGroup2,
1977
- roundPixelsBit
1978
- ]
1979
- });
1980
- this.shader = new Shader({
1981
- gpuProgram,
1982
- resources: {
1983
- // added on the fly!
1984
- localUniforms
1985
- }
1986
- });
1987
- }
1988
- execute(graphicsPipe, renderable) {
1989
- const context = renderable.context;
1990
- const shader = context.customShader || this.shader;
1991
- const renderer = graphicsPipe.renderer;
1992
- const contextSystem = renderer.graphicsContext;
1993
- const {
1994
- batcher,
1995
- instructions
1996
- } = contextSystem.getContextRenderData(context);
1997
- const encoder = renderer.encoder;
1998
- encoder.setGeometry(batcher.geometry, shader.gpuProgram);
1999
- const globalUniformsBindGroup = renderer.globalUniforms.bindGroup;
2000
- encoder.setBindGroup(0, globalUniformsBindGroup, shader.gpuProgram);
2001
- const localBindGroup = renderer.renderPipes.uniformBatch.getUniformBindGroup(shader.resources.localUniforms, true);
2002
- encoder.setBindGroup(2, localBindGroup, shader.gpuProgram);
2003
- const batches = instructions.instructions;
2004
- let topology = null;
2005
- for (let i = 0; i < instructions.instructionSize; i++) {
2006
- const batch = batches[i];
2007
- if (batch.topology !== topology) {
2008
- topology = batch.topology;
2009
- encoder.setPipelineFromGeometryProgramAndState(
2010
- batcher.geometry,
2011
- shader.gpuProgram,
2012
- graphicsPipe.state,
2013
- batch.topology
2014
- );
2015
- }
2016
- shader.groups[1] = batch.bindGroup;
2017
- if (!batch.gpuBindGroup) {
2018
- const textureBatch = batch.textures;
2019
- batch.bindGroup = getTextureBatchBindGroup(
2020
- textureBatch.textures,
2021
- textureBatch.count,
2022
- this._maxTextures
2023
- );
2024
- batch.gpuBindGroup = renderer.bindGroup.getBindGroup(
2025
- batch.bindGroup,
2026
- shader.gpuProgram,
2027
- 1
2028
- );
2029
- }
2030
- encoder.setBindGroup(1, batch.bindGroup, shader.gpuProgram);
2031
- encoder.renderPassEncoder.drawIndexed(batch.size, 1, batch.start);
2032
- }
2033
- }
2034
- destroy() {
2035
- this.shader.destroy(true);
2036
- this.shader = null;
2037
- }
2038
- }
2039
- /** @ignore */
2040
- GpuGraphicsAdaptor.extension = {
2041
- type: [
2042
- ExtensionType.WebGPUPipesAdaptor
2043
- ],
2044
- name: "graphics"
2045
- };
2046
-
2047
- class GpuMeshAdapter {
2048
- init() {
2049
- const gpuProgram = compileHighShaderGpuProgram({
2050
- name: "mesh",
2051
- bits: [
2052
- localUniformBit,
2053
- textureBit,
2054
- roundPixelsBit
2055
- ]
2056
- });
2057
- this._shader = new Shader({
2058
- gpuProgram,
2059
- resources: {
2060
- uTexture: Texture.EMPTY._source,
2061
- uSampler: Texture.EMPTY._source.style,
2062
- textureUniforms: {
2063
- uTextureMatrix: { type: "mat3x3<f32>", value: new Matrix() }
2064
- }
2065
- }
2066
- });
2067
- }
2068
- execute(meshPipe, mesh) {
2069
- const renderer = meshPipe.renderer;
2070
- let shader = mesh._shader;
2071
- if (!shader) {
2072
- shader = this._shader;
2073
- shader.groups[2] = renderer.texture.getTextureBindGroup(mesh.texture);
2074
- } else if (!shader.gpuProgram) {
2075
- warn("Mesh shader has no gpuProgram", mesh.shader);
2076
- return;
2077
- }
2078
- const gpuProgram = shader.gpuProgram;
2079
- if (gpuProgram.autoAssignGlobalUniforms) {
2080
- shader.groups[0] = renderer.globalUniforms.bindGroup;
2081
- }
2082
- if (gpuProgram.autoAssignLocalUniforms) {
2083
- const localUniforms = meshPipe.localUniforms;
2084
- shader.groups[1] = renderer.renderPipes.uniformBatch.getUniformBindGroup(localUniforms, true);
2085
- }
2086
- renderer.encoder.draw({
2087
- geometry: mesh._geometry,
2088
- shader,
2089
- state: mesh.state
2090
- });
2091
- }
2092
- destroy() {
2093
- this._shader.destroy(true);
2094
- this._shader = null;
2095
- }
2096
- }
2097
- /** @ignore */
2098
- GpuMeshAdapter.extension = {
2099
- type: [
2100
- ExtensionType.WebGPUPipesAdaptor
2101
- ],
2102
- name: "mesh"
2103
- };
2104
-
2105
- const DefaultWebGPUSystems = [
2106
- ...SharedSystems,
2107
- GpuUboSystem,
2108
- GpuEncoderSystem,
2109
- GpuDeviceSystem,
2110
- GpuLimitsSystem,
2111
- GpuBufferSystem,
2112
- GpuTextureSystem,
2113
- GpuRenderTargetSystem,
2114
- GpuShaderSystem,
2115
- GpuStateSystem,
2116
- PipelineSystem,
2117
- GpuColorMaskSystem,
2118
- GpuStencilSystem,
2119
- BindGroupSystem
2120
- ];
2121
- const DefaultWebGPUPipes = [...SharedRenderPipes, GpuUniformBatchPipe];
2122
- const DefaultWebGPUAdapters = [GpuBatchAdaptor, GpuMeshAdapter, GpuGraphicsAdaptor];
2123
- const systems = [];
2124
- const renderPipes = [];
2125
- const renderPipeAdaptors = [];
2126
- extensions.handleByNamedList(ExtensionType.WebGPUSystem, systems);
2127
- extensions.handleByNamedList(ExtensionType.WebGPUPipes, renderPipes);
2128
- extensions.handleByNamedList(ExtensionType.WebGPUPipesAdaptor, renderPipeAdaptors);
2129
- extensions.add(...DefaultWebGPUSystems, ...DefaultWebGPUPipes, ...DefaultWebGPUAdapters);
2130
- class WebGPURenderer extends AbstractRenderer {
2131
- constructor() {
2132
- const systemConfig = {
2133
- name: "webgpu",
2134
- type: RendererType.WEBGPU,
2135
- systems,
2136
- renderPipes,
2137
- renderPipeAdaptors
2138
- };
2139
- super(systemConfig);
2140
- }
2141
- }
2142
-
2143
- export { WebGPURenderer };