cleanup.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Cleanup</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – Cleanup">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="/files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="/files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="/manual/resources/lesson.css">
  12. <link rel="stylesheet" href="/manual/resources/lang.css">
  13. </head>
  14. <body>
  15. <div class="container">
  16. <div class="lesson-title">
  17. <h1>Cleanup</h1>
  18. </div>
  19. <div class="lesson">
  20. <div class="lesson-main">
  21. <p>Three.js apps often use lots of memory. A 3D model
  22. might be 1 to 20 meg memory for all of its vertices.
  23. A model might use many textures that even if they are
  24. compressed into jpg files they have to be expanded
  25. to their uncompressed form to use. Each 1024x1024
  26. texture takes 4 to 6meg of memory.</p>
  27. <p>Most three.js apps load resources at init time and
  28. then use those resources forever until the page is
  29. closed. But, what if you want to load and change resources
  30. over time?</p>
  31. <p>Unlike most JavaScript, three.js can not automatically
  32. clean these resources up. The browser will clean them
  33. up if you switch pages but otherwise it's up to you
  34. to manage them. This is an issue of how WebGL is designed
  35. and so three.js has no recourse but to pass on the
  36. responsibility to free resources back to you.</p>
  37. <p>You free three.js resource this by calling the <code class="notranslate" translate="no">dispose</code> function on
  38. <a href="textures.html">textures</a>,
  39. <a href="primitives.html">geometries</a>, and
  40. <a href="materials.html">materials</a>.</p>
  41. <p>You could do this manually. At the start you might create
  42. some of these resources</p>
  43. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const boxGeometry = new THREE.BoxGeometry(...);
  44. const boxTexture = textureLoader.load(...);
  45. const boxMaterial = new THREE.MeshPhongMaterial({map: texture});
  46. </pre>
  47. <p>and then when you're done with them you'd free them</p>
  48. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">boxGeometry.dispose();
  49. boxTexture.dispose();
  50. boxMaterial.dispose();
  51. </pre>
  52. <p>As you use more and more resources that would get more and
  53. more tedious.</p>
  54. <p>To help remove some of the tedium let's make a class to track
  55. the resources. We'll then ask that class to do the cleanup
  56. for us.</p>
  57. <p>Here's a first pass at such a class</p>
  58. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  59. constructor() {
  60. this.resources = new Set();
  61. }
  62. track(resource) {
  63. if (resource.dispose) {
  64. this.resources.add(resource);
  65. }
  66. return resource;
  67. }
  68. untrack(resource) {
  69. this.resources.delete(resource);
  70. }
  71. dispose() {
  72. for (const resource of this.resources) {
  73. resource.dispose();
  74. }
  75. this.resources.clear();
  76. }
  77. }
  78. </pre>
  79. <p>Let's use this class with the first example from <a href="textures.html">the article on textures</a>.
  80. We can create an instance of this class</p>
  81. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const resTracker = new ResourceTracker();
  82. </pre>
  83. <p>and then just to make it easier to use let's create a bound function for the <code class="notranslate" translate="no">track</code> method</p>
  84. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const resTracker = new ResourceTracker();
  85. +const track = resTracker.track.bind(resTracker);
  86. </pre>
  87. <p>Now to use it we just need to call <code class="notranslate" translate="no">track</code> with for each geometry, texture, and material
  88. we create</p>
  89. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const boxWidth = 1;
  90. const boxHeight = 1;
  91. const boxDepth = 1;
  92. -const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  93. +const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth));
  94. const cubes = []; // an array we can use to rotate the cubes
  95. const loader = new THREE.TextureLoader();
  96. -const material = new THREE.MeshBasicMaterial({
  97. - map: loader.load('resources/images/wall.jpg'),
  98. -});
  99. +const material = track(new THREE.MeshBasicMaterial({
  100. + map: track(loader.load('resources/images/wall.jpg')),
  101. +}));
  102. const cube = new THREE.Mesh(geometry, material);
  103. scene.add(cube);
  104. cubes.push(cube); // add to our list of cubes to rotate
  105. </pre>
  106. <p>And then to free them we'd want to remove the cubes from the scene
  107. and then call <code class="notranslate" translate="no">resTracker.dispose</code></p>
  108. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (const cube of cubes) {
  109. scene.remove(cube);
  110. }
  111. cubes.length = 0; // clears the cubes array
  112. resTracker.dispose();
  113. </pre>
  114. <p>That would work but I find having to remove the cubes from the
  115. scene kind of tedious. Let's add that functionality to the <code class="notranslate" translate="no">ResourceTracker</code>.</p>
  116. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  117. constructor() {
  118. this.resources = new Set();
  119. }
  120. track(resource) {
  121. - if (resource.dispose) {
  122. + if (resource.dispose || resource instanceof THREE.Object3D) {
  123. this.resources.add(resource);
  124. }
  125. return resource;
  126. }
  127. untrack(resource) {
  128. this.resources.delete(resource);
  129. }
  130. dispose() {
  131. for (const resource of this.resources) {
  132. - resource.dispose();
  133. + if (resource instanceof THREE.Object3D) {
  134. + if (resource.parent) {
  135. + resource.parent.remove(resource);
  136. + }
  137. + }
  138. + if (resource.dispose) {
  139. + resource.dispose();
  140. + }
  141. + }
  142. this.resources.clear();
  143. }
  144. }
  145. </pre>
  146. <p>And now we can track the cubes</p>
  147. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const material = track(new THREE.MeshBasicMaterial({
  148. map: track(loader.load('resources/images/wall.jpg')),
  149. }));
  150. const cube = track(new THREE.Mesh(geometry, material));
  151. scene.add(cube);
  152. cubes.push(cube); // add to our list of cubes to rotate
  153. </pre>
  154. <p>We no longer need the code to remove the cubes from the scene.</p>
  155. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-for (const cube of cubes) {
  156. - scene.remove(cube);
  157. -}
  158. cubes.length = 0; // clears the cube array
  159. resTracker.dispose();
  160. </pre>
  161. <p>Let's arrange this code so that we can re-add the cube,
  162. texture, and material.</p>
  163. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  164. *const cubes = []; // just an array we can use to rotate the cubes
  165. +function addStuffToScene() {
  166. const resTracker = new ResourceTracker();
  167. const track = resTracker.track.bind(resTracker);
  168. const boxWidth = 1;
  169. const boxHeight = 1;
  170. const boxDepth = 1;
  171. const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth));
  172. const loader = new THREE.TextureLoader();
  173. const material = track(new THREE.MeshBasicMaterial({
  174. map: track(loader.load('resources/images/wall.jpg')),
  175. }));
  176. const cube = track(new THREE.Mesh(geometry, material));
  177. scene.add(cube);
  178. cubes.push(cube); // add to our list of cubes to rotate
  179. + return resTracker;
  180. +}
  181. </pre>
  182. <p>And then let's write some code to add and remove things over time.</p>
  183. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function waitSeconds(seconds = 0) {
  184. return new Promise(resolve =&gt; setTimeout(resolve, seconds * 1000));
  185. }
  186. async function process() {
  187. for (;;) {
  188. const resTracker = addStuffToScene();
  189. await wait(2);
  190. cubes.length = 0; // remove the cubes
  191. resTracker.dispose();
  192. await wait(1);
  193. }
  194. }
  195. process();
  196. </pre>
  197. <p>This code will create the cube, texture and material, wait for 2 seconds, then dispose of them and wait for 1 second
  198. and repeat.</p>
  199. <p></p><div translate="no" class="threejs_example_container notranslate">
  200. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cleanup-simple.html"></iframe></div>
  201. <a class="threejs_center" href="/manual/examples/cleanup-simple.html" target="_blank">click here to open in a separate window</a>
  202. </div>
  203. <p></p>
  204. <p>So that seems to work.</p>
  205. <p>For a loaded file though it's a little more work. Most loaders only return an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>
  206. as a root of the hierarchy of objects they load so we need to discover what all the resources
  207. are.</p>
  208. <p>Let's update our <code class="notranslate" translate="no">ResourceTracker</code> to try to do that.</p>
  209. <p>First we'll check if the object is an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> then track its geometry, material, and children</p>
  210. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  211. constructor() {
  212. this.resources = new Set();
  213. }
  214. track(resource) {
  215. if (resource.dispose || resource instanceof THREE.Object3D) {
  216. this.resources.add(resource);
  217. }
  218. + if (resource instanceof THREE.Object3D) {
  219. + this.track(resource.geometry);
  220. + this.track(resource.material);
  221. + this.track(resource.children);
  222. + }
  223. return resource;
  224. }
  225. ...
  226. }
  227. </pre>
  228. <p>Now, because any of <code class="notranslate" translate="no">resource.geometry</code>, <code class="notranslate" translate="no">resource.material</code>, and <code class="notranslate" translate="no">resource.children</code>
  229. might be null or undefined we'll check at the top of <code class="notranslate" translate="no">track</code>.</p>
  230. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  231. constructor() {
  232. this.resources = new Set();
  233. }
  234. track(resource) {
  235. + if (!resource) {
  236. + return resource;
  237. + }
  238. if (resource.dispose || resource instanceof THREE.Object3D) {
  239. this.resources.add(resource);
  240. }
  241. if (resource instanceof THREE.Object3D) {
  242. this.track(resource.geometry);
  243. this.track(resource.material);
  244. this.track(resource.children);
  245. }
  246. return resource;
  247. }
  248. ...
  249. }
  250. </pre>
  251. <p>Also because <code class="notranslate" translate="no">resource.children</code> is an array and because <code class="notranslate" translate="no">resource.material</code> can be
  252. an array let's check for arrays</p>
  253. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  254. constructor() {
  255. this.resources = new Set();
  256. }
  257. track(resource) {
  258. if (!resource) {
  259. return resource;
  260. }
  261. + // handle children and when material is an array of materials.
  262. + if (Array.isArray(resource)) {
  263. + resource.forEach(resource =&gt; this.track(resource));
  264. + return resource;
  265. + }
  266. if (resource.dispose || resource instanceof THREE.Object3D) {
  267. this.resources.add(resource);
  268. }
  269. if (resource instanceof THREE.Object3D) {
  270. this.track(resource.geometry);
  271. this.track(resource.material);
  272. this.track(resource.children);
  273. }
  274. return resource;
  275. }
  276. ...
  277. }
  278. </pre>
  279. <p>And finally we need to walk the properties and uniforms
  280. of a material looking for textures.</p>
  281. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ResourceTracker {
  282. constructor() {
  283. this.resources = new Set();
  284. }
  285. track(resource) {
  286. if (!resource) {
  287. return resource;
  288. }
  289. * // handle children and when material is an array of materials or
  290. * // uniform is array of textures
  291. if (Array.isArray(resource)) {
  292. resource.forEach(resource =&gt; this.track(resource));
  293. return resource;
  294. }
  295. if (resource.dispose || resource instanceof THREE.Object3D) {
  296. this.resources.add(resource);
  297. }
  298. if (resource instanceof THREE.Object3D) {
  299. this.track(resource.geometry);
  300. this.track(resource.material);
  301. this.track(resource.children);
  302. - }
  303. + } else if (resource instanceof THREE.Material) {
  304. + // We have to check if there are any textures on the material
  305. + for (const value of Object.values(resource)) {
  306. + if (value instanceof THREE.Texture) {
  307. + this.track(value);
  308. + }
  309. + }
  310. + // We also have to check if any uniforms reference textures or arrays of textures
  311. + if (resource.uniforms) {
  312. + for (const value of Object.values(resource.uniforms)) {
  313. + if (value) {
  314. + const uniformValue = value.value;
  315. + if (uniformValue instanceof THREE.Texture ||
  316. + Array.isArray(uniformValue)) {
  317. + this.track(uniformValue);
  318. + }
  319. + }
  320. + }
  321. + }
  322. + }
  323. return resource;
  324. }
  325. ...
  326. }
  327. </pre>
  328. <p>And with that let's take an example from <a href="load-gltf.html">the article on loading gltf files</a>
  329. and make it load and free files.</p>
  330. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const gltfLoader = new GLTFLoader();
  331. function loadGLTF(url) {
  332. return new Promise((resolve, reject) =&gt; {
  333. gltfLoader.load(url, resolve, undefined, reject);
  334. });
  335. }
  336. function waitSeconds(seconds = 0) {
  337. return new Promise(resolve =&gt; setTimeout(resolve, seconds * 1000));
  338. }
  339. const fileURLs = [
  340. 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf',
  341. 'resources/models/3dbustchallange_submission/scene.gltf',
  342. 'resources/models/mountain_landscape/scene.gltf',
  343. 'resources/models/simple_house_scene/scene.gltf',
  344. ];
  345. async function loadFiles() {
  346. for (;;) {
  347. for (const url of fileURLs) {
  348. const resMgr = new ResourceTracker();
  349. const track = resMgr.track.bind(resMgr);
  350. const gltf = await loadGLTF(url);
  351. const root = track(gltf.scene);
  352. scene.add(root);
  353. // compute the box that contains all the stuff
  354. // from root and below
  355. const box = new THREE.Box3().setFromObject(root);
  356. const boxSize = box.getSize(new THREE.Vector3()).length();
  357. const boxCenter = box.getCenter(new THREE.Vector3());
  358. // set the camera to frame the box
  359. frameArea(boxSize * 1.1, boxSize, boxCenter, camera);
  360. await waitSeconds(2);
  361. renderer.render(scene, camera);
  362. resMgr.dispose();
  363. await waitSeconds(1);
  364. }
  365. }
  366. }
  367. loadFiles();
  368. </pre>
  369. <p>and we get</p>
  370. <p></p><div translate="no" class="threejs_example_container notranslate">
  371. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cleanup-loaded-files.html"></iframe></div>
  372. <a class="threejs_center" href="/manual/examples/cleanup-loaded-files.html" target="_blank">click here to open in a separate window</a>
  373. </div>
  374. <p></p>
  375. <p>Some notes about the code.</p>
  376. <p>If we wanted to load 2 or more files at once and free them at
  377. anytime we would use one <code class="notranslate" translate="no">ResourceTracker</code> per file.</p>
  378. <p>Above we are only tracking <code class="notranslate" translate="no">gltf.scene</code> right after loading.
  379. Based on our current implementation of <code class="notranslate" translate="no">ResourceTracker</code> that
  380. will track all the resources just loaded. If we added more
  381. things to the scene we need to decide whether or not to track them.</p>
  382. <p>For example let's say after we loaded a character we put a tool
  383. in their hand by making the tool a child of their hand. As it is
  384. that tool will not be freed. I'm guessing more often than not
  385. this is what we want. </p>
  386. <p>That brings up a point. Originally when I first wrote the <code class="notranslate" translate="no">ResourceTracker</code>
  387. above I walked through everything inside the <code class="notranslate" translate="no">dispose</code> method instead of <code class="notranslate" translate="no">track</code>.
  388. It was only later as I thought about the tool as a child of hand case above
  389. that it became clear that tracking exactly what to free in <code class="notranslate" translate="no">track</code> was more
  390. flexible and arguably more correct since we could then track what was loaded
  391. from the file rather than just freeing the state of the scene graph later.</p>
  392. <p>I honestly am not 100% happy with <code class="notranslate" translate="no">ResourceTracker</code>. Doing things this
  393. way is not common in 3D engines. We shouldn't have to guess what
  394. resources were loaded, we should know. It would be nice if three.js
  395. changed so that all file loaders returned some standard object with
  396. references to all the resources loaded. At least at the moment,
  397. three.js doesn't give us any more info when loading a scene so this
  398. solution seems to work.</p>
  399. <p>I hope you find this example useful or at least a good reference for what is
  400. required to free resources in three.js</p>
  401. </div>
  402. </div>
  403. </div>
  404. <script src="/manual/resources/prettify.js"></script>
  405. <script src="/manual/resources/lesson.js"></script>
  406. </body></html>