What is the most efficient way to refresh a geometry's topology in ThreeJS?

Is there a way to efficiently update the vertices and faces of my geometry without creating new typed arrays and generating garbage for the JavaScript Garbage Collector? I currently use BufferedGeometry to create my geometry, but when updating vertex coordinates with verticesNeedUpdate, the faces are not updated. This process is called frequently (20-50 times per second) and can be taxing on the browser. How can I optimize this process to minimize memory allocation? Please refer to the update() method below for context.

function WGeometry77(verts, faces) {
    THREE.Geometry.call( this );
    this.type = 'WGeometry77';
    this.parameters = {};
    // Initially create the mesh the easy way, by copying from a BufferGeometry
    this.fromBufferGeometry( new MyBufferGeometry77( verts, faces ) ); 
};

WGeometry77.prototype = Object.create( THREE.Geometry.prototype );
WGeometry77.prototype.constructor = WGeometry77;

WGeometry77.prototype.update = function(verts, faces) {
    var geom = this;
    var nl = Math.min(geom.vertices.length, verts.length/3);
    for ( var vi = 0; vi < nl; vi ++ ) {
        geom.vertices[ vi ].x = verts[vi*3+0];
        geom.vertices[ vi ].y = verts[vi*3+1];
        geom.vertices[ vi ].z = verts[vi*3+2];
    }
    var nf = Math.min(geom.faces.length, faces.length/3);
    for ( var fi = 0; fi < nf; fi++ ) {
        geom.faces[ fi ].a = faces[fi*3+0];
        geom.faces[ fi ].b= faces[fi*3+1];
        geom.faces[ fi ].c = faces[fi*3+2];
    }
    geom.verticesNeedUpdate = true;  // Does not update the geom.faces
}

PS. My code is written in Emscripten, which does something like this:

var verts = Module.HEAPF32.subarray(verts_address/_FLOAT_SIZE, verts_address/_FLOAT_SIZE + 3*nverts);

I am looking to create dynamic geometries (such as ones generated using Marching Cubes) that require frequent updates to both topology and vertex information. Is there a ThreeJS class that suits these requirements, or should a new class like UpdatableBufferedGeometry be developed?

Answer №1

If you need to update a THREE.BufferGeometry after it has already been rendered, follow this pattern:

geometry.attributes.position.setXYZ( index, x, y, z );

geometry.attributes.position.needsUpdate = true;

For indexed BufferGeometry, simply modify the index array like this:

geometry.index.array[ index ] = value;

geometry.index.needsUpdate = true;

Keep in mind that buffers cannot be resized, only their contents can be changed. To handle this, consider pre-allocating larger arrays and using

geometry.setDrawRange( 0, numVertices );

This applies for three.js version r.78.

Answer №2

To achieve optimal performance, it is recommended to utilize a BufferGeometry rather than a traditional Geometry.

For guidance on implementing this approach, you can refer to the code provided in the following example:

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

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

The rationale behind organizing analogous variables into groups

Currently, I am grappling with determining the optimal logic for grouping parameters within a specified tolerance level. Let me illustrate this with an example... Task1: parameter1=140 Task2: parameter1=137 Task3: parameter1=142 Task4: parameter1=139 Task ...

Leveraging the navigator geolocation feature in tandem with reactors

Struggling to save geolocation variables position.coords.lat/long in a global scope. Check out this code: var GeoLoco = React.createClass({ lat: 0, long: 0, handler: function(position) { ...

Registration window restriction

I have implemented a sign-up modal on a Bootstrap website and am looking to restrict the number of times visitors see it to twice per session instead of on every page, as well as hiding it once a visitor has subscribed. The modal will appear after 5 second ...

Efficiently passing multiple files with Rails using jQuery/Ajax and API

I'm currently utilizing the FileStack API along with the filepicker gem in my project. The JavaScript snippet provided below is responsible for parsing a JSON response from the browser and forwarding it to the create action of the Attachment controlle ...

Converting a JSON array with two dimensions to PHP

My JSON encoded array originated from a 2D PHP string array and appears as follows: [ [ "a1", "a2", "a3", "a4" ], [ "b1", "b2", "b3", "b4" ], [ "c1", "c2", "c3", "c4" ] ] The validity of this array has been ...

The p5js function pixelDensity() does not provide improved resolution on retina screens

Currently, I am working on a project that involves generating collages from sets of photos. This process includes averaging the pixels' colors of the images and then using that averaged color to plot points on the canvas. However, when I zoom in on re ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

How can you selectively add a CSS class during the iteration of a VueJs object?

Using Vuetify components: <v-layout row wrap> <v-flex xs2 v-for="(month, key) in months" :key ="key"> <router-link class = "decoration" :to="month.target">{{(month.month)}}</router-link> </v-flex> The "v ...

Trouble getting CSS and JavaScript to function properly with HTTPS?

It seems that the css and js files are functioning properly on , but not on . As a novice in web design and javascript, I am struggling to find a solution to this issue. Trying to link the CSS file with "//isdhh.org/css/style.css" has not resolved the pr ...

How to retrieve JSON data from ASP.NET code-behind file and pass it to JavaScript

I'm facing an issue with my webstatic method that converts my dataset into JSON. I want to retrieve this JSON in my JavaScript file, but unfortunately nothing is appearing in my div. As a newcomer to ASP.NET and JSON, I must be doing something wrong h ...

Is there a way to smoothly transition a FlatList while the keyboard is open?

At the moment, the appearance and animation of my messaging screen are as follows: However, I'm eager to enhance my messaging initial animation to lift up my flatlist like this (opens with scrolling): This is the code for the screen: // Code goes he ...

What is the best way to replicate the Ctrl+A action on an element using jQuery or JavaScript?

Is there a way to trigger the Ctrl+A key combination in a textarea element when a specific event occurs, without resorting to caret positioning or selecting all text separately? I'm looking for a method that simulates hitting Ctrl+A using a cross-brow ...

Is the order of return guaranteed for Ajax requests?

This particular inquiry raises the question of whether Ajax requests follow the order in which they are sent. While it appears that Ajax requests may not always return in the same order they were dispatched, the use of the TCP protocol suggests that packet ...

Implementing Content-Security-Policy for a web application embedded in an iframe

Hey there! I've got this cool webapp called myApp, developed using Spring Boot and Vaadin. It's going to be deployed on a Tomcat server at http://tomcatserver:8080/myApp Now, what I want to do is display the webapp in an iframe like this: <if ...

Is it achievable to utilize HTML tabindex for activating a function?

Currently working on an application using PhoneGap, where I encounter a complex form layout. The form consists of a text input field at the top, followed by multiple buttons and additional text inputs below. I am wondering if it is feasible to activate a ...

The import error states that the object 'useHistory' is not available for export from the module 'react-router-dom'

Struggling with importing useHistory from 'react-router-dom' and encountering the error message: import error: 'useHistory' is not exported from 'react-router-dom'. Despite searching for solutions like Attempted import error: ...

"Utilizing multiple optional parameters in Expressjs can lead to the request handler being

Hey there, I could use a fresh perspective on this issue I'm having. I am attempting to set up a request handler that can accept 0, 1, or 2 parameters like http://localhost:3000/{seed}/{size}. The parameters "seed" and "size" should both be optional. ...