Combining meshes in Three.js while preserving individual materials

I've been tackling a visualization project on a web server, and while I've achieved the desired look and functionality, the performance is not up to par. The project involves a large grid that models a space, with individual cubes displayed in different colors to indicate the likelihood of an object's presence in that area. The colors need to change dynamically as more data is received. Below is the current code for the project (named VFF.js):

//code here

I've experimented with various methods to improve performance, such as reducing the number of materials used and attempting to merge the cube meshes. While merging meshes significantly improved speed, it resulted in a single material for all cubes, which is not suitable. I also explored MeshFaceMaterial but was unsure of its compatibility with merged meshes. Any suggestions or alternative approaches to enhance performance would be greatly appreciated!

To test the project, I'm running it on a simple HTML file:

<html> 
<head> 
<title>VFF Vizualization Test</title> 
</head>

<body> 
<canvas id="VFFCanvas" width="640" height="480"></canvas>
<script src="three.min.js"></script> 
<script src="VFF.js"></script>
</body> 
</html>

Answer №1

I have identified a significant issue that is affecting performance: the scene is being constantly modified by adding and removing objects in the render() function. It would be more efficient to create all necessary objects upfront and simply toggle their visibility on and off when needed, rather than constantly adding and removing them.

Additionally, there is a problem unrelated to performance in which a directional light is being moved. Directional lights do not have a position, but they do have an orientation that should be adjusted instead.

Lastly, it is crucial to optimize the render loop as much as possible. Minimizing unnecessary changes to the geometry is essential as each change must be sent to the GPU every frame, leading to increased cost. Keeping the render() loop streamlined and efficient is key.

Another improvement that could be made is to implement a method for creating materials based on color. This way, if a color already exists, it can be reused, saving resources. Small optimizations like this can contribute to overall performance improvements.

Answer №2

If you're searching for a method to merge meshes with multiple materials, here is a function that can help. This function merges meshes and re-indexes materials, ensuring everything works smoothly (tested on r71).

 function combineMeshes (meshArray) {
    var mergedGeometry = new THREE.Geometry(),
        materialList = [],
        currentMaterial,
        materialIndex = 0,
        newIndex = 0;

    for (var i = 0; i < meshArray.length; i++) {
        currentMaterial = meshArray[i];

        if (currentMaterial.material.materials) {
            for (var j = 0; j < currentMaterial.material.materials.length; j++) {
                materialList[materialIndex++] = currentMaterial.material.materials[j];
            }
        } else if (currentMaterial.material) {
            materialList[materialIndex++] = currentMaterial.material;
        }
        mergedGeometry.merge(currentMaterial.geometry, currentMaterial.matrix, newIndex);
        newIndex = materialIndex;
    }
    return new THREE.Mesh(mergedGeometry, new THREE.MeshFaceMaterial(materialList));
};

This function can significantly increase the performance of scenes with numerous static objects. Keep in mind that once merged, the objects will act as a single large mesh.

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

Tips on implementing multiple consecutive setState calls in ReactJS

Recently, I discovered that setState is an async call. I'm facing an issue where I need to utilize the updated result from setState immediately after setting it, but due to its async nature, I end up getting the old state value. While researching for ...

Attempting to include a new choice on a drop-down menu and ensure its visibility within the drop-down menu

On my journey into the world of web development, I am facing a challenge with adding an option to a dropdown list. Despite pressing the add button to insert "Pasta" as a new option, it is not showing up in the list immediately. However, selecting all optio ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

When I trigger a function by clicking, I also set a timeout of 1 second. Is it possible to deactivate this timeout from within the function itself?

One button triggers a function with a timeout that repeats itself upon clicking. Here's the code snippet: function chooseNum() { let timeout = setTimeout(chooseNum, 1000); } To disable this repeating function, I attempted another function like so ...

Ways to insert script tag in a React/JSX document?

private get mouseGestureSettingView() { const {selectedMenu} = this.state; return ( selectedMenu == 2 ? <script src="../../assets/js/extensions/mouse-gesture/options.js"></script> <div className={styles.settingForm}& ...

Is there a way to determine which option is currently highlighted in Internet Explorer before it is actually chosen?

Despite the fact that IE does not support mouse events on <option> elements, it does highlight the option under the mouse cursor when you open a dropdown list. Is there a way in JavaScript to capture this highlighted option as the user moves the mous ...

Initiate an Ajax request from a hyperlink

Is it possible to trigger an Ajax request from a hyperlink? I am interested in updating the inner html of a div element upon clicking on a hyperlink through JavaScript. ...

Directive not working on Mozilla Firefox

Currently, I have a directive set up to display an image as a background image. This works perfectly fine in Chrome and Safari, but for some reason, it doesn't seem to be functioning properly in Firefox as the background images are not showing up. Aft ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Using Three.js to create smooth radius transitions in RingGeometry

Is there a way to animate the innerRadius property of THREE.RingGeometry() in three.js by incorporating tween.js? I am looking to modify the geometry itself rather than simply scaling the ring. ...

Develop an innovative showcase page showcasing 151 individual profiles with React Router

I am new to using React Router and feeling a bit confused about how to proceed. On my homepage, I have 151 unique monster thumbnails. When a user clicks on a thumbnail, they should be directed to the specific monster's 'show page'. Currently ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

Providing parameters to a dynamic component within NextJS

I am dynamically importing a map component using Next.js and I need to pass data to it through props. const MapWithNoSSR = dynamic(() => import("../Map"), { ssr: false, loading: () => <p>...</p>, }); Can anyone sugges ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log. Here is the code snippet: this.logicItem.$promise.then( ...

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...