matrix-engine-wgpu 1.3.13 → 1.3.16

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,475 +0,0 @@
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
- import {downloadMeshes} from './loader-obj';
8
-
9
- export default class MEMesh {
10
-
11
- constructor(canvas, device, context, o) {
12
-
13
- this.done = false;
14
- this.device = device;
15
- this.context = context;
16
- this.entityArgPass = o.entityArgPass;
17
-
18
- this.mesh = o.mesh;
19
- this.inputHandler = createInputHandler(window, canvas);
20
- this.cameras = o.cameras;
21
- this.mainCameraParams = {
22
- type: o.mainCameraParams.type,
23
- responseCoef: o.mainCameraParams.responseCoef
24
- }
25
- this.lastFrameMS = 0;
26
- this.texturesPaths = [];
27
- o.texturesPaths.forEach((t) => {this.texturesPaths.push(t)})
28
- this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
29
- this.position = new Position(o.position.x, o.position.y, o.position.z);
30
- // console.log('cube added on pos : ', this.position)
31
- this.rotation = new Rotation(o.rotation.x, o.rotation.y, o.rotation.z);
32
- this.rotation.rotationSpeed.x = o.rotationSpeed.x;
33
- this.rotation.rotationSpeed.y = o.rotationSpeed.y;
34
- this.rotation.rotationSpeed.z = o.rotationSpeed.z;
35
- this.scale = o.scale;
36
-
37
- // new
38
- this.runProgram = () => {
39
- return new Promise(async (resolve) => {
40
- this.shadowDepthTextureSize = 1024;
41
- const aspect = canvas.width / canvas.height;
42
- this.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 2000.0);
43
- this.modelViewProjectionMatrix = mat4.create();
44
-
45
- this.loadTex0(this.texturesPaths, device).then(() => {
46
- resolve()
47
- console.log('load tex for mesh', this.texture0)
48
- })
49
- })
50
- }
51
-
52
- this.runProgram().then(() => {
53
- const aspect = canvas.width / canvas.height;
54
- const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
55
- this.context.configure({
56
- device: this.device,
57
- format: presentationFormat,
58
- alphaMode: 'premultiplied',
59
- });
60
-
61
- // Create the model vertex buffer.
62
- this.vertexBuffer = this.device.createBuffer({
63
- size: this.mesh.positions.length * 3 * 2 * Float32Array.BYTES_PER_ELEMENT,
64
- usage: GPUBufferUsage.VERTEX,
65
- mappedAtCreation: true,
66
- });
67
- {
68
- const mapping = new Float32Array(this.vertexBuffer.getMappedRange());
69
- for(let i = 0;i < this.mesh.positions.length;++i) {
70
- mapping.set(this.mesh.positions[i], 6 * i);
71
- mapping.set(this.mesh.normals[i], 6 * i + 3);
72
- }
73
- this.vertexBuffer.unmap();
74
- }
75
-
76
- // Create the model index buffer.
77
- this.indexCount = this.mesh.triangles.length * 3;
78
- this.indexBuffer = this.device.createBuffer({
79
- size: this.indexCount * Uint16Array.BYTES_PER_ELEMENT,
80
- usage: GPUBufferUsage.INDEX,
81
- mappedAtCreation: true,
82
- });
83
- {
84
- const mapping = new Uint16Array(this.indexBuffer.getMappedRange());
85
- for(let i = 0;i < this.mesh.triangles.length;++i) {
86
- mapping.set(this.mesh.triangles[i], 3 * i);
87
- }
88
- this.indexBuffer.unmap();
89
- }
90
-
91
- // Create the depth texture for rendering/sampling the shadow map.
92
- this.shadowDepthTexture = this.device.createTexture({
93
- size: [this.shadowDepthTextureSize, this.shadowDepthTextureSize, 1],
94
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
95
- format: 'depth32float',
96
- });
97
- this.shadowDepthTextureView = this.shadowDepthTexture.createView();
98
-
99
- // Create some common descriptors used for both the shadow pipeline
100
- // and the color rendering pipeline.
101
- this.vertexBuffers = [
102
- {
103
- arrayStride: Float32Array.BYTES_PER_ELEMENT * 6,
104
- attributes: [
105
- {
106
- // position
107
- shaderLocation: 0,
108
- offset: 0,
109
- format: 'float32x3',
110
- },
111
- {
112
- // normal
113
- shaderLocation: 1,
114
- offset: Float32Array.BYTES_PER_ELEMENT * 3,
115
- format: 'float32x3',
116
- },
117
- ],
118
- },
119
- ];
120
-
121
- const primitive = {
122
- topology: 'triangle-list',
123
- cullMode: 'back',
124
- };
125
-
126
- this.uniformBufferBindGroupLayout = this.device.createBindGroupLayout({
127
- entries: [
128
- {
129
- binding: 0,
130
- visibility: GPUShaderStage.VERTEX,
131
- buffer: {
132
- type: 'uniform',
133
- },
134
- },
135
- ],
136
- });
137
-
138
- this.shadowPipeline = this.device.createRenderPipeline({
139
- layout: this.device.createPipelineLayout({
140
- bindGroupLayouts: [
141
- this.uniformBufferBindGroupLayout,
142
- this.uniformBufferBindGroupLayout,
143
- ],
144
- }),
145
- vertex: {
146
- module: this.device.createShaderModule({
147
- code: vertexShadowWGSL,
148
- }),
149
- buffers: this.vertexBuffers,
150
- },
151
- depthStencil: {
152
- depthWriteEnabled: true,
153
- depthCompare: 'less',
154
- format: 'depth32float',
155
- },
156
- primitive,
157
- });
158
-
159
- // Create a bind group layout which holds the scene uniforms and
160
- // the texture+sampler for depth. We create it manually because the WebPU
161
- // implementation doesn't infer this from the shader (yet).
162
- this.bglForRender = this.device.createBindGroupLayout({
163
- entries: [
164
- {
165
- binding: 0,
166
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
167
- buffer: {
168
- type: 'uniform',
169
- },
170
- },
171
- {
172
- binding: 1,
173
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
174
- texture: {
175
- sampleType: 'depth',
176
- },
177
- },
178
- {
179
- binding: 2,
180
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
181
- sampler: {
182
- type: 'comparison',
183
- },
184
- },
185
- {
186
- binding: 3,
187
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
188
- texture: {
189
- sampleType: 'float',
190
- },
191
- },
192
- {
193
- binding: 4,
194
- visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
195
- sampler: {
196
- type: 'filtering',
197
- },
198
- }
199
- ],
200
- });
201
-
202
- this.pipeline = this.device.createRenderPipeline({
203
- layout: this.device.createPipelineLayout({
204
- bindGroupLayouts: [this.bglForRender, this.uniformBufferBindGroupLayout],
205
- }),
206
- vertex: {
207
- module: this.device.createShaderModule({
208
- code: vertexWGSL,
209
- }),
210
- buffers: this.vertexBuffers,
211
- },
212
- fragment: {
213
- module: this.device.createShaderModule({
214
- code: fragmentWGSL,
215
- }),
216
- targets: [
217
- {
218
- format: presentationFormat,
219
- },
220
- ],
221
- constants: {
222
- shadowDepthTextureSize: this.shadowDepthTextureSize,
223
- },
224
- },
225
- depthStencil: {
226
- depthWriteEnabled: true,
227
- depthCompare: 'less',
228
- format: 'depth24plus-stencil8',
229
- },
230
- primitive,
231
- });
232
-
233
- const depthTexture = this.device.createTexture({
234
- size: [canvas.width, canvas.height],
235
- format: 'depth24plus-stencil8',
236
- usage: GPUTextureUsage.RENDER_ATTACHMENT,
237
- });
238
-
239
- this.renderPassDescriptor = {
240
- colorAttachments: [
241
- {
242
- // view is acquired and set in render loop.
243
- view: undefined,
244
- clearValue: {r: 0.5, g: 0.5, b: 0.5, a: 1.0},
245
- loadOp: 'load',
246
- storeOp: 'store',
247
- },
248
- ],
249
- depthStencilAttachment: {
250
- view: depthTexture.createView(),
251
-
252
- depthClearValue: 1.0,
253
- depthLoadOp: 'clear',
254
- depthStoreOp: 'store',
255
- stencilClearValue: 0,
256
- stencilLoadOp: 'clear',
257
- stencilStoreOp: 'store',
258
- },
259
- };
260
-
261
- this.modelUniformBuffer = this.device.createBuffer({
262
- size: 4 * 16, // 4x4 matrix
263
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
264
- });
265
-
266
- this.sceneUniformBuffer = this.device.createBuffer({
267
- // Two 4x4 viewProj matrices,
268
- // one for the camera and one for the light.
269
- // Then a vec3 for the light position.
270
- // Rounded to the nearest multiple of 16.
271
- size: 2 * 4 * 16 + 4 * 4,
272
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
273
- });
274
-
275
- this.sceneBindGroupForShadow = this.device.createBindGroup({
276
- layout: this.uniformBufferBindGroupLayout,
277
- entries: [
278
- {
279
- binding: 0,
280
- resource: {
281
- buffer: this.sceneUniformBuffer,
282
- },
283
- },
284
- ],
285
- });
286
-
287
- this.sceneBindGroupForRender = this.device.createBindGroup({
288
- layout: this.bglForRender,
289
- entries: [
290
- {
291
- binding: 0,
292
- resource: {
293
- buffer: this.sceneUniformBuffer,
294
- },
295
- },
296
- {
297
- binding: 1,
298
- resource: this.shadowDepthTextureView,
299
- },
300
- {
301
- binding: 2,
302
- resource: this.device.createSampler({
303
- compare: 'less',
304
- }),
305
- },
306
- {
307
- binding: 3,
308
- resource: this.texture0.createView(),
309
- },
310
- {
311
- binding: 4,
312
- resource: this.sampler,
313
- },
314
- ],
315
- });
316
-
317
- this.modelBindGroup = this.device.createBindGroup({
318
- layout: this.uniformBufferBindGroupLayout,
319
- entries: [
320
- {
321
- binding: 0,
322
- resource: {
323
- buffer: this.modelUniformBuffer,
324
- },
325
- },
326
- ],
327
- });
328
-
329
- // Rotates the camera around the origin based on time.
330
- this.getTransformationMatrix = (pos) => {
331
- const now = Date.now();
332
- const deltaTime = (now - this.lastFrameMS) / this.mainCameraParams.responseCoef;
333
- this.lastFrameMS = now;
334
-
335
- const camera = this.cameras[this.mainCameraParams.type];
336
- this.viewMatrix = camera.update(deltaTime, this.inputHandler());
337
-
338
- mat4.translate(this.viewMatrix, vec3.fromValues(pos.x, pos.y, pos.z), this.viewMatrix);
339
- mat4.rotateX(this.viewMatrix, Math.PI * this.rotation.getRotX(), this.viewMatrix);
340
- mat4.rotateY(this.viewMatrix, Math.PI * this.rotation.getRotY(), this.viewMatrix);
341
- mat4.rotateZ(this.viewMatrix, Math.PI * this.rotation.getRotZ(), this.viewMatrix);
342
- mat4.multiply(this.projectionMatrix, this.viewMatrix, this.modelViewProjectionMatrix);
343
-
344
- return this.modelViewProjectionMatrix;
345
- }
346
-
347
- this.upVector = vec3.fromValues(0, 1, 0);
348
- this.origin = vec3.fromValues(0, 0, 0);
349
-
350
- const lightPosition = vec3.fromValues(50, 100, -100);
351
- const lightViewMatrix = mat4.lookAt(lightPosition, this.origin, this.upVector);
352
- const lightProjectionMatrix = mat4.create();
353
- {
354
- const left = -80;
355
- const right = 80;
356
- const bottom = -80;
357
- const top = 80;
358
- const near = -200;
359
- const far = 300;
360
- mat4.ortho(left, right, bottom, top, near, far, lightProjectionMatrix);
361
- }
362
-
363
- const lightViewProjMatrix = mat4.multiply(
364
- lightProjectionMatrix,
365
- lightViewMatrix
366
- );
367
-
368
- // looks like affect on transformations for now const 0
369
- const modelMatrix = mat4.translation([0, 0, 0]);
370
- // The camera/light aren't moving, so write them into buffers now.
371
- {
372
- const lightMatrixData = lightViewProjMatrix; // as Float32Array;
373
- this.device.queue.writeBuffer(
374
- this.sceneUniformBuffer,
375
- 0,
376
- lightMatrixData.buffer,
377
- lightMatrixData.byteOffset,
378
- lightMatrixData.byteLength
379
- );
380
-
381
- const lightData = lightPosition;
382
- this.device.queue.writeBuffer(
383
- this.sceneUniformBuffer,
384
- 128,
385
- lightData.buffer,
386
- lightData.byteOffset,
387
- lightData.byteLength
388
- );
389
-
390
- const modelData = modelMatrix;
391
- this.device.queue.writeBuffer(
392
- this.modelUniformBuffer,
393
- 0,
394
- modelData.buffer,
395
- modelData.byteOffset,
396
- modelData.byteLength
397
- );
398
- }
399
-
400
- this.shadowPassDescriptor = {
401
- colorAttachments: [],
402
- depthStencilAttachment: {
403
- view: this.shadowDepthTextureView,
404
- depthClearValue: 1.0,
405
- depthLoadOp: 'clear',
406
- depthStoreOp: 'store',
407
- },
408
- };
409
-
410
- this.done = true;
411
- })
412
- }
413
-
414
- async loadTex0(texturesPaths, device) {
415
- this.sampler = device.createSampler({
416
- magFilter: 'linear',
417
- minFilter: 'linear',
418
- });
419
-
420
- return new Promise(async (resolve) => {
421
- const response = await fetch(texturesPaths[0]);
422
- const imageBitmap = await createImageBitmap(await response.blob());
423
- this.texture0 = device.createTexture({
424
- size: [imageBitmap.width, imageBitmap.height, 1],
425
- format: 'rgba8unorm',
426
- usage:
427
- GPUTextureUsage.TEXTURE_BINDING |
428
- GPUTextureUsage.COPY_DST |
429
- GPUTextureUsage.RENDER_ATTACHMENT,
430
- });
431
-
432
- device.queue.copyExternalImageToTexture(
433
- {source: imageBitmap},
434
- {texture: this.texture0},
435
- [imageBitmap.width, imageBitmap.height]
436
- );
437
- resolve()
438
- })
439
- }
440
-
441
- draw = (commandEncoder) => {
442
- if(this.done == false) return;
443
- const transformationMatrix = this.getTransformationMatrix(this.position);
444
- this.device.queue.writeBuffer(
445
- this.sceneUniformBuffer,
446
- 64,
447
- transformationMatrix.buffer,
448
- transformationMatrix.byteOffset,
449
- transformationMatrix.byteLength
450
- );
451
- this.renderPassDescriptor.colorAttachments[0].view = this.context
452
- .getCurrentTexture()
453
- .createView();
454
- {
455
- const shadowPass = commandEncoder.beginRenderPass(this.shadowPassDescriptor);
456
- shadowPass.setPipeline(this.shadowPipeline);
457
- shadowPass.setBindGroup(0, this.sceneBindGroupForShadow);
458
- shadowPass.setBindGroup(1, this.modelBindGroup);
459
- shadowPass.setVertexBuffer(0, this.vertexBuffer);
460
- shadowPass.setIndexBuffer(this.indexBuffer, 'uint16');
461
- shadowPass.drawIndexed(this.indexCount);
462
- shadowPass.end();
463
- }
464
- {
465
- const renderPass = commandEncoder.beginRenderPass(this.renderPassDescriptor);
466
- renderPass.setPipeline(this.pipeline);
467
- renderPass.setBindGroup(0, this.sceneBindGroupForRender);
468
- renderPass.setBindGroup(1, this.modelBindGroup);
469
- renderPass.setVertexBuffer(0, this.vertexBuffer);
470
- renderPass.setIndexBuffer(this.indexBuffer, 'uint16');
471
- renderPass.drawIndexed(this.indexCount);
472
- renderPass.end();
473
- }
474
- }
475
- }
@@ -1,219 +0,0 @@
1
- /**
2
- * @author Nikola Lukic
3
- * @email zlatnaspirala@gmail.com
4
- * @site https://maximumroulette.com
5
- * @Licence GPL v3
6
- * @credits chatgpt used for this script adaptation.
7
- * @Note matrix-engine-wgpu adaptation test
8
- * default for now:
9
- * app.cameras['WASD']
10
- * Only tested for WASD type of camera.
11
- * app is global - will be fixed in future
12
- */
13
- import {mat4, vec3, vec4} from "wgpu-matrix";
14
- let rayHitEvent;
15
-
16
- export let touchCoordinate = {
17
- enabled: false,
18
- x: 0,
19
- y: 0,
20
- stopOnFirstDetectedHit: false
21
- };
22
-
23
- function multiplyMatrixVector(matrix, vector) {
24
- return vec4.transformMat4(vector, matrix);
25
- }
26
-
27
- export function getRayFromMouse(event, canvas, camera) {
28
- const rect = canvas.getBoundingClientRect();
29
- let x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
30
- let y = ((event.clientY - rect.top) / rect.height) * 2 - 1;
31
- // simple invert
32
- x = -x;
33
- y = -y;
34
- const fov = Math.PI / 4;
35
- const aspect = canvas.width / canvas.height;
36
- const near = 0.1;
37
- const far = 1000;
38
- camera.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 1000.0);
39
- const invProjection = mat4.inverse(camera.projectionMatrix);
40
- const invView = mat4.inverse(camera.view);
41
- const ndc = [x, y, 1, 1];
42
- let worldPos = multiplyMatrixVector(invProjection, ndc);
43
- worldPos = multiplyMatrixVector(invView, worldPos);
44
- let world;
45
- if(worldPos[3] !== 0) {
46
- world = [
47
- worldPos[0] / worldPos[3],
48
- worldPos[2] / worldPos[3],
49
- worldPos[1] / worldPos[3]
50
- ];
51
- } else {
52
- console.log("[raycaster]special case 0.");
53
- world = [
54
- worldPos[0],
55
- worldPos[1],
56
- worldPos[2]
57
- ];
58
- }
59
- const rayOrigin = [camera.position[0], camera.position[1], camera.position[2]];
60
- const rayDirection = vec3.normalize(vec3.subtract(world, rayOrigin));
61
- rayDirection[2] = -rayDirection[2];
62
- return {rayOrigin, rayDirection};
63
- }
64
-
65
- export function getRayFromMouse2(event, canvas, camera) {
66
- const rect = canvas.getBoundingClientRect();
67
- let x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
68
- let y = ((event.clientY - rect.top) / rect.height) * 2 - 1;
69
- // simple invert
70
- y = -y;
71
- const fov = Math.PI / 4;
72
- const aspect = canvas.width / canvas.height;
73
- const near = 0.1;
74
- const far = 1000;
75
- camera.projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 1, 1000.0);
76
- const invProjection = mat4.inverse(camera.projectionMatrix);
77
- console.log("camera.view:" + camera.view)
78
- const invView = mat4.inverse(camera.view);
79
- const ndc = [x, y, 1, 1];
80
- let worldPos = multiplyMatrixVector(invProjection, ndc);
81
- worldPos = multiplyMatrixVector(invView, worldPos);
82
- let world;
83
- if(worldPos[3] !== 0) {
84
- world = [
85
- worldPos[0] / worldPos[3],
86
- worldPos[1] / worldPos[3],
87
- worldPos[2] / worldPos[3]
88
- ];
89
- } else {
90
- console.log("[raycaster]special case 0.");
91
- world = [
92
- worldPos[0],
93
- worldPos[1],
94
- worldPos[2]
95
- ];
96
- }
97
- const rayOrigin = [camera.position[0], camera.position[1], camera.position[2]];
98
- const rayDirection = vec3.normalize(vec3.subtract(world, rayOrigin));
99
- return {rayOrigin, rayDirection};
100
- }
101
-
102
- export function rayIntersectsSphere(rayOrigin, rayDirection, sphereCenter, sphereRadius) {
103
- const pos = [sphereCenter.x, sphereCenter.y, sphereCenter.z];
104
- const oc = vec3.subtract(rayOrigin, pos);
105
- const a = vec3.dot(rayDirection, rayDirection);
106
- const b = 2.0 * vec3.dot(oc, rayDirection);
107
- const c = vec3.dot(oc, oc) - sphereRadius * sphereRadius;
108
- const discriminant = b * b - 4 * a * c;
109
- return discriminant > 0;
110
- }
111
-
112
- export function addRaycastListener(canvasId = "canvas1") {
113
- let canvasDom = document.getElementById(canvasId);
114
- canvasDom.addEventListener('click', (event) => {
115
- let camera = app.cameras.WASD;
116
- const {rayOrigin, rayDirection} = getRayFromMouse(event, canvasDom, camera);
117
- for(const object of app.mainRenderBundle) {
118
- if(object.raycast.enabled == false) return;
119
- if(rayIntersectsSphere(rayOrigin, rayDirection, object.position, object.raycast.radius)) {
120
- console.log('Object clicked:', object.name);
121
- // Just like in matrix-engine webGL version "ray.hit.event"
122
- dispatchEvent(new CustomEvent('ray.hit.event', {
123
- detail: {
124
- hitObject: object,
125
- rayOrigin: rayOrigin,
126
- rayDirection: rayDirection
127
- }
128
- }))
129
- }
130
- }
131
- });
132
- }
133
-
134
- // Compute AABB from flat vertices array [x,y,z, x,y,z, ...]
135
- export function computeAABB(vertices) {
136
- const min = [Infinity, Infinity, Infinity];
137
- const max = [-Infinity, -Infinity, -Infinity];
138
-
139
- for(let i = 0;i < vertices.length;i += 3) {
140
- min[0] = Math.min(min[0], vertices[i]);
141
- min[1] = Math.min(min[1], vertices[i + 1]);
142
- min[2] = Math.min(min[2], vertices[i + 2]);
143
-
144
- max[0] = Math.max(max[0], vertices[i]);
145
- max[1] = Math.max(max[1], vertices[i + 1]);
146
- max[2] = Math.max(max[2], vertices[i + 2]);
147
- }
148
-
149
- return [min, max];
150
- }
151
-
152
- // Ray-AABB intersection using slabs method
153
- export function rayIntersectsAABB(rayOrigin, rayDirection, boxMin, boxMax) {
154
- let tmin = (boxMin[0] - rayOrigin[0]) / rayDirection[0];
155
- let tmax = (boxMax[0] - rayOrigin[0]) / rayDirection[0];
156
- if(tmin > tmax) [tmin, tmax] = [tmax, tmin];
157
-
158
- let tymin = (boxMin[1] - rayOrigin[1]) / rayDirection[1];
159
- let tymax = (boxMax[1] - rayOrigin[1]) / rayDirection[1];
160
- if(tymin > tymax) [tymin, tymax] = [tymax, tymin];
161
-
162
- if((tmin > tymax) || (tymin > tmax)) return false;
163
- if(tymin > tmin) tmin = tymin;
164
- if(tymax < tmax) tmax = tymax;
165
-
166
- let tzmin = (boxMin[2] - rayOrigin[2]) / rayDirection[2];
167
- let tzmax = (boxMax[2] - rayOrigin[2]) / rayDirection[2];
168
- if(tzmin > tzmax) [tzmin, tzmax] = [tzmax, tzmin];
169
-
170
- if((tmin > tzmax) || (tzmin > tmax)) return false;
171
-
172
- return true;
173
- }
174
-
175
- export function computeWorldVertsAndAABB(object) {
176
- const modelMatrix = object.getModelMatrix(object.position);
177
- const worldVerts = [];
178
- for(let i = 0;i < object.mesh.vertices.length;i += 3) {
179
- const local = vec3.fromValues(
180
- object.mesh.vertices[i],
181
- object.mesh.vertices[i + 1],
182
- object.mesh.vertices[i + 2]
183
- );
184
- const world = vec3.transformMat4(local, modelMatrix); // OK
185
- worldVerts.push(world[0], world[1], world[2]);
186
- }
187
- const [boxMin, boxMax] = computeAABB(worldVerts);
188
- return {
189
- modelMatrix,
190
- worldVerts,
191
- boxMin,
192
- boxMax,
193
- };
194
- }
195
-
196
- export function addRaycastsAABBListener(canvasId = "canvas1") {
197
- const canvasDom = document.getElementById(canvasId);
198
- if(!canvasDom) {
199
- console.warn(`Canvas with id ${canvasId} not found`);
200
- return;
201
- }
202
-
203
- canvasDom.addEventListener('click', (event) => {
204
- const camera = app.cameras.WASD;
205
- const {rayOrigin, rayDirection} = getRayFromMouse2(event, canvasDom, camera);
206
- for(const object of app.mainRenderBundle) {
207
- const {boxMin, boxMax} = computeWorldVertsAndAABB(object);
208
- if(object.raycast.enabled == false) return;
209
- if(rayIntersectsAABB(rayOrigin, rayDirection, boxMin, boxMax)) {
210
- // console.log('AABB hit:', object.name);
211
- canvasDom.dispatchEvent(new CustomEvent('ray.hit.event', {
212
- detail: {hitObject: object},
213
- rayOrigin: rayOrigin,
214
- rayDirection: rayDirection
215
- }));
216
- }
217
- }
218
- });
219
- }