diff --git a/src/backend/web-gl/fragment-shader.js b/src/backend/web-gl/fragment-shader.js index 166e80e5..c59be4c4 100644 --- a/src/backend/web-gl/fragment-shader.js +++ b/src/backend/web-gl/fragment-shader.js @@ -24,8 +24,12 @@ float asinh(float x) { } float atan2(float v1, float v2) { - if (v1 == 0.0 || v2 == 0.0) return 0.0; - return atan(v1 / v2); + if (v2 == 0.0) { + if (v1 == 0.0) return 0.0; + if (v1 > 0.0) return 1.5707963267948966; + if (v1 < 0.0) return -1.5707963267948966; + } + return atan(v1, v2); } float atanh(float x) { diff --git a/src/backend/web-gl2/fragment-shader.js b/src/backend/web-gl2/fragment-shader.js index b45a8706..28bdc819 100644 --- a/src/backend/web-gl2/fragment-shader.js +++ b/src/backend/web-gl2/fragment-shader.js @@ -14,8 +14,12 @@ __CONSTANTS__; in vec2 vTexCoord; float atan2(float v1, float v2) { - if (v1 == 0.0 || v2 == 0.0) return 0.0; - return atan(v1 / v2); + if (v2 == 0.0) { + if (v1 == 0.0) return 0.0; + if (v1 > 0.0) return 1.5707963267948966; + if (v1 < 0.0) return -1.5707963267948966; + } + return atan(v1, v2); } float cbrt(float x) { diff --git a/test/all.html b/test/all.html index c538a108..e32c9d08 100644 --- a/test/all.html +++ b/test/all.html @@ -180,6 +180,7 @@ + diff --git a/test/issues/647-atan2-range.js b/test/issues/647-atan2-range.js new file mode 100644 index 00000000..7ddd7bc3 --- /dev/null +++ b/test/issues/647-atan2-range.js @@ -0,0 +1,50 @@ +const { assert, skip, test, module: describe } = require('qunit'); +const { GPU } = require('../../src'); + +describe('issue #647'); + +function buildAtan2KernelResult(mode) { + const gpu = new GPU({ mode }); + const kernel = gpu.createKernel(function (x, y) { + return Math.atan2(y[this.thread.x], x[this.thread.x]); + }, { + output: [5], + }); + + // test atan2 at center, E, N, W, S on unit circle + // [0,0] [1,0], [0, 1], [-1, 0], [0, -1] + const x = [0, 1, 0, -1, 0]; + const y = [0, 0, 1, 0, -1]; + const result = kernel(x, y); + + assert.equal(result[0].toFixed(7), 0.0000000); + assert.equal(result[1].toFixed(7), 0.0000000); + assert.equal(result[2].toFixed(7), 1.5707964); + assert.equal(result[3].toFixed(7), 3.1415927); + assert.equal(result[4].toFixed(7), -1.5707964); + gpu.destroy(); +} + +test('Issue #647 atan2 - auto', () => { + buildAtan2KernelResult(); +}); + +test('Issue #647 atan2 - gpu', () => { + buildAtan2KernelResult('gpu'); +}); + +(GPU.isWebGLSupported ? test : skip)('Issue #647 atan2 - webgl', () => { + buildAtan2KernelResult('webgl'); +}); + +(GPU.isWebGL2Supported ? test : skip)('Issue #647 atan2 - webgl2', () => { + buildAtan2KernelResult('webgl2'); +}); + +(GPU.isHeadlessGLSupported ? test : skip)('Issue #647 atan2 - headlessgl', () => { + buildAtan2KernelResult('headlessgl'); +}); + +test('Issue #647 atan2 - cpu', () => { + buildAtan2KernelResult('cpu'); +});