gpujs / gpu.js

GPU Accelerated JavaScript
https://gpu.rocks
MIT License
15.1k stars 652 forks source link

Using for loop in kernel throws of float operations #678

Open Awendel opened 3 years ago

Awendel commented 3 years ago

Just spend half a day fixing a bug that was really hard to isolate.

Most Math by default gets converted to Float operations behind the scenes at the GLSL layer, which is very sound behaviour.

However if one writes a for loop in the manner of

for(let i = 0; i <length ; i++){

}

and now uses the "i" variable to compute stuff within blog, it throws of float division / multiplication and leads to wrong results. (since i is probably an integer in GLSL) This probably could be easily fixed on GLSL side by auto creating in the for loop a new float and assign it the "i" value and then always using that float_i instead of the original "i".

not sure if anyone else came across this bug / whether its been addressed. but implementing my suggestion would probably lead to a lot less nasty surprises.

EDIT: I realise that of course the "i" would also be used to access array indices, in which case always converting it to float would lead to errors. Dunno if hybrid approach would be feasible, so we have the float and int versions of the I and compile to int if we detect that it's used as array index and to float if in normal calculations. Of course there could always be edge cases hard to cover, maybe we should just throw a warning on compile stage if one detects usage of "i" in normal computation and then maybe linking to documentation that explains behaviour / solution.

A solution that works btw is to create a new variable and assign it the value maybe in the manner of:

const x = i +0.0

that's similar to how I solved my issue in the end.

ted-piotrowski commented 3 years ago

@Awendel can you provide the actual error? This loop should be fine and all Number in Javascript are floats behind the scenes and as far as I know represented as floats when transpiled.