Dispose of 3D models automatically when they are no longer in sight

To optimize memory usage in my application, I've implemented a method to dispose of any 3D models that are no longer visible to the camera. This involves checking if the camera can see the position of each model using model.position. The following code snippet is part of my animate loop.

const frustum = new THREE.Frustum();
const matrix = new THREE.Matrix4().multiplyMatrices(test.camera.projectionMatrix, test.camera.matrixWorldInverse);
frustum.setFromProjectionMatrix(matrix);

let earthContainerPos = { ...earthContainer.position }; //using spread syntax to remove reference to container position
earthContainerPos.z += 10; //ensure complete removal only when out of view 
if (!frustum.containsPoint(earthContainerPos)) {
   console.log('Out of view')
   earthContainer.dispose(); //attempting to dispose of the model, but encountering issues
};

The technique successfully detects when a model goes out of view, however, I'm facing difficulties with the disposal method for my container which holds two 3D models. Should I dispose of everything or is there a more efficient way to handle this?


Model Details:

  • GLTF models
  • 2 models stored in the container

Answer №1

earthContainer.dispose();

If earthContainer is of type Object3D, executing this code will result in a runtime error. The dispose() method is only available for specific classes such as BufferGeometry, Material, Texture, or WebGLRenderTarget.

Additionally, the practice of calling dispose() when a 3D object leaves the view doesn't seem logical. The rendering engine already ensures that objects are only rendered when they are within the view frustum, making it more efficient than premature resource deallocation which may lead to unnecessary overhead. For instance, invoking dispose() on a material could delete its corresponding shader. If you later need to render an object with the same material again, a costly recompilation process would be necessary.

I recommend using dispose() only if the resources are not needed again in your application. For further details on dispose(), please refer to the following guide:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Using Jquery's closest technique to target a class located outside of the parent div

I am having trouble accessing a class outside of its parent div $(document).on('click', '.delete_photo', function(event){ var del_id = $(this).attr('id'); $.ajax({ type:'POST', cache: false, url:&apo ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

Sending KeyValuePair or IDictionary as payload to Web Api Controller using JavaScript

In my web api controller, I am trying to post two parameters: a flat int ID and an IDictionary (or similar equivalent). [HttpPost] public void DoStuff(int id, [FromBody]IDictionary<int, int> things) { } var things = new Array(); things.push({ 1: 10 ...

Is there a method to modify the arrangement in which 3 specific HTML elements are displayed (i.e., their hierarchy in relation to one another)?

I have 3 "p" elements and I'm trying to find a way to change the order in which they load on the page using JS or CSS. Below is an example of what I've attempted so far. When you click on the first box labeled "about 1," it opens up and displays ...

Attempting to test a Jasmine directive in Angular results in failure

After creating a simple directive that throws an error when the input is invalid, I encountered an issue with my testing. When attempting to test for the thrown error using expect().toThrow(), it succeeded as expected. However, the same result occurred w ...

React is unable to locate an import statement for Material UI components

I am facing an issue while incorporating material UI components into my React project. The error message I receive is related to an invalid import. Snippet from My Component File import React from 'react' import './middle.css' import Mi ...

Have Vue props been set to null?

Currently, I have a component within my vue.js application that looks like this: export default { props: ['forums'], methods: { increment(forum, index) { ForumService.increment(forum) .then(() => { ...

Running Windows commands from Node.js on WSL2 Ubuntu and handling escape sequences

When running the following command in the CMD shell on Windows, it executes successfully: CMD /S /C " "..\..\Program Files\Google\Chrome\Application\chrome.exe" " However, attempting to run the same comman ...

Tips for activating swf file autoplay on the mobile edition of WordPress

I recently added a swf file to my WordPress page (https://www.pacifictintlv.com/mobile). However, I have noticed that it does not seem to work properly when viewed on mobile devices. Is there a way to redirect users to the Flash download link if they do ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

Exploring the possibilities of ReactJS and the sleek design of

How can I alter the background color of a RaisedButton without having the CSS class name appear in the autogenerated div? Here is the button: <RaisedButton className="access-login" label="Acceder" type="submit"/> This is the specified CSS: .acces ...

What is the best way to use jQuery to fill a dropdown menu with options from a JSON object?

Looking to populate a dropdown box #dropdown with values from a json object stored in a JavaScript string variable. How can I access each element as value/label pairs and insert them into the dropdown? The structure of the json string is as follows: [{"n ...

Implementing jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

Move the scroll event binding from the parent element to the child element

I'm working on an HTML page with the following structure: <div class="parent"> <div class="child1"> <div class="child2"> </div> </div> </div> Currently, I have a scr ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...

The unsightly square surrounding my sprite in Three.js

I am attempting to create a beautiful "starry sky" effect using Three.js. However, I am encountering an issue where my transparent .png star sprites have a colored outline around them. Here is the sprite I am using: https://i.sstatic.net/2uylp.png This ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...