eisensheng / agar-gamepad

// ==UserScript==
// @name            agar-gamepad
// @namespace       agar-gamepad.eisensheng.openuserjs.org
// @description     Move your blob with your gamepad from the couch!
// @license         MIT; http://opensource.org/licenses/MIT
// @include         http://agar.io/
// @version         1.0
// @grant           none
// @run-at          document-end
// @oujs:author     eisensheng
// ==/UserScript==
/*
Copyright (c) 2015 eisensheng

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* jshint esnext: true */

(function () {
    'use strict';
    var known_gamepads = {}, button_state = {a: 0, b: 0},
        el_overlays = document.getElementById('overlays'),
        el_crosshair = document.createElement('img'),
        el_canvas = document.getElementById('canvas'),
        pointing_pos = {clientX: (el_canvas.width / 2), 
                        clientY: (el_canvas.height / 2)},
        agar_update_position = null, disable_mouse = true;

    var crosshair_data = [
        'iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABHNCSVQICAgIfAh',
        'kiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAXBJREFUeJzt3bENAyEQAEFwU99/eF',
        'XZLRA9kncmJjidVgQkrEXavj3Am57n+Z6cm5nMXj63B+AuAcQJIE4AcQKIE0CcA',
        'OIEECeAOAHECSBOAHECiBNAnADiBBAngDgBxAkgTgBxAogTQJwA4gQQJ4A4AcQJ',
        'IE4AcQKIE0CcAOIEECeAOAHECSBOAHECiBNAnADiBBAngDgBxAkgTgBxAogTQJw',
        'A4gQQJ4A4AcQJIE4AcQKIE0CcAOIEECeAuL3W+Y+a/JeZ2W6AOAHECSBOAHECiB',
        'NAnADiBBAngLh9e4A3nb54zkxmL26AOAHECSBOAHECiBNAnADiBBAngDgBxAkgT',
        'gBxAogTQJwA4gQQJ4A4AcQJIE4AcQKIE0CcAOIEECeAOAHECSBOAHECiBNAnADi',
        'BBAngDgBxAkgTgBxAogTQJwA4gQQJ4A4AcQJIE4AcQKIE0CcAOIEECeAOAHECSB',
        'OAHECiBNAnADiBBAnACj7AceCDPoxnZOdAAAAAElFTkSuQmCC'
    ].join('');

    el_crosshair.src = 'data:image/png;base64,' + crosshair_data;
    ['position:absolute', 'z-index:199', 'width:64px', 'height:64px', 
     'left:0px', 'top:0px'].forEach(function (pair) {
        var tup = pair.split(':');
        el_crosshair.style[tup[0]] = tup[1];
    });
    document.getElementsByTagName('body')[0].appendChild(el_crosshair);

    el_canvas.style.cursor = 'none';

    function Vector2(x, y) {
        if (!(this instanceof Vector2)) {
            return new Vector2(x, y);
        }

        this.x = x || 0;
        this.y = y || 0;
    }

    Vector2.prototype.clone = function () {
        return new Vector2(this.x, this.y);
    };

    Vector2.prototype.add = function (v) {
        this.x += v.x;
        this.y += v.y;
        return this;
    };

    Vector2.prototype.subtract = function (v) {
        this.x -= v.x;
        this.y -= v.y;
        return this;
    };

    Vector2.prototype.multiply = function (v) {
        this.x *= v.x;
        this.y *= v.y;
        return this;
    };

    Vector2.prototype.distance_x = function (v) {
        return this.x - v.x;
    };

    Vector2.prototype.distance_y = function (v) {
        return this.y - v.y;
    };

    Vector2.prototype.distance_squared = function (v) {
        var dx = this.distance_x(v),
            dy = this.distance_y(v);

        return dx * dx + dy * dy;
    };

    Vector2.prototype.distance = function (v) {
        return Math.sqrt(this.distance_squared(v));
    };

    Vector2.prototype.horizontal_angle = function () {
        return Math.atan2(this.y, this.x);
    };

    Vector2.prototype.fenced = function (center, radius) {
        var rad = this.subtract(center).horizontal_angle();

        this.x = Math.cos(rad) * radius + center.x;
        this.y = Math.sin(rad) * radius + center.y;
        return this;
    };

    Vector2.prototype.to_fixed = function (digits) {
        this.x = this.x.toFixed(digits);
        this.y = this.y.toFixed(digits);
        return this;
    };

    function log (value) {
        console.log('[AGAR-GAMEPAD] ' + value);
    }

    function update_mouse_state () {
        if (disable_mouse) {
            el_canvas.style.cursor = 'none';
            el_crosshair.style.display = 'block';
        } else {
            el_canvas.style.cursor = 'default';
            el_crosshair.style.display = 'none';
        }
    }

    function gamepad_add (gamepad) {
        known_gamepads[gamepad.index] = gamepad;
        log('Gamepad found: ' + gamepad.id);
    }

    function gamepad_update_position (gamepad) {
        var center_pos = new Vector2(el_canvas.width / 2, 
                                     el_canvas.height / 2), 
            fov_radius = Math.min(center_pos.x, center_pos.y), 
            cross_pos = new Vector2(), gamepad_pos;

        gamepad_pos = (new Vector2(gamepad.axes[0] + 1, gamepad.axes[1] + 1))
                      .multiply(center_pos);
        gamepad_pos = (gamepad_pos.distance(center_pos) > fov_radius ? 
                       gamepad_pos.fenced(center_pos, fov_radius) : 
                       gamepad_pos).to_fixed(4);
        
        cross_pos = gamepad_pos.clone().subtract(new Vector2(32, 32));
        el_crosshair.style.left = cross_pos.x.toString() + 'px';
        el_crosshair.style.top = cross_pos.y.toString() + 'px';

        pointing_pos.clientX = gamepad_pos.x;
        pointing_pos.clientY = gamepad_pos.y;
        agar_update_position(pointing_pos);
    }

    function gamepad_button_a () {
        if (el_overlays.style.display === 'block') {
            if (el_overlays.style.opacity !== '')
                return;
            window.setNick(document.getElementById('nick').value); 
        } else {
            window.onkeydown({keyCode: 32});
            window.onkeyup({keyCode: 32});
        }
    }

    function gamepad_button_b () {
        window.onkeydown({keyCode: 87});
        window.onkeyup({keyCode: 87});
    }

    function gamepad_update_buttons (gamepad) {
        var button_a = gamepad.buttons[0].value|0, 
            button_b = gamepad.buttons[1].value|0;

        if (button_state.a != button_a) {
            if (button_a)
                gamepad_button_a();
            button_state.a = button_a;
        }

        if (button_state.b != button_b) {
            if (button_b)
                gamepad_button_b();
            button_state.b = button_b;
        }
    }

    function tick () {
        var found_gamepads = navigator.getGamepads(), 
            gamepad, selected_gamepad;
        
        for (var i = 0; i < found_gamepads.length; i++) {
            gamepad = found_gamepads[i];
            if (gamepad) {
                if (!(gamepad.index in known_gamepads))
                    gamepad_add(gamepad);
                selected_gamepad = gamepad;
            }
        }

        if (selected_gamepad) {
            if (disable_mouse)
                gamepad_update_position(selected_gamepad);
            gamepad_update_buttons(selected_gamepad);
        }

        window.requestAnimationFrame(tick);
    }

    window.addEventListener('gamepadconnected', function (e) {
        gamepad_add(e.gamepad);
    });
    window.addEventListener('gamepaddisconnected', function (e) {
        delete known_gamepads[e.gamepad.index];
    });
    window.addEventListener('mousemove', function (e) {
        if (!disable_mouse)
            agar_update_position(e);
    })
    window.addEventListener('keypress', function (e) {
        if (e.which == 116)
            disable_mouse = !disable_mouse

        update_mouse_state();

        if (localStorage) {
            localStorage.setItem('agar-gamepad.disable_mouse',
                                 disable_mouse ? 'yes' : 'no');
        }
    });

    (function overwrite_watch (start_time) {
        if (Date.now() - start_time > 10000)
            return log('Failed enabling extension.');
        
        if (!el_canvas.onmousemove)
            return setTimeout(overwrite_watch, 200, start_time);
      
        agar_update_position = el_canvas.onmousemove;
        el_canvas.onmousemove = null;

        window.requestAnimationFrame(function () { tick(); });
        log('STARTED');
    })(Date.now());

    if (localStorage) {
        disable_mouse = (localStorage
                         .getItem('agar-gamepad.disable_mouse') === 'yes');
        update_mouse_state();
    }
})();