effects_manager.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { ColorEffect } from '../effects/color_effect.js';
  2. import { NoiseEffect } from '../effects/noise_effect.js';
  3. /// An object to manage effects (by not destroying them all the time)
  4. export const EffectsManager = class EffectsManager {
  5. constructor(connections) {
  6. this.connections = connections;
  7. this.used = [];
  8. this.color_effects = [];
  9. this.noise_effects = [];
  10. }
  11. connect_to_destroy(effect) {
  12. effect.old_actor = effect.get_actor();
  13. if (effect.old_actor)
  14. effect.old_actor_id = effect.old_actor.connect('destroy', _ => {
  15. this.remove(effect);
  16. });
  17. this.connections.connect(effect, 'notify::actor', _ => {
  18. let actor = effect.get_actor();
  19. if (effect.old_actor && actor != effect.old_actor)
  20. effect.old_actor.disconnect(effect.old_actor_id);
  21. if (actor) {
  22. effect.old_actor_id = actor.connect('destroy', _ => {
  23. this.remove(effect);
  24. });
  25. }
  26. });
  27. }
  28. new_color_effect(params, settings) {
  29. let effect;
  30. if (this.color_effects.length > 0) {
  31. effect = this.color_effects.splice(0, 1)[0];
  32. effect.set(params);
  33. } else
  34. effect = new ColorEffect(params, settings);
  35. this.used.push(effect);
  36. this.connect_to_destroy(effect);
  37. return effect;
  38. }
  39. new_noise_effect(params, settings) {
  40. let effect;
  41. if (this.noise_effects.length > 0) {
  42. effect = this.noise_effects.splice(0, 1)[0];
  43. effect.set(params);
  44. } else
  45. effect = new NoiseEffect(params, settings);
  46. this.used.push(effect);
  47. this.connect_to_destroy(effect);
  48. return effect;
  49. }
  50. remove(effect) {
  51. effect.get_actor()?.remove_effect(effect);
  52. if (effect.old_actor)
  53. effect.old_actor.disconnect(effect.old_actor_id);
  54. delete effect.old_actor;
  55. delete effect.old_actor_id;
  56. let index = this.used.indexOf(effect);
  57. if (index >= 0) {
  58. this.used.splice(index, 1);
  59. if (effect instanceof ColorEffect)
  60. this.color_effects.push(effect);
  61. else if (effect instanceof NoiseEffect)
  62. this.noise_effects.push(effect);
  63. }
  64. }
  65. destroy_all() {
  66. this.used.forEach(effect => { this.remove(effect); });
  67. [
  68. this.used,
  69. this.color_effects,
  70. this.noise_effects
  71. ].forEach(array => {
  72. array.splice(0, array.length);
  73. });
  74. }
  75. };