ResourceTracker.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import * as THREE from 'three';
  2. export default class ResourceTracker {
  3. constructor() {
  4. this.resources = new Set();
  5. }
  6. track(resource) {
  7. if (!resource) {
  8. return resource;
  9. }
  10. // handle children and when material is an array of materials or
  11. // uniform is array of textures
  12. if (Array.isArray(resource)) {
  13. resource.forEach((resource) => this.track(resource));
  14. return resource;
  15. }
  16. if (resource.dispose || resource instanceof THREE.Object3D) {
  17. this.resources.add(resource);
  18. }
  19. if (resource instanceof THREE.Object3D) {
  20. this.track(resource.geometry);
  21. this.track(resource.material);
  22. this.track(resource.children);
  23. } else if (resource instanceof THREE.Material) {
  24. // We have to check if there are any textures on the material
  25. for (const value of Object.values(resource)) {
  26. if (value instanceof THREE.Texture) {
  27. this.track(value);
  28. }
  29. }
  30. // We also have to check if any uniforms reference textures or arrays of textures
  31. if (resource.uniforms) {
  32. for (const value of Object.values(resource.uniforms)) {
  33. if (value) {
  34. const uniformValue = value.value;
  35. if (uniformValue instanceof THREE.Texture || Array.isArray(uniformValue)) {
  36. this.track(uniformValue);
  37. }
  38. }
  39. }
  40. }
  41. }
  42. return resource;
  43. }
  44. untrack(resource) {
  45. resource = undefined;
  46. this.resources.delete(resource);
  47. }
  48. dispose() {
  49. for (const resource of this.resources) {
  50. try {
  51. if (resource instanceof THREE.Object3D) {
  52. if (resource.parent) {
  53. resource.parent.remove(resource);
  54. }
  55. }
  56. if (resource.dispose) {
  57. resource.dispose();
  58. }
  59. this.untrack(resource);
  60. } catch (error) {
  61. console.log('资源删除失败------>', resource);
  62. }
  63. }
  64. console.log('this.resources--------------->', this.resources);
  65. this.resources.clear();
  66. }
  67. doDispose(obj) {
  68. if (obj !== null) {
  69. for (var i = 0; i < obj.children.length; i++) {
  70. doDispose(obj.children[i]);
  71. }
  72. if (obj.geometry) {
  73. obj.geometry.dispose();
  74. obj.geometry = undefined;
  75. }
  76. if (obj.material) {
  77. if (obj.material.materials) {
  78. for (i = 0; i < obj.material.materials.length; i++) {
  79. obj.material.materials[i].dispose();
  80. }
  81. } else {
  82. obj.material.dispose();
  83. }
  84. obj.material = undefined;
  85. }
  86. if (obj.texture) {
  87. obj.texture.dispose();
  88. obj.texture = undefined;
  89. }
  90. }
  91. obj = undefined;
  92. }
  93. }