Created
January 1, 2022 23:20
-
-
Save HoraceShmorace/5041e4f1392c16987a4215b70c89af13 to your computer and use it in GitHub Desktop.
Disposes of any Three.js object and any disposal objects in the hierarchy below it by doing a depth-first search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Disposes of any Three.js object (mesh, material, etc.) and any disposable objects in the hierarchy below it by doing a depth-first search. | |
* @param {Boolean} showLogging Output logs useful for troubleshooting. | |
* @example | |
* const trash = HierarchyDisposal(true) | |
* trash([some three.js object]) | |
*/ | |
function HierarchyDisposal (showLogging = false) { | |
const bag = [] | |
const ignoreKeys = [ | |
'_super', | |
'parent' | |
] | |
const dispose = (obj, ondone) => { | |
const id = obj.uuid | |
const name = obj.name || id || obj | |
if (bag.includes(id)) return | |
if (showLogging) console.log('calling dispose on', name) | |
for (var key in obj) { | |
const childObj = obj[key] | |
if ( | |
obj.hasOwnProperty(key) && | |
!ignoreKeys.includes(key) && | |
childObj && | |
typeof childObj === 'object' | |
) dispose(childObj) | |
} | |
if (typeof obj.dispose === 'function' && obj.uuid) { | |
if (showLogging) console.log('disposing of', name) | |
obj.dispose() | |
bag.push(id) | |
} | |
if (typeof ondone === 'function') ondone(bag) | |
} | |
return dispose | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment