Source: filters/displacement/DisplacementFilter.js

filters/displacement/DisplacementFilter.js

  1. import * as core from '../../core';
  2. import { readFileSync } from 'fs';
  3. import { join } from 'path';
  4. /**
  5. * The DisplacementFilter class uses the pixel values from the specified texture
  6. * (called the displacement map) to perform a displacement of an object. You can
  7. * use this filter to apply all manor of crazy warping effects. Currently the r
  8. * property of the texture is used to offset the x and the g property of the texture
  9. * is used to offset the y.
  10. *
  11. * @class
  12. * @extends PIXI.Filter
  13. * @memberof PIXI.filters
  14. */
  15. export default class DisplacementFilter extends core.Filter
  16. {
  17. /**
  18. * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!)
  19. * @param {number} scale - The scale of the displacement
  20. */
  21. constructor(sprite, scale)
  22. {
  23. const maskMatrix = new core.Matrix();
  24. sprite.renderable = false;
  25. super(
  26. // vertex shader
  27. readFileSync(join(__dirname, '../fragments/default-filter-matrix.vert'), 'utf8'),
  28. // fragment shader
  29. readFileSync(join(__dirname, './displacement.frag'), 'utf8')
  30. );
  31. this.maskSprite = sprite;
  32. this.maskMatrix = maskMatrix;
  33. this.uniforms.mapSampler = sprite._texture;
  34. this.uniforms.filterMatrix = maskMatrix;
  35. this.uniforms.scale = { x: 1, y: 1 };
  36. if (scale === null || scale === undefined)
  37. {
  38. scale = 20;
  39. }
  40. this.scale = new core.Point(scale, scale);
  41. }
  42. /**
  43. * Applies the filter.
  44. *
  45. * @param {PIXI.FilterManager} filterManager - The manager.
  46. * @param {PIXI.RenderTarget} input - The input target.
  47. * @param {PIXI.RenderTarget} output - The output target.
  48. */
  49. apply(filterManager, input, output)
  50. {
  51. this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite);
  52. this.uniforms.scale.x = this.scale.x;
  53. this.uniforms.scale.y = this.scale.y;
  54. // draw the filter...
  55. filterManager.applyFilter(this, input, output);
  56. }
  57. /**
  58. * The texture used for the displacement map. Must be power of 2 sized texture.
  59. *
  60. * @member {PIXI.Texture}
  61. */
  62. get map()
  63. {
  64. return this.uniforms.mapSampler;
  65. }
  66. set map(value) // eslint-disable-line require-jsdoc
  67. {
  68. this.uniforms.mapSampler = value;
  69. }
  70. }