I try to write some very fast logic to detect all collisions in game.
So I using GPU.js for this and my code was crashing because I trying to create new array variable inside function?
I need list of all objects from constant (loaded to GPU/CPU memory) and this is fastest than in any call with new context.
import {GPU, KernelFunction, IKernelRunShortcut, IConstantsThis, IKernelFunctionThis, Texture} from 'gpu.js';
interface IConstants extends IConstantsThis {
elementsSize: number,
elements: Array<[number, number, number]>,
}
interface IThis extends IKernelFunctionThis {
constants: IConstants,
}
const gpu = new GPU({mode: 'cpu'});
gpu.addFunction<number[]>(function distance(x1, y1, z1, x2, y2, z2) {
const dx = x1 - x2;
const dy = y1 - y2;
const dz = z1 - z2;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}, {
argumentTypes: {x1: 'Float', y1: 'Float', z1: 'Float', x2: 'Float', y2: 'Float', z2: 'Float'},
returnType: 'Float',
});
const kernelMap = gpu.createKernel(function kernelFunction(this: IThis, objPosition: [number, number, number]) {
// @ts-ignore
const d = distance(
this.constants.elements[0][0],
this.constants.elements[0][1],
this.constants.elements[0][2],
objPosition[0],
objPosition[1],
objPosition[2],
)
const distances = []; // can't create here new variable
for (let i = 0; i < this.constants.elementsSize; i++) {
distances[i] = d;
}
return distances;
}, {
argumentTypes: {objPosition: 'Array(3)'},
constants: <IConstants>{
elementsSize: 2,
elements: [
[1, 1, 1],
[2, 2, 2],
// ... 100k elements
],
},
output: [1],
pipeline: true,
precision: 'single',
immutable: true
})
const result = kernelMap([0, 0, 0]);
console.log(JSON.stringify(result, null, 2));
How can I check all objects from constants and get result distance of every object?