matrix-engine-wgpu 1.0.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.
@@ -0,0 +1,456 @@
1
+ import {BALL_SHADER} from "../shaders/shaders";
2
+ import {mat4, vec3} from 'wgpu-matrix';
3
+ import {Position} from "./matrix-class";
4
+
5
+ export default class MEBall {
6
+
7
+ constructor(canvas, device, context, o) {
8
+ this.context = context;
9
+ this.device = device;
10
+
11
+ this.SphereLayout = {
12
+ vertexStride: 8 * 4,
13
+ positionsOffset: 0,
14
+ normalOffset: 3 * 4,
15
+ uvOffset: 6 * 4,
16
+ };
17
+
18
+ this.texturesPaths = [];
19
+
20
+ o.texturesPaths.forEach((t) => {
21
+ this.texturesPaths.push(t)
22
+ })
23
+
24
+ this.position = new Position(o.position.x, o.position.y, o.position.z)
25
+ this.shaderModule = device.createShaderModule({code: BALL_SHADER});
26
+ this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
27
+
28
+ this.pipeline = device.createRenderPipeline({
29
+ layout: 'auto',
30
+ vertex: {
31
+ module: this.shaderModule,
32
+ entryPoint: 'vertexMain',
33
+ buffers: [
34
+ {
35
+ arrayStride: this.SphereLayout.vertexStride,
36
+ attributes: [
37
+ {
38
+ // position
39
+ shaderLocation: 0,
40
+ offset: this.SphereLayout.positionsOffset,
41
+ format: 'float32x3',
42
+ },
43
+ {
44
+ // normal
45
+ shaderLocation: 1,
46
+ offset: this.SphereLayout.normalOffset,
47
+ format: 'float32x3',
48
+ },
49
+ {
50
+ // uv
51
+ shaderLocation: 2,
52
+ offset: this.SphereLayout.uvOffset,
53
+ format: 'float32x2',
54
+ },
55
+ ],
56
+ },
57
+ ],
58
+ },
59
+ fragment: {
60
+ module: this.shaderModule,
61
+ entryPoint: 'fragmentMain',
62
+ targets: [
63
+ {
64
+ format: this.presentationFormat,
65
+ },
66
+ ],
67
+ },
68
+ primitive: {
69
+ topology: 'triangle-list',
70
+
71
+ // Backface culling since the sphere is solid piece of geometry.
72
+ // Faces pointing away from the camera will be occluded by faces
73
+ // pointing toward the camera.
74
+ cullMode: 'back',
75
+ },
76
+
77
+ // Enable depth testing so that the fragment closest to the camera
78
+ // is rendered in front.
79
+ depthStencil: {
80
+ depthWriteEnabled: true,
81
+ depthCompare: 'less',
82
+ format: 'depth24plus',
83
+ },
84
+ });
85
+
86
+ this.depthTexture = device.createTexture({
87
+ size: [canvas.width, canvas.height],
88
+ format: 'depth24plus',
89
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
90
+ });
91
+
92
+ this.uniformBufferSize = 4 * 16; // 4x4 matrix
93
+ this.uniformBuffer = device.createBuffer({
94
+ size: this.uniformBufferSize,
95
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
96
+ });
97
+
98
+ // Fetch the images and upload them into a GPUTexture.
99
+ this.texture0 = null;
100
+ this.moonTexture = null;
101
+
102
+ this.settings = {
103
+ useRenderBundles: true,
104
+ asteroidCount: 15,
105
+ };
106
+
107
+ this.loadTex0(this.texturesPaths, device).then(() => {
108
+ this.loadTex1(device).then(() => {
109
+
110
+ console.log('NICE THIS', this)
111
+ this.sampler = device.createSampler({
112
+ magFilter: 'linear',
113
+ minFilter: 'linear',
114
+ });
115
+
116
+ this.transform = mat4.create();
117
+ mat4.identity(this.transform);
118
+
119
+ // Create one large central planet surrounded by a large ring of asteroids
120
+ this.planet = this.createSphereRenderable(1.0);
121
+ this.planet.bindGroup = this.createSphereBindGroup(this.texture0, this.transform);
122
+
123
+ var asteroids = [
124
+ this.createSphereRenderable(0.2, 8, 6, 0.15),
125
+ this.createSphereRenderable(0.13, 8, 6, 0.15)
126
+ ];
127
+
128
+ this.renderables = [this.planet];
129
+
130
+ // this.ensureEnoughAsteroids(asteroids, this.transform);
131
+
132
+ this.renderPassDescriptor = {
133
+ colorAttachments: [
134
+ {
135
+ view: undefined, // Assigned later
136
+
137
+ clearValue: {r: 0.0, g: 0.0, b: 0.0, a: 1.0},
138
+ loadOp: 'clear',
139
+ storeOp: 'store',
140
+ },
141
+ ],
142
+ depthStencilAttachment: {
143
+ view: this.depthTexture.createView(),
144
+
145
+ depthClearValue: 1.0,
146
+ depthLoadOp: 'clear',
147
+ depthStoreOp: 'store',
148
+ },
149
+ };
150
+
151
+ const aspect = canvas.width / canvas.height;
152
+ this.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 100.0);
153
+ this.modelViewProjectionMatrix = mat4.create();
154
+
155
+ this.frameBindGroup = device.createBindGroup({
156
+ layout: this.pipeline.getBindGroupLayout(0),
157
+ entries: [
158
+ {
159
+ binding: 0,
160
+ resource: {
161
+ buffer: this.uniformBuffer,
162
+ },
163
+ },
164
+ ],
165
+ });
166
+
167
+
168
+ // The render bundle can be encoded once and re-used as many times as needed.
169
+ // Because it encodes all of the commands needed to render at the GPU level,
170
+ // those commands will not need to execute the associated JavaScript code upon
171
+ // execution or be re-validated, which can represent a significant time savings.
172
+ //
173
+ // However, because render bundles are immutable once created, they are only
174
+ // appropriate for rendering content where the same commands will be executed
175
+ // every time, with the only changes being the contents of the buffers and
176
+ // textures used. Cases where the executed commands differ from frame-to-frame,
177
+ // such as when using frustrum or occlusion culling, will not benefit from
178
+ // using render bundles as much.
179
+ this.renderBundle;
180
+ this.updateRenderBundle();
181
+
182
+ })
183
+ })
184
+
185
+ }
186
+
187
+ ensureEnoughAsteroids(asteroids, transform) {
188
+ for(let i = this.renderables.length;i <= this.settings.asteroidCount;++i) {
189
+ // Place copies of the asteroid in a ring.
190
+ const radius = Math.random() * 1.7 + 1.25;
191
+ const angle = Math.random() * Math.PI * 2;
192
+ const x = Math.sin(angle) * radius;
193
+ const y = (Math.random() - 0.5) * 0.015;
194
+ const z = Math.cos(angle) * radius;
195
+
196
+ mat4.identity(transform);
197
+ mat4.translate(transform, [x, y, z], transform);
198
+ mat4.rotateX(transform, Math.random() * Math.PI, transform);
199
+ mat4.rotateY(transform, Math.random() * Math.PI, transform);
200
+ this.renderables.push({
201
+ ...asteroids[i % asteroids.length],
202
+ bindGroup: this.createSphereBindGroup(this.moonTexture, transform),
203
+ });
204
+ }
205
+ }
206
+
207
+ updateRenderBundle() {
208
+ console.log('updateRenderBundle')
209
+ const renderBundleEncoder = this.device.createRenderBundleEncoder({
210
+ colorFormats: [this.presentationFormat],
211
+ depthStencilFormat: 'depth24plus',
212
+ });
213
+ this.renderScene(renderBundleEncoder);
214
+ this.renderBundle = renderBundleEncoder.finish();
215
+ }
216
+
217
+ createSphereRenderable(radius, widthSegments = 8, heightSegments = 4, randomness = 0) {
218
+
219
+ const sphereMesh = this.createSphereMesh(radius, widthSegments, heightSegments, randomness);
220
+ // Create a vertex buffer from the sphere data.
221
+ const vertices = this.device.createBuffer({
222
+ size: sphereMesh.vertices.byteLength,
223
+ usage: GPUBufferUsage.VERTEX,
224
+ mappedAtCreation: true,
225
+ });
226
+ new Float32Array(vertices.getMappedRange()).set(sphereMesh.vertices);
227
+ vertices.unmap();
228
+
229
+ const indices = this.device.createBuffer({
230
+ size: sphereMesh.indices.byteLength,
231
+ usage: GPUBufferUsage.INDEX,
232
+ mappedAtCreation: true,
233
+ });
234
+ new Uint16Array(indices.getMappedRange()).set(sphereMesh.indices);
235
+ indices.unmap();
236
+
237
+ return {
238
+ vertices,
239
+ indices,
240
+ indexCount: sphereMesh.indices.length,
241
+ };
242
+ }
243
+
244
+ createSphereBindGroup(texture, transform) {
245
+
246
+ const uniformBufferSize = 4 * 16; // 4x4 matrix
247
+ const uniformBuffer = this.device.createBuffer({
248
+ size: uniformBufferSize,
249
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
250
+ mappedAtCreation: true,
251
+ });
252
+ new Float32Array(uniformBuffer.getMappedRange()).set(transform);
253
+ uniformBuffer.unmap();
254
+
255
+ const bindGroup = this.device.createBindGroup({
256
+ layout: this.pipeline.getBindGroupLayout(1),
257
+ entries: [
258
+ {
259
+ binding: 0,
260
+ resource: {
261
+ buffer: uniformBuffer,
262
+ },
263
+ },
264
+ {
265
+ binding: 1,
266
+ resource: this.sampler,
267
+ },
268
+ {
269
+ binding: 2,
270
+ resource: texture.createView(),
271
+ },
272
+ ],
273
+ });
274
+
275
+ return bindGroup;
276
+ }
277
+
278
+ getTransformationMatrix(pos) {
279
+
280
+ const viewMatrix = mat4.identity();
281
+ mat4.translate(viewMatrix, vec3.fromValues(pos.x, pos.y, pos.z), viewMatrix);
282
+ const now = Date.now() / 1000;
283
+
284
+ mat4.rotateZ(viewMatrix, Math.PI * 0.1, viewMatrix);
285
+ mat4.rotateX(viewMatrix, Math.PI * 0.1, viewMatrix);
286
+ mat4.rotateY(viewMatrix, now * 0.05, viewMatrix);
287
+
288
+ mat4.multiply(this.projectionMatrix, viewMatrix, this.modelViewProjectionMatrix);
289
+ return this.modelViewProjectionMatrix;
290
+ }
291
+
292
+ async loadTex1(device) {
293
+ return new Promise(async (resolve) => {
294
+ const response = await fetch('./res/textures/tex1.jpg');
295
+ const imageBitmap = await createImageBitmap(await response.blob());
296
+
297
+ this.moonTexture = device.createTexture({
298
+ size: [imageBitmap.width, imageBitmap.height, 1],
299
+ format: 'rgba8unorm',
300
+ usage:
301
+ GPUTextureUsage.TEXTURE_BINDING |
302
+ GPUTextureUsage.COPY_DST |
303
+ GPUTextureUsage.RENDER_ATTACHMENT,
304
+ });
305
+ var moonTexture = this.moonTexture
306
+ device.queue.copyExternalImageToTexture(
307
+ {source: imageBitmap},
308
+ {texture: moonTexture},
309
+ [imageBitmap.width, imageBitmap.height]
310
+ );
311
+ resolve()
312
+ })
313
+ }
314
+
315
+ async loadTex0(paths, device) {
316
+ return new Promise(async (resolve) => {
317
+ const response = await fetch(paths[0]);
318
+ const imageBitmap = await createImageBitmap(await response.blob());
319
+ console.log('loadTex0 WHAT IS THIS -> ', this)
320
+ this.texture0 = device.createTexture({
321
+ size: [imageBitmap.width, imageBitmap.height, 1],
322
+ format: 'rgba8unorm',
323
+ usage:
324
+ GPUTextureUsage.TEXTURE_BINDING |
325
+ GPUTextureUsage.COPY_DST |
326
+ GPUTextureUsage.RENDER_ATTACHMENT,
327
+ });
328
+ var texture0 = this.texture0
329
+ device.queue.copyExternalImageToTexture(
330
+ {source: imageBitmap},
331
+ {texture: texture0},
332
+ [imageBitmap.width, imageBitmap.height]
333
+ );
334
+ resolve()
335
+ })
336
+
337
+ }
338
+
339
+ createSphereMesh(radius, widthSegments = 3, heightSegments = 3, randomness = 0) {
340
+ const vertices = [];
341
+ const indices = [];
342
+
343
+ widthSegments = Math.max(3, Math.floor(widthSegments));
344
+ heightSegments = Math.max(2, Math.floor(heightSegments));
345
+
346
+ const firstVertex = vec3.create();
347
+ const vertex = vec3.create();
348
+ const normal = vec3.create();
349
+
350
+ let index = 0;
351
+ const grid = [];
352
+
353
+ // generate vertices, normals and uvs
354
+ for(let iy = 0;iy <= heightSegments;iy++) {
355
+ const verticesRow = [];
356
+ const v = iy / heightSegments;
357
+ // special case for the poles
358
+ let uOffset = 0;
359
+ if(iy === 0) {
360
+ uOffset = 0.5 / widthSegments;
361
+ } else if(iy === heightSegments) {
362
+ uOffset = -0.5 / widthSegments;
363
+ }
364
+
365
+ for(let ix = 0;ix <= widthSegments;ix++) {
366
+ const u = ix / widthSegments;
367
+ // Poles should just use the same position all the way around.
368
+ if(ix == widthSegments) {
369
+ vec3.copy(firstVertex, vertex);
370
+ } else if(ix == 0 || (iy != 0 && iy !== heightSegments)) {
371
+ const rr = radius + (Math.random() - 0.5) * 2 * randomness * radius;
372
+ // vertex
373
+ vertex[0] = -rr * Math.cos(u * Math.PI * 2) * Math.sin(v * Math.PI);
374
+ vertex[1] = rr * Math.cos(v * Math.PI);
375
+ vertex[2] = rr * Math.sin(u * Math.PI * 2) * Math.sin(v * Math.PI);
376
+ if(ix == 0) {
377
+ vec3.copy(vertex, firstVertex);
378
+ }
379
+ }
380
+ vertices.push(...vertex);
381
+
382
+ // normal
383
+ vec3.copy(vertex, normal);
384
+ vec3.normalize(normal, normal);
385
+ vertices.push(...normal);
386
+ // uv
387
+ vertices.push(u + uOffset, 1 - v);
388
+ verticesRow.push(index++);
389
+ }
390
+ grid.push(verticesRow);
391
+ }
392
+ // indices
393
+ for(let iy = 0;iy < heightSegments;iy++) {
394
+ for(let ix = 0;ix < widthSegments;ix++) {
395
+ const a = grid[iy][ix + 1];
396
+ const b = grid[iy][ix];
397
+ const c = grid[iy + 1][ix];
398
+ const d = grid[iy + 1][ix + 1];
399
+
400
+ if(iy !== 0) indices.push(a, b, d);
401
+ if(iy !== heightSegments - 1) indices.push(b, c, d);
402
+ }
403
+ }
404
+
405
+
406
+ return {
407
+ vertices: new Float32Array(vertices),
408
+ indices: new Uint16Array(indices),
409
+ };
410
+ }
411
+ // Render bundles function as partial, limited render passes, so we can use the
412
+ // same code both to render the scene normally and to build the render bundle.
413
+ renderScene(passEncoder) {
414
+
415
+ if(typeof this.renderables === 'undefined') return;
416
+
417
+ passEncoder.setPipeline(this.pipeline);
418
+ passEncoder.setBindGroup(0, this.frameBindGroup);
419
+
420
+ // Loop through every renderable object and draw them individually.
421
+ // (Because many of these meshes are repeated, with only the transforms
422
+ // differing, instancing would be highly effective here. This sample
423
+ // intentionally avoids using instancing in order to emulate a more complex
424
+ // scene, which helps demonstrate the potential time savings a render bundle
425
+ // can provide.)
426
+ let count = 0;
427
+ for(const renderable of this.renderables) {
428
+ passEncoder.setBindGroup(1, renderable.bindGroup);
429
+ passEncoder.setVertexBuffer(0, renderable.vertices);
430
+ passEncoder.setIndexBuffer(renderable.indices, 'uint16');
431
+ passEncoder.drawIndexed(renderable.indexCount);
432
+
433
+ if(++count > this.settings.asteroidCount) {
434
+ break;
435
+ }
436
+ }
437
+ }
438
+
439
+ draw = () => {
440
+ if(this.moonTexture == null) {
441
+ console.log('not ready')
442
+ return;
443
+ }
444
+ const transformationMatrix = this.getTransformationMatrix(this.position);
445
+ this.device.queue.writeBuffer(
446
+ this.uniformBuffer,
447
+ 0,
448
+ transformationMatrix.buffer,
449
+ transformationMatrix.byteOffset,
450
+ transformationMatrix.byteLength
451
+ );
452
+ this.renderPassDescriptor.colorAttachments[0].view = this.context
453
+ .getCurrentTexture()
454
+ .createView();
455
+ }
456
+ }