Reputation: 121
I am using OBJLoader.js. I have a button that on click removes a 3d model from scene and adds a new one but everytime the model is loaded, memory usage in chrome is increasing by about 50 MB and it is not reducing. I have tried "dispose()" and null, but not much of use. There is a animate function that is being called every second that renders the scene using renderer.
function freeMemory(model) {
if (model instanceof THREE.Mesh) {
var texMat = model.material;
texMat.map.dispose();
texMat.map = null;
texMat.dispose();
texMat = null;
model.geometry.dispose();
model.geometry = null;
model = null;
}
}
function loadModel() {
scene.remove(model);
freeMemory(model);
var loader = new THREE.OBJLoader();
loader.load('test3d.obj', function(object) {
object.children[0].geometry.computeFaceNormals();
geometry = object.children[0].geometry;
console.log(geometry);
geometry.dynamic = true;
var modelTexture = THREE.ImageUtils.loadTexture("models/tex_0.jpg");
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.map = modelTexture;
model = child;
model.scale.set(0.5, 0.5, 0.5);
model.translateOnAxis(new THREE.Vector3(1, 0, 1).normalize(),
1.5);
model.rotation.x = 0;
model.rotation.y = 0;
model.rotation.z = 0;
modelInitialPositionX = model.position.x;
modelInitialPositionY = model.position.y;
modelInitialPositionZ = model.position.z;
scene.add(model);
}
});
modelTexture.dispose();
modelTexture = null;
});
loader = null;
}
I there any best practice which i can use in adding and removing .obj and textures on button click.
Upvotes: 12
Views: 1004
Reputation: 151
a workaround is to try limiting the framerate. i found it keep the ram usage to a minimum. My sketch would keep using incremental ram until the pc would start to hang, sometimes the gpu usage was ~80%.
Limiting framerate in Three.js to increase performance, requestAnimationFrame?
Upvotes: -1
Reputation: 81
If you store the Object3D in a var before adding it to your Scene, you don't need to remove / dispose it and instantiate a new object, you can just modify it, and maybe this will not cause memory leaks.
try something like:
var model = new THREE.Mesh( firstGeometry, firstMaterial);
scene.add( model );
then, when you need to replace it, you just modify it:
model.geometry = newGeometry;
model.material = newMaterial;
without the need to add it again to your Scene.
if you fiddle it, I can edit your loadModel function.
Upvotes: 0
Reputation: 47
Try to stop the animation, with the following code:
animate(){
this.requestId = requestAnimationFrame(this.animate.bind(this));
this.render();
}
render(){
this.renderer.render(this.scene, this.camera);
}
stop(){
window.cancelAnimationFrame(this.requestId);
}
Upvotes: 0