matrix-engine-wgpu 1.0.2 → 1.0.4

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.
Files changed (44) hide show
  1. package/app-worker.js +45 -0
  2. package/empty.js +12 -0
  3. package/examples/load-obj-file.js +48 -0
  4. package/examples/unlit-textures.js +27 -0
  5. package/examples.js +7 -0
  6. package/index.js +18 -5
  7. package/main.js +34 -23
  8. package/package.json +11 -2
  9. package/public/app-worker.js +47 -0
  10. package/public/app.js +2678 -310
  11. package/public/css/style.css +1 -2
  12. package/public/empty.html +25 -0
  13. package/public/empty.js +9107 -0
  14. package/public/examples.html +25 -0
  15. package/public/examples.js +9180 -0
  16. package/public/res/meshes/blender/piramyd.blend +0 -0
  17. package/public/res/meshes/blender/piramyd.blend1 +0 -0
  18. package/public/res/meshes/blender/piramyd.js +42 -0
  19. package/public/res/meshes/blender/piramyd.mtl +10 -0
  20. package/public/res/meshes/blender/piramyd.obj +18696 -0
  21. package/public/res/meshes/blender/piramyd1.js +42 -0
  22. package/public/res/meshes/blender/welcomeTextblend.blend +0 -0
  23. package/public/res/meshes/dragon/stanfordDragonData.js +5 -0
  24. package/public/res/meshes/obj/armor.obj +319 -0
  25. package/public/res/meshes/obj/armor.png +0 -0
  26. package/public/worker.html +25 -0
  27. package/readme.md +45 -37
  28. package/src/engine/ball.js +26 -10
  29. package/src/engine/cube.js +96 -81
  30. package/src/engine/engine.js +466 -4
  31. package/src/engine/final/adaptJSON1.js +53 -0
  32. package/src/engine/final/utils2.js +63 -0
  33. package/src/engine/loader-obj.js +469 -0
  34. package/src/engine/matrix-class.js +5 -4
  35. package/src/engine/matrix-mesh.js +49 -0
  36. package/src/engine/mesh-obj.js +526 -0
  37. package/src/engine/mesh.js +477 -0
  38. package/src/engine/utils.js +2 -0
  39. package/src/shaders/fragment.wgsl.js +48 -0
  40. package/src/shaders/shaders.js +4 -124
  41. package/src/shaders/vertex.wgsl.js +49 -0
  42. package/src/shaders/vertexShadow.wgsl.js +20 -0
  43. package/src/world.js +263 -0
  44. package/src/meWGPU.js +0 -173
@@ -0,0 +1,526 @@
1
+ import {mat4, vec3} from 'wgpu-matrix';
2
+ import {Position, Rotation} from "./matrix-class";
3
+ import {createInputHandler} from "./engine";
4
+ import {vertexShadowWGSL} from '../shaders/vertexShadow.wgsl';
5
+ import {fragmentWGSL} from '../shaders/fragment.wgsl';
6
+ import {vertexWGSL} from '../shaders/vertex.wgsl';
7
+
8
+ export default class MEMeshObj {
9
+
10
+ constructor(canvas, device, context, o) {
11
+
12
+ this.done = false;
13
+ this.device = device;
14
+ this.context = context;
15
+ this.entityArgPass = o.entityArgPass;
16
+
17
+ // Mesh stuff
18
+ this.mesh = o.mesh;
19
+ this.mesh.uvs = this.mesh.textures;
20
+ console.log('mesh obj: ', this.mesh)
21
+
22
+ this.inputHandler = createInputHandler(window, canvas);
23
+ this.cameras = o.cameras;
24
+
25
+ this.cameraParams = {
26
+ type: o.mainCameraParams.type,
27
+ responseCoef: o.mainCameraParams.responseCoef
28
+ }
29
+
30
+ this.lastFrameMS = 0;
31
+ this.texturesPaths = [];
32
+ o.texturesPaths.forEach((t) => {this.texturesPaths.push(t)})
33
+
34
+ this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
35
+
36
+ this.position = new Position(o.position.x, o.position.y, o.position.z);
37
+ this.rotation = new Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
38
+ this.rotation.rotationSpeed.x = o.rotationSpeed.x;
39
+ this.rotation.rotationSpeed.y = o.rotationSpeed.y;
40
+ this.rotation.rotationSpeed.z = o.rotationSpeed.z;
41
+ this.scale = o.scale;
42
+
43
+ this.runProgram = () => {
44
+ return new Promise(async (resolve) => {
45
+ this.shadowDepthTextureSize = 1024;
46
+ const aspect = canvas.width / canvas.height;
47
+ this.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 2000.0);
48
+ this.modelViewProjectionMatrix = mat4.create();
49
+ // console.log('cube added texturesPaths: ', this.texturesPaths)
50
+ this.loadTex0(this.texturesPaths, device).then(() => {
51
+ console.log('loaded tex buffer for mesh:', this.texture0)
52
+ resolve()
53
+ })
54
+ })
55
+ }
56
+
57
+ this.runProgram().then(() => {
58
+ const aspect = canvas.width / canvas.height;
59
+ const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
60
+ this.context.configure({
61
+ device: this.device,
62
+ format: presentationFormat,
63
+ alphaMode: 'premultiplied',
64
+ });
65
+
66
+ // Create the model vertex buffer.
67
+ this.vertexBuffer = this.device.createBuffer({
68
+ size: this.mesh.vertices.length * Float32Array.BYTES_PER_ELEMENT,
69
+ usage: GPUBufferUsage.VERTEX,
70
+ mappedAtCreation: true,
71
+ });
72
+ {
73
+ // const mapping = new Float32Array(this.vertexBuffer.getMappedRange());
74
+ // // for(let i = 0;i < this.mesh.vertices.length;++i) {
75
+ // // mapping.set(this.mesh.vertices[i], 6 * i);
76
+ // // mapping.set(this.mesh.normals[i], 6 * i + 3);
77
+ // // }
78
+ // this.vertexBuffer.unmap();
79
+ new Float32Array(this.vertexBuffer.getMappedRange()).set(this.mesh.vertices);
80
+ this.vertexBuffer.unmap();
81
+ }
82
+
83
+ // NIDZA TEST SECOUND BUFFER
84
+ // Create the model vertex buffer.
85
+ this.vertexNormalsBuffer = this.device.createBuffer({
86
+ size: this.mesh.vertexNormals.length * Float32Array.BYTES_PER_ELEMENT,
87
+ usage: GPUBufferUsage.VERTEX,
88
+ mappedAtCreation: true,
89
+ });
90
+ {
91
+ new Float32Array(this.vertexNormalsBuffer.getMappedRange()).set(this.mesh.vertexNormals);
92
+ this.vertexNormalsBuffer.unmap();
93
+ }
94
+
95
+ this.vertexTexCoordsBuffer = this.device.createBuffer({
96
+ size: this.mesh.textures.length * Float32Array.BYTES_PER_ELEMENT,
97
+ usage: GPUBufferUsage.VERTEX,
98
+ mappedAtCreation: true,
99
+ });
100
+ {
101
+ new Float32Array(this.vertexTexCoordsBuffer.getMappedRange()).set(this.mesh.textures);
102
+ this.vertexTexCoordsBuffer.unmap();
103
+ }
104
+
105
+ // Create the model index buffer.
106
+ this.indexCount = this.mesh.indices.length;
107
+ this.indexBuffer = this.device.createBuffer({
108
+ size: this.indexCount * Uint16Array.BYTES_PER_ELEMENT,
109
+ usage: GPUBufferUsage.INDEX,
110
+ mappedAtCreation: true,
111
+ });
112
+ {
113
+ // const mapping = new Uint16Array(this.indexBuffer.getMappedRange());
114
+ // for(let i = 0;i < this.mesh.indices.length;++i) {
115
+ // mapping.set(this.mesh.indices[i], i);
116
+ // }
117
+ new Uint16Array(this.indexBuffer.getMappedRange()).set(this.mesh.indices);
118
+ this.indexBuffer.unmap();
119
+ }
120
+
121
+ // Create the depth texture for rendering/sampling the shadow map.
122
+ this.shadowDepthTexture = this.device.createTexture({
123
+ size: [this.shadowDepthTextureSize, this.shadowDepthTextureSize, 1],
124
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
125
+ format: 'depth32float',
126
+ });
127
+ this.shadowDepthTextureView = this.shadowDepthTexture.createView();
128
+
129
+ // Create some common descriptors used for both the shadow pipeline
130
+ // and the color rendering pipeline.
131
+ this.vertexBuffers = [
132
+ {
133
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
134
+ attributes: [
135
+ {
136
+ // position
137
+ shaderLocation: 0,
138
+ offset: 0,
139
+ format: "float32x3",
140
+ }
141
+ ],
142
+ },
143
+ {
144
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 3,
145
+ attributes: [
146
+ {
147
+ // normal
148
+ shaderLocation: 1,
149
+ offset: 0,
150
+ format: "float32x3",
151
+ },
152
+ ],
153
+ },
154
+ {
155
+ arrayStride: Float32Array.BYTES_PER_ELEMENT * 2,
156
+ attributes: [
157
+ {
158
+ // uvs
159
+ shaderLocation: 2,
160
+ offset: 0,
161
+ format: "float32x2",
162
+ },
163
+ ],
164
+ },
165
+ ];
166
+
167
+ const primitive = {
168
+ topology: 'triangle-list',
169
+ cullMode: 'back',
170
+ };
171
+
172
+ this.uniformBufferBindGroupLayout = this.device.createBindGroupLayout({
173
+ entries: [
174
+ {
175
+ binding: 0,
176
+ visibility: GPUShaderStage.VERTEX,
177
+ buffer: {
178
+ type: 'uniform',
179
+ },
180
+ },
181
+ ],
182
+ });
183
+
184
+ this.shadowPipeline = this.device.createRenderPipeline({
185
+ layout: this.device.createPipelineLayout({
186
+ bindGroupLayouts: [
187
+ this.uniformBufferBindGroupLayout,
188
+ this.uniformBufferBindGroupLayout,
189
+ ],
190
+ }),
191
+ vertex: {
192
+ module: this.device.createShaderModule({
193
+ code: vertexShadowWGSL,
194
+ }),
195
+ buffers: this.vertexBuffers,
196
+ },
197
+ depthStencil: {
198
+ depthWriteEnabled: true,
199
+ depthCompare: 'less',
200
+ format: 'depth32float',
201
+ },
202
+ primitive,
203
+ });
204
+
205
+ // Create a bind group layout which holds the scene uniforms and
206
+ // the texture+sampler for depth. We create it manually because the WebPU
207
+ // implementation doesn't infer this from the shader (yet).
208
+ this.bglForRender = this.device.createBindGroupLayout({
209
+ entries: [
210
+ {
211
+ binding: 0,
212
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
213
+ buffer: {
214
+ type: 'uniform',
215
+ },
216
+ },
217
+ {
218
+ binding: 1,
219
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
220
+ texture: {
221
+ sampleType: 'depth',
222
+ },
223
+ },
224
+ {
225
+ binding: 2,
226
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
227
+ sampler: {
228
+ type: 'comparison',
229
+ },
230
+ },
231
+ {
232
+ binding: 3,
233
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
234
+ texture: {
235
+ sampleType: 'float',
236
+ }
237
+ },
238
+ {
239
+ binding: 4,
240
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
241
+ sampler: {
242
+ type: 'filtering',
243
+ }
244
+ }
245
+ ]
246
+ });
247
+
248
+ this.pipeline = this.device.createRenderPipeline({
249
+ layout: this.device.createPipelineLayout({
250
+ bindGroupLayouts: [this.bglForRender, this.uniformBufferBindGroupLayout],
251
+ }),
252
+ vertex: {
253
+ module: this.device.createShaderModule({
254
+ code: vertexWGSL,
255
+ }),
256
+ buffers: this.vertexBuffers,
257
+ },
258
+ fragment: {
259
+ module: this.device.createShaderModule({
260
+ code: fragmentWGSL,
261
+ }),
262
+ targets: [
263
+ {
264
+ format: presentationFormat,
265
+ },
266
+ ],
267
+ constants: {
268
+ shadowDepthTextureSize: this.shadowDepthTextureSize,
269
+ },
270
+ },
271
+ depthStencil: {
272
+ depthWriteEnabled: true,
273
+ depthCompare: 'less',
274
+ format: 'depth24plus-stencil8',
275
+ },
276
+ primitive,
277
+ });
278
+
279
+ const depthTexture = this.device.createTexture({
280
+ size: [canvas.width, canvas.height],
281
+ format: 'depth24plus-stencil8',
282
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
283
+ });
284
+
285
+ this.renderPassDescriptor = {
286
+ colorAttachments: [
287
+ {
288
+ // view is acquired and set in render loop.
289
+ view: undefined,
290
+ clearValue: {r: 0.5, g: 0.5, b: 0.5, a: 1.0},
291
+ loadOp: 'load',
292
+ storeOp: 'store',
293
+ },
294
+ ],
295
+ depthStencilAttachment: {
296
+ view: depthTexture.createView(),
297
+ depthClearValue: 1.0,
298
+ depthLoadOp: 'clear',
299
+ depthStoreOp: 'store',
300
+ stencilClearValue: 0,
301
+ stencilLoadOp: 'clear',
302
+ stencilStoreOp: 'store',
303
+ },
304
+ };
305
+
306
+ this.modelUniformBuffer = this.device.createBuffer({
307
+ size: 4 * 16, // 4x4 matrix
308
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
309
+ });
310
+
311
+ this.sceneUniformBuffer = this.device.createBuffer({
312
+ // Two 4x4 viewProj matrices,
313
+ // one for the camera and one for the light.
314
+ // Then a vec3 for the light position.
315
+ // Rounded to the nearest multiple of 16.
316
+ size: 2 * 4 * 16 + 4 * 4,
317
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
318
+ });
319
+
320
+ this.sceneBindGroupForShadow = this.device.createBindGroup({
321
+ layout: this.uniformBufferBindGroupLayout,
322
+ entries: [
323
+ {
324
+ binding: 0,
325
+ resource: {
326
+ buffer: this.sceneUniformBuffer,
327
+ },
328
+ },
329
+ ],
330
+ });
331
+
332
+ this.sceneBindGroupForRender = this.device.createBindGroup({
333
+ layout: this.bglForRender,
334
+ entries: [
335
+ {
336
+ binding: 0,
337
+ resource: {
338
+ buffer: this.sceneUniformBuffer,
339
+ },
340
+ },
341
+ {
342
+ binding: 1,
343
+ resource: this.shadowDepthTextureView,
344
+ },
345
+ {
346
+ binding: 2,
347
+ resource: this.device.createSampler({
348
+ compare: 'less',
349
+ }),
350
+ },
351
+ {
352
+ binding: 3,
353
+ resource: this.texture0.createView(),
354
+ },
355
+ {
356
+ binding: 4,
357
+ resource: this.sampler,
358
+ },
359
+ ],
360
+ });
361
+
362
+ this.modelBindGroup = this.device.createBindGroup({
363
+ layout: this.uniformBufferBindGroupLayout,
364
+ entries: [
365
+ {
366
+ binding: 0,
367
+ resource: {
368
+ buffer: this.modelUniformBuffer,
369
+ },
370
+ },
371
+ ],
372
+ });
373
+
374
+ // Rotates the camera around the origin based on time.
375
+ this.getTransformationMatrix = (pos) => {
376
+ const now = Date.now();
377
+ const deltaTime = (now - this.lastFrameMS) / this.cameraParams.responseCoef;
378
+ this.lastFrameMS = now;
379
+
380
+ // const this.viewMatrix = mat4.identity()
381
+ const camera = this.cameras[this.cameraParams.type];
382
+ this.viewMatrix = camera.update(deltaTime, this.inputHandler());
383
+
384
+ mat4.translate(this.viewMatrix, vec3.fromValues(pos.x, pos.y, pos.z), this.viewMatrix);
385
+ mat4.rotateX(this.viewMatrix, Math.PI * this.rotation.getRotX(), this.viewMatrix);
386
+ mat4.rotateY(this.viewMatrix, Math.PI * this.rotation.getRotY(), this.viewMatrix);
387
+ mat4.rotateZ(this.viewMatrix, Math.PI * this.rotation.getRotZ(), this.viewMatrix);
388
+ mat4.multiply(this.projectionMatrix, this.viewMatrix, this.modelViewProjectionMatrix);
389
+
390
+ return this.modelViewProjectionMatrix;
391
+ }
392
+
393
+ this.upVector = vec3.fromValues(0, 1, 0);
394
+ this.origin = vec3.fromValues(0, 0, 0);
395
+
396
+ const lightPosition = vec3.fromValues(50, 100, -100);
397
+ const lightViewMatrix = mat4.lookAt(lightPosition, this.origin, this.upVector);
398
+ const lightProjectionMatrix = mat4.create();
399
+ {
400
+ const left = -80;
401
+ const right = 80;
402
+ const bottom = -80;
403
+ const top = 80;
404
+ const near = -200;
405
+ const far = 300;
406
+ mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
407
+ }
408
+
409
+ const lightViewProjMatrix = mat4.multiply(
410
+ lightProjectionMatrix,
411
+ lightViewMatrix
412
+ );
413
+
414
+ // looks like affect on transformations for now const 0
415
+ const modelMatrix = mat4.translation([0, 0, 0]);
416
+ // The camera/light aren't moving, so write them into buffers now.
417
+ {
418
+ const lightMatrixData = lightViewProjMatrix; // as Float32Array;
419
+ this.device.queue.writeBuffer(
420
+ this.sceneUniformBuffer,
421
+ 0,
422
+ lightMatrixData.buffer,
423
+ lightMatrixData.byteOffset,
424
+ lightMatrixData.byteLength
425
+ );
426
+
427
+ const lightData = lightPosition;
428
+ this.device.queue.writeBuffer(
429
+ this.sceneUniformBuffer,
430
+ 128,
431
+ lightData.buffer,
432
+ lightData.byteOffset,
433
+ lightData.byteLength
434
+ );
435
+
436
+ const modelData = modelMatrix;
437
+ this.device.queue.writeBuffer(
438
+ this.modelUniformBuffer,
439
+ 0,
440
+ modelData.buffer,
441
+ modelData.byteOffset,
442
+ modelData.byteLength
443
+ );
444
+ }
445
+
446
+ this.shadowPassDescriptor = {
447
+ colorAttachments: [],
448
+ depthStencilAttachment: {
449
+ view: this.shadowDepthTextureView,
450
+ depthClearValue: 1.0,
451
+ depthLoadOp: 'clear',
452
+ depthStoreOp: 'store',
453
+ },
454
+ };
455
+
456
+ this.done = true;
457
+ })
458
+ }
459
+
460
+ async loadTex0(texturesPaths, device) {
461
+
462
+ this.sampler = device.createSampler({
463
+ magFilter: 'linear',
464
+ minFilter: 'linear',
465
+ });
466
+
467
+ return new Promise(async (resolve) => {
468
+ const response = await fetch(texturesPaths[0]);
469
+ const imageBitmap = await createImageBitmap(await response.blob());
470
+ this.texture0 = device.createTexture({
471
+ size: [imageBitmap.width, imageBitmap.height, 1],
472
+ format: 'rgba8unorm',
473
+ usage:
474
+ GPUTextureUsage.TEXTURE_BINDING |
475
+ GPUTextureUsage.COPY_DST |
476
+ GPUTextureUsage.RENDER_ATTACHMENT,
477
+ });
478
+
479
+ device.queue.copyExternalImageToTexture(
480
+ {source: imageBitmap},
481
+ {texture: this.texture0},
482
+ [imageBitmap.width, imageBitmap.height]
483
+ );
484
+ resolve()
485
+ })
486
+ }
487
+
488
+ draw = (commandEncoder) => {
489
+ if(this.done == false) return;
490
+ const transformationMatrix = this.getTransformationMatrix(this.position);
491
+ this.device.queue.writeBuffer(
492
+ this.sceneUniformBuffer,
493
+ 64,
494
+ transformationMatrix.buffer,
495
+ transformationMatrix.byteOffset,
496
+ transformationMatrix.byteLength
497
+ );
498
+ this.renderPassDescriptor.colorAttachments[0].view = this.context
499
+ .getCurrentTexture()
500
+ .createView();
501
+ {
502
+ const shadowPass = commandEncoder.beginRenderPass(this.shadowPassDescriptor);
503
+ shadowPass.setPipeline(this.shadowPipeline);
504
+ shadowPass.setBindGroup(0, this.sceneBindGroupForShadow);
505
+ shadowPass.setBindGroup(1, this.modelBindGroup);
506
+ shadowPass.setVertexBuffer(0, this.vertexBuffer);
507
+ shadowPass.setVertexBuffer(1, this.vertexNormalsBuffer);
508
+ shadowPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
509
+ shadowPass.setIndexBuffer(this.indexBuffer, 'uint16');
510
+ shadowPass.drawIndexed(this.indexCount);
511
+ shadowPass.end();
512
+ }
513
+ {
514
+ const renderPass = commandEncoder.beginRenderPass(this.renderPassDescriptor);
515
+ renderPass.setPipeline(this.pipeline);
516
+ renderPass.setBindGroup(0, this.sceneBindGroupForRender);
517
+ renderPass.setBindGroup(1, this.modelBindGroup);
518
+ renderPass.setVertexBuffer(0, this.vertexBuffer);
519
+ renderPass.setVertexBuffer(1, this.vertexNormalsBuffer);
520
+ renderPass.setVertexBuffer(2, this.vertexTexCoordsBuffer);
521
+ renderPass.setIndexBuffer(this.indexBuffer, 'uint16');
522
+ renderPass.drawIndexed(this.indexCount);
523
+ renderPass.end();
524
+ }
525
+ }
526
+ }