Clean up Threejs WebGl contexts

renderer, resource-cleanup, three.js, webgl

Solution

You can keep the same renderer for different scenes. The renderer does not care what scene it will render. You can supply a different `Scene` everytime you call `render()` if you like.

// instantiate only once and keep it
var renderer = new THREE.WebGLRenderer();

// current scene and camera. Switch whenever you like
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(...);
fillScene(scene);

// rendering always uses current scene
function render() {
    renderer.render(scene, camera);
    requestAnimationFrame(render);
}

/* ... 
 *   somewhere in your application
 * ...
 */
if(condition) {
  // switch scene
  scene = new THREE.Scene();
  fillOtherScene(scene);
}

Problem

I have a problem while cleaning up my WebGl-Scenes. I'm using Three.js with a WebGlRenderer. In my application I have to change the views quite often and therefore need to render new scenes all the time. Uptil now I destroy and reinitialize the entire Threejs scene. After switching the scenes about 15 - 20 times I get following warning: `WARNING: Too many active WebGL contexts. Oldest context will be lost.` After switching a couple of times more the context is lost completly and the application crashes. Is there a way to destroy the current WebGl context, when cleaning up? Or does the WebGlRenderer always create a new WebGl context when being instantiated? I'm using Three.js R64.

Original source