jquery.ripples.js 26.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
/**
 * jQuery Ripples plugin v0.6.3 / https://github.com/sirxemic/jquery.ripples
 * MIT License
 * @author sirxemic / https://sirxemic.com/
 */

(function(global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined'
    ? factory(require('jquery'))
    : typeof define === 'function' && define.amd
    ? define(['jquery'], factory)
    : factory(global.$);
})(this, function($) {
  $ = $ && 'default' in $ ? $.default : $;

  let gl;
  const $window = $(window); // There is only one window, so why not cache the jQuery-wrapped window?

  function isPercentage(str) {
    return str[str.length - 1] == '%';
  }

  /**
   *  Load a configuration of GL settings which the browser supports.
   *  For example:
   *  - not all browsers support WebGL
   *  - not all browsers support floating point textures
   *  - not all browsers support linear filtering for floating point textures
   *  - not all browsers support rendering to floating point textures
   *  - some browsers *do* support rendering to half-floating point textures instead.
   */
  function loadConfig() {
    const canvas = document.createElement('canvas');
    gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

    if (!gl) {
      // Browser does not support WebGL.
      return null;
    }

    // Load extensions
    const extensions = {};
    [
      'OES_texture_float',
      'OES_texture_half_float',
      'OES_texture_float_linear',
      'OES_texture_half_float_linear',
    ].forEach(function(name) {
      const extension = gl.getExtension(name);
      if (extension) {
        extensions[name] = extension;
      }
    });

    // If no floating point extensions are supported we can bail out early.
    if (!extensions.OES_texture_float) {
      return null;
    }

    const configs = [];

    function createConfig(type, glType, arrayType) {
      const name = `OES_texture_${type}`;
      const nameLinear = `${name}_linear`;
      const linearSupport = nameLinear in extensions;
      const configExtensions = [name];

      if (linearSupport) {
        configExtensions.push(nameLinear);
      }

      return {
        type: glType,
        arrayType,
        linearSupport,
        extensions: configExtensions,
      };
    }

    configs.push(createConfig('float', gl.FLOAT, Float32Array));

    if (extensions.OES_texture_half_float) {
      configs.push(
        // Array type should be Uint16Array, but at least on iOS that breaks. In that case we
        // just initialize the textures with data=null, instead of data=new Uint16Array(...).
        // This makes initialization a tad slower, but it's still negligible.
        createConfig('half_float', extensions.OES_texture_half_float.HALF_FLOAT_OES, null),
      );
    }

    // Setup the texture and framebuffer
    const texture = gl.createTexture();
    const framebuffer = gl.createFramebuffer();

    gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    // Check for each supported texture type if rendering to it is supported
    let config = null;

    for (let i = 0; i < configs.length; i++) {
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, configs[i].type, null);

      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
      if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
        config = configs[i];
        break;
      }
    }

    return config;
  }

  function createImageData(width, height) {
    try {
      return new ImageData(width, height);
    } catch (e) {
      // Fallback for IE
      const canvas = document.createElement('canvas');
      return canvas.getContext('2d').createImageData(width, height);
    }
  }

  function translateBackgroundPosition(value) {
    const parts = value.split(' ');

    if (parts.length === 1) {
      switch (value) {
        case 'center':
          return ['50%', '50%'];
        case 'top':
          return ['50%', '0'];
        case 'bottom':
          return ['50%', '100%'];
        case 'left':
          return ['0', '50%'];
        case 'right':
          return ['100%', '50%'];
        default:
          return [value, '50%'];
      }
    } else {
      return parts.map(function(part) {
        switch (value) {
          case 'center':
            return '50%';
          case 'top':
          case 'left':
            return '0';
          case 'right':
          case 'bottom':
            return '100%';
          default:
            return part;
        }
      });
    }
  }

  function createProgram(vertexSource, fragmentSource, uniformValues) {
    function compileSource(type, source) {
      const shader = gl.createShader(type);
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        throw new Error(`compile error: ${gl.getShaderInfoLog(shader)}`);
      }
      return shader;
    }

    const program = {};

    program.id = gl.createProgram();
    gl.attachShader(program.id, compileSource(gl.VERTEX_SHADER, vertexSource));
    gl.attachShader(program.id, compileSource(gl.FRAGMENT_SHADER, fragmentSource));
    gl.linkProgram(program.id);
    if (!gl.getProgramParameter(program.id, gl.LINK_STATUS)) {
      throw new Error(`link error: ${gl.getProgramInfoLog(program.id)}`);
    }

    // Fetch the uniform and attribute locations
    program.uniforms = {};
    program.locations = {};
    gl.useProgram(program.id);
    gl.enableVertexAttribArray(0);
    let match;
    let name;
    const regex = /uniform (\w+) (\w+)/g;
    const shaderCode = vertexSource + fragmentSource;
    while ((match = regex.exec(shaderCode)) != null) {
      name = match[2];
      program.locations[name] = gl.getUniformLocation(program.id, name);
    }

    return program;
  }

  function bindTexture(texture, unit) {
    gl.activeTexture(gl.TEXTURE0 + (unit || 0));
    gl.bindTexture(gl.TEXTURE_2D, texture);
  }

  function extractUrl(value) {
    const urlMatch = /url\(["']?([^"']*)["']?\)/.exec(value);
    if (urlMatch == null) {
      return null;
    }

    return urlMatch[1];
  }

  function isDataUri(url) {
    return url.match(/^data:/);
  }

  const config = loadConfig();
  const transparentPixels = createImageData(32, 32);

  // Extend the css
  $('head').prepend('<style>.jquery-ripples { position: relative; z-index: 0; }</style>');

  // RIPPLES CLASS DEFINITION
  // =========================

  const Ripples = function(el, options) {
    const that = this;

    this.$el = $(el);

    // Init properties from options
    this.interactive = options.interactive;
    this.resolution = options.resolution;
    this.textureDelta = new Float32Array([1 / this.resolution, 1 / this.resolution]);

    this.perturbance = options.perturbance;
    this.dropRadius = options.dropRadius;

    this.crossOrigin = options.crossOrigin;
    this.imageUrl = options.imageUrl;

    // Init WebGL canvas
    const canvas = document.createElement('canvas');
    canvas.width = this.$el.innerWidth();
    canvas.height = this.$el.innerHeight();
    this.canvas = canvas;
    this.$canvas = $(canvas);
    this.$canvas.css({
      position: 'absolute',
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
      zIndex: -1,
    });

    this.$el.addClass('jquery-ripples').append(canvas);
    this.context = gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

    // Load extensions
    config.extensions.forEach(function(name) {
      gl.getExtension(name);
    });

    // Auto-resize when window size changes.
    this.updateSize = this.updateSize.bind(this);
    $(window).on('resize', this.updateSize);

    // Init rendertargets for ripple data.
    this.textures = [];
    this.framebuffers = [];
    this.bufferWriteIndex = 0;
    this.bufferReadIndex = 1;

    const { arrayType } = config;
    const textureData = arrayType ? new arrayType(this.resolution * this.resolution * 4) : null;

    for (let i = 0; i < 2; i++) {
      const texture = gl.createTexture();
      const framebuffer = gl.createFramebuffer();

      gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);

      gl.bindTexture(gl.TEXTURE_2D, texture);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, config.linearSupport ? gl.LINEAR : gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, config.linearSupport ? gl.LINEAR : gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.resolution, this.resolution, 0, gl.RGBA, config.type, textureData);

      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

      this.textures.push(texture);
      this.framebuffers.push(framebuffer);
    }

    // Init GL stuff
    this.quad = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, this.quad);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, +1, -1, +1, +1, -1, +1]), gl.STATIC_DRAW);

    this.initShaders();
    this.initTexture();
    this.setTransparentTexture();

    // Load the image either from the options or CSS rules
    this.loadImage();

    // Set correct clear color and blend mode (regular alpha blending)
    gl.clearColor(0, 0, 0, 0);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    // Plugin is successfully initialized!
    this.visible = true;
    this.running = true;
    this.inited = true;
    this.destroyed = false;

    this.setupPointerEvents();

    // Init animation
    function step() {
      if (!that.destroyed) {
        that.step();

        requestAnimationFrame(step);
      }
    }

    requestAnimationFrame(step);
  };

  Ripples.DEFAULTS = {
    imageUrl: null,
    resolution: 256,
    dropRadius: 20,
    perturbance: 0.03,
    interactive: true,
    crossOrigin: '',
  };

  Ripples.prototype = {
    // Set up pointer (mouse + touch) events
    setupPointerEvents() {
      const that = this;

      function pointerEventsEnabled() {
        return that.visible && that.running && that.interactive;
      }

      function dropAtPointer(pointer, big) {
        if (pointerEventsEnabled()) {
          that.dropAtPointer(pointer, that.dropRadius * (big ? 1.5 : 1), big ? 0.14 : 0.01);
        }
      }

      // Start listening to pointer events
      this.$el

        // Create regular, small ripples for mouse move and touch events...
        .on('mousemove.ripples', function(e) {
          dropAtPointer(e);
        })
        .on('touchmove.ripples touchstart.ripples', function(e) {
          const touches = e.originalEvent.changedTouches;
          for (let i = 0; i < touches.length; i++) {
            dropAtPointer(touches[i]);
          }
        })

        // ...and only a big ripple on mouse down events.
        .on('mousedown.ripples', function(e) {
          dropAtPointer(e, true);
        });
    },

    // Load the image either from the options or the element's CSS rules.
    loadImage() {
      const that = this;

      gl = this.context;

      const newImageSource =
        this.imageUrl || extractUrl(this.originalCssBackgroundImage) || extractUrl(this.$el.css('backgroundImage'));

      // If image source is unchanged, don't reload it.
      if (newImageSource == this.imageSource) {
        return;
      }

      this.imageSource = newImageSource;

      // Falsy source means no background.
      if (!this.imageSource) {
        this.setTransparentTexture();
        return;
      }

      // Load the texture from a new image.
      const image = new Image();
      image.onload = function() {
        gl = that.context;

        // Only textures with dimensions of powers of two can have repeat wrapping.
        function isPowerOfTwo(x) {
          return (x & (x - 1)) == 0;
        }

        const wrapping = isPowerOfTwo(image.width) && isPowerOfTwo(image.height) ? gl.REPEAT : gl.CLAMP_TO_EDGE;

        gl.bindTexture(gl.TEXTURE_2D, that.backgroundTexture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapping);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapping);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

        that.backgroundWidth = image.width;
        that.backgroundHeight = image.height;

        // Hide the background that we're replacing.
        that.hideCssBackground();
      };

      // Fall back to a transparent texture when loading the image failed.
      image.onerror = function() {
        gl = that.context;

        that.setTransparentTexture();
      };

      // Disable CORS when the image source is a data URI.
      image.crossOrigin = isDataUri(this.imageSource) ? null : this.crossOrigin;

      image.src = this.imageSource;
    },

    step() {
      gl = this.context;

      if (!this.visible) {
        return;
      }

      this.computeTextureBoundaries();

      if (this.running) {
        this.update();
      }

      this.render();
    },

    drawQuad() {
      gl.bindBuffer(gl.ARRAY_BUFFER, this.quad);
      gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
      gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
    },

    render() {
      gl.bindFramebuffer(gl.FRAMEBUFFER, null);

      gl.viewport(0, 0, this.canvas.width, this.canvas.height);

      gl.enable(gl.BLEND);
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

      gl.useProgram(this.renderProgram.id);

      bindTexture(this.backgroundTexture, 0);
      bindTexture(this.textures[0], 1);

      gl.uniform1f(this.renderProgram.locations.perturbance, this.perturbance);
      gl.uniform2fv(this.renderProgram.locations.topLeft, this.renderProgram.uniforms.topLeft);
      gl.uniform2fv(this.renderProgram.locations.bottomRight, this.renderProgram.uniforms.bottomRight);
      gl.uniform2fv(this.renderProgram.locations.containerRatio, this.renderProgram.uniforms.containerRatio);
      gl.uniform1i(this.renderProgram.locations.samplerBackground, 0);
      gl.uniform1i(this.renderProgram.locations.samplerRipples, 1);

      this.drawQuad();
      gl.disable(gl.BLEND);
    },

    update() {
      gl.viewport(0, 0, this.resolution, this.resolution);

      gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[this.bufferWriteIndex]);
      bindTexture(this.textures[this.bufferReadIndex]);
      gl.useProgram(this.updateProgram.id);

      this.drawQuad();

      this.swapBufferIndices();
    },

    swapBufferIndices() {
      this.bufferWriteIndex = 1 - this.bufferWriteIndex;
      this.bufferReadIndex = 1 - this.bufferReadIndex;
    },

    computeTextureBoundaries() {
      let backgroundSize = this.$el.css('background-size');
      const backgroundAttachment = this.$el.css('background-attachment');
      const backgroundPosition = translateBackgroundPosition(this.$el.css('background-position'));

      // Here the 'container' is the element which the background adapts to
      // (either the chrome window or some element, depending on attachment)
      let container;
      if (backgroundAttachment == 'fixed') {
        container = { left: window.pageXOffset, top: window.pageYOffset };
        container.width = $window.width();
        container.height = $window.height();
      } else {
        container = this.$el.offset();
        container.width = this.$el.innerWidth();
        container.height = this.$el.innerHeight();
      }

      // TODO: background-clip
      if (backgroundSize == 'cover') {
        var scale = Math.max(container.width / this.backgroundWidth, container.height / this.backgroundHeight);

        var backgroundWidth = this.backgroundWidth * scale;
        var backgroundHeight = this.backgroundHeight * scale;
      } else if (backgroundSize == 'contain') {
        var scale = Math.min(container.width / this.backgroundWidth, container.height / this.backgroundHeight);

        var backgroundWidth = this.backgroundWidth * scale;
        var backgroundHeight = this.backgroundHeight * scale;
      } else {
        backgroundSize = backgroundSize.split(' ');
        var backgroundWidth = backgroundSize[0] || '';
        var backgroundHeight = backgroundSize[1] || backgroundWidth;

        if (isPercentage(backgroundWidth)) {
          backgroundWidth = (container.width * parseFloat(backgroundWidth)) / 100;
        } else if (backgroundWidth != 'auto') {
          backgroundWidth = parseFloat(backgroundWidth);
        }

        if (isPercentage(backgroundHeight)) {
          backgroundHeight = (container.height * parseFloat(backgroundHeight)) / 100;
        } else if (backgroundHeight != 'auto') {
          backgroundHeight = parseFloat(backgroundHeight);
        }

        if (backgroundWidth == 'auto' && backgroundHeight == 'auto') {
          backgroundWidth = this.backgroundWidth;
          backgroundHeight = this.backgroundHeight;
        } else {
          if (backgroundWidth == 'auto') {
            backgroundWidth = this.backgroundWidth * (backgroundHeight / this.backgroundHeight);
          }

          if (backgroundHeight == 'auto') {
            backgroundHeight = this.backgroundHeight * (backgroundWidth / this.backgroundWidth);
          }
        }
      }

      // Compute backgroundX and backgroundY in page coordinates
      let backgroundX = backgroundPosition[0];
      let backgroundY = backgroundPosition[1];

      if (isPercentage(backgroundX)) {
        backgroundX = container.left + ((container.width - backgroundWidth) * parseFloat(backgroundX)) / 100;
      } else {
        backgroundX = container.left + parseFloat(backgroundX);
      }

      if (isPercentage(backgroundY)) {
        backgroundY = container.top + ((container.height - backgroundHeight) * parseFloat(backgroundY)) / 100;
      } else {
        backgroundY = container.top + parseFloat(backgroundY);
      }

      const elementOffset = this.$el.offset();

      this.renderProgram.uniforms.topLeft = new Float32Array([
        (elementOffset.left - backgroundX) / backgroundWidth,
        (elementOffset.top - backgroundY) / backgroundHeight,
      ]);
      this.renderProgram.uniforms.bottomRight = new Float32Array([
        this.renderProgram.uniforms.topLeft[0] + this.$el.innerWidth() / backgroundWidth,
        this.renderProgram.uniforms.topLeft[1] + this.$el.innerHeight() / backgroundHeight,
      ]);

      const maxSide = Math.max(this.canvas.width, this.canvas.height);

      this.renderProgram.uniforms.containerRatio = new Float32Array([
        this.canvas.width / maxSide,
        this.canvas.height / maxSide,
      ]);
    },

    initShaders() {
      const vertexShader = [
        'attribute vec2 vertex;',
        'varying vec2 coord;',
        'void main() {',
        'coord = vertex * 0.5 + 0.5;',
        'gl_Position = vec4(vertex, 0.0, 1.0);',
        '}',
      ].join('\n');

      this.dropProgram = createProgram(
        vertexShader,
        [
          'precision highp float;',

          'const float PI = 3.141592653589793;',
          'uniform sampler2D texture;',
          'uniform vec2 center;',
          'uniform float radius;',
          'uniform float strength;',

          'varying vec2 coord;',

          'void main() {',
          'vec4 info = texture2D(texture, coord);',

          'float drop = max(0.0, 1.0 - length(center * 0.5 + 0.5 - coord) / radius);',
          'drop = 0.5 - cos(drop * PI) * 0.5;',

          'info.r += drop * strength;',

          'gl_FragColor = info;',
          '}',
        ].join('\n'),
      );

      this.updateProgram = createProgram(
        vertexShader,
        [
          'precision highp float;',

          'uniform sampler2D texture;',
          'uniform vec2 delta;',

          'varying vec2 coord;',

          'void main() {',
          'vec4 info = texture2D(texture, coord);',

          'vec2 dx = vec2(delta.x, 0.0);',
          'vec2 dy = vec2(0.0, delta.y);',

          'float average = (',
          'texture2D(texture, coord - dx).r +',
          'texture2D(texture, coord - dy).r +',
          'texture2D(texture, coord + dx).r +',
          'texture2D(texture, coord + dy).r',
          ') * 0.25;',

          'info.g += (average - info.r) * 2.0;',
          'info.g *= 0.995;',
          'info.r += info.g;',

          'gl_FragColor = info;',
          '}',
        ].join('\n'),
      );
      gl.uniform2fv(this.updateProgram.locations.delta, this.textureDelta);

      this.renderProgram = createProgram(
        [
          'precision highp float;',

          'attribute vec2 vertex;',
          'uniform vec2 topLeft;',
          'uniform vec2 bottomRight;',
          'uniform vec2 containerRatio;',
          'varying vec2 ripplesCoord;',
          'varying vec2 backgroundCoord;',
          'void main() {',
          'backgroundCoord = mix(topLeft, bottomRight, vertex * 0.5 + 0.5);',
          'backgroundCoord.y = 1.0 - backgroundCoord.y;',
          'ripplesCoord = vec2(vertex.x, -vertex.y) * containerRatio * 0.5 + 0.5;',
          'gl_Position = vec4(vertex.x, -vertex.y, 0.0, 1.0);',
          '}',
        ].join('\n'),
        [
          'precision highp float;',

          'uniform sampler2D samplerBackground;',
          'uniform sampler2D samplerRipples;',
          'uniform vec2 delta;',

          'uniform float perturbance;',
          'varying vec2 ripplesCoord;',
          'varying vec2 backgroundCoord;',

          'void main() {',
          'float height = texture2D(samplerRipples, ripplesCoord).r;',
          'float heightX = texture2D(samplerRipples, vec2(ripplesCoord.x + delta.x, ripplesCoord.y)).r;',
          'float heightY = texture2D(samplerRipples, vec2(ripplesCoord.x, ripplesCoord.y + delta.y)).r;',
          'vec3 dx = vec3(delta.x, heightX - height, 0.0);',
          'vec3 dy = vec3(0.0, heightY - height, delta.y);',
          'vec2 offset = -normalize(cross(dy, dx)).xz;',
          'float specular = pow(max(0.0, dot(offset, normalize(vec2(-0.6, 1.0)))), 4.0);',
          'gl_FragColor = texture2D(samplerBackground, backgroundCoord + offset * perturbance) + specular;',
          '}',
        ].join('\n'),
      );
      gl.uniform2fv(this.renderProgram.locations.delta, this.textureDelta);
    },

    initTexture() {
      this.backgroundTexture = gl.createTexture();
      gl.bindTexture(gl.TEXTURE_2D, this.backgroundTexture);
      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    },

    setTransparentTexture() {
      gl.bindTexture(gl.TEXTURE_2D, this.backgroundTexture);
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, transparentPixels);
    },

    hideCssBackground() {
      // Check whether we're changing inline CSS or overriding a global CSS rule.
      const inlineCss = this.$el[0].style.backgroundImage;

      if (inlineCss == 'none') {
        return;
      }

      this.originalInlineCss = inlineCss;

      this.originalCssBackgroundImage = this.$el.css('backgroundImage');
      this.$el.css('backgroundImage', 'none');
    },

    restoreCssBackground() {
      // Restore background by either changing the inline CSS rule to what it was, or
      // simply remove the inline CSS rule if it never was inlined.
      this.$el.css('backgroundImage', this.originalInlineCss || '');
    },

    dropAtPointer(pointer, radius, strength) {
      const borderLeft = parseInt(this.$el.css('border-left-width')) || 0;
      const borderTop = parseInt(this.$el.css('border-top-width')) || 0;

      this.drop(
        pointer.pageX - this.$el.offset().left - borderLeft,
        pointer.pageY - this.$el.offset().top - borderTop,
        radius,
        strength,
      );
    },

    /**
     *  Public methods
     */
    drop(x, y, radius, strength) {
      gl = this.context;

      const elWidth = this.$el.innerWidth();
      const elHeight = this.$el.innerHeight();
      const longestSide = Math.max(elWidth, elHeight);

      radius /= longestSide;

      const dropPosition = new Float32Array([(2 * x - elWidth) / longestSide, (elHeight - 2 * y) / longestSide]);

      gl.viewport(0, 0, this.resolution, this.resolution);

      gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[this.bufferWriteIndex]);
      bindTexture(this.textures[this.bufferReadIndex]);

      gl.useProgram(this.dropProgram.id);
      gl.uniform2fv(this.dropProgram.locations.center, dropPosition);
      gl.uniform1f(this.dropProgram.locations.radius, radius);
      gl.uniform1f(this.dropProgram.locations.strength, strength);

      this.drawQuad();

      this.swapBufferIndices();
    },

    updateSize() {
      const newWidth = this.$el.innerWidth();
      const newHeight = this.$el.innerHeight();

      if (newWidth != this.canvas.width || newHeight != this.canvas.height) {
        this.canvas.width = newWidth;
        this.canvas.height = newHeight;
      }
    },

    destroy() {
      this.$el
        .off('.ripples')
        .removeClass('jquery-ripples')
        .removeData('ripples');

      // Make sure the last used context is garbage-collected
      gl = null;

      $(window).off('resize', this.updateSize);

      this.$canvas.remove();
      this.restoreCssBackground();

      this.destroyed = true;
    },

    show() {
      this.visible = true;

      this.$canvas.show();
      this.hideCssBackground();
    },

    hide() {
      this.visible = false;

      this.$canvas.hide();
      this.restoreCssBackground();
    },

    pause() {
      this.running = false;
    },

    play() {
      this.running = true;
    },

    set(property, value) {
      switch (property) {
        case 'dropRadius':
        case 'perturbance':
        case 'interactive':
        case 'crossOrigin':
          this[property] = value;
          break;
        case 'imageUrl':
          this.imageUrl = value;
          this.loadImage();
          break;
      }
    },
  };

  // RIPPLES PLUGIN DEFINITION
  // ==========================

  const old = $.fn.ripples;

  $.fn.ripples = function(option) {
    if (!config) {
      throw new Error(
        'Your browser does not support WebGL, the OES_texture_float extension or rendering to floating point textures.',
      );
    }

    const args = arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : undefined;

    return this.each(function() {
      const $this = $(this);
      let data = $this.data('ripples');
      const options = $.extend({}, Ripples.DEFAULTS, $this.data(), typeof option === 'object' && option);

      if (!data && typeof option === 'string') {
        return;
      }
      if (!data) {
        $this.data('ripples', (data = new Ripples(this, options)));
      } else if (typeof option === 'string') {
        Ripples.prototype[option].apply(data, args);
      }
    });
  };

  $.fn.ripples.Constructor = Ripples;

  // RIPPLES NO CONFLICT
  // ====================

  $.fn.ripples.noConflict = function() {
    $.fn.ripples = old;
    return this;
  };
});