The vertices in Three.js BufferGeometry refuse to update

As I strive to connect grid tiles with real elevation data from IndexedDB, I encounter a challenge due to the imperfect data resolution on the STRM elevation causing discrepancies at the edges between the tiles. To address this issue, my goal is to average out all the grid edges between the connecting vertices in order to create a seamless terrain.

Interestingly, when I directly input the code into the console within the scene, it functions correctly. However, when embedded solely in the codebase, it does not yield the desired outcome. It's worth noting that the passed sceneRef parameter is valid and correctly utilized throughout the rest of the codebase.

The grid comprises 3 x 3 tiles, with the current center tile positioned at 1,1 within the range of 0,0 - 2,2.

function connectTiles(currGridKey, sceneRef){
console.log("connectTiles");
console.log("currGridKey");
// Current Tile Connection
for (var lat = 0; lat < currGridKey[0]+2; lat++) {
    for (var long = 0; long < currGridKey[1]+2; long++) {
        const currentTile = sceneRef.getObjectByName(`${lat}-${long}`); 
        // Current Grid Tile Per Loop
        if (currentTile) {
            const currentTileVerts = currentTile.geometry.attributes.position.array,
                  latPlusTile = sceneRef.getObjectByName(`${lat}-${long+1}`),
                  longPlusTile = sceneRef.getObjectByName(`${lat+1}-${long}`);

            // Connect Latitudinally
            if (latPlusTile) {
                const latPlusTileVerts = latPlusTile.geometry.attributes.position.array;
                for (var z = 0; z < currentTileVerts.length; z+=27) {
                    const newVertHeight = (currentTileVerts[z] + latPlusTileVerts[z]) / 2;
                    latPlusTileVerts[z] = newVertHeight;
                    currentTileVerts[z] = newVertHeight;
                }
                latPlusTile.geometry.attributes.position.needsUpdate = true;
                currentTile.geometry.attributes.position.needsUpdate = true;
            }
            // Connection Longitudinally
            if (longPlusTile) {
                const longPlusTileVerts = longPlusTile.geometry.attributes.position.array;
                for (var x = 0; x < currentTileVerts.length; x+=3) {
                    const newVertHeight = (currentTileVerts[x] + longPlusTileVerts[x]) / 2;
                    longPlusTileVerts[x] = newVertHeight;
                    currentTileVerts[x] = newVertHeight;
                }
                longPlusTile.geometry.attributes.position.needsUpdate = true;
                currentTile.geometry.attributes.position.needsUpdate = true;
            }       
        }
    }
}

Answer №1

In the event that all values within the array are indeed being updated but not being uploaded to the GPU, it may be worth considering a different approach. Rather than directly modifying the value inside geometry.attributes.position, experimenting with the .setAttribute() method could yield better results according to the documentation. The documentation indicates that utilizing .setAttribute() and .getAttribute() is more advisable than direct access due to its own internal storage mechanism.

const latPlusTileVerts = latPlusTile.geometry.getAttribute("position").array;
// ... Loops
latPlusTile.geometry.getAttribute("position").needsUpdate = true;

// Alternatively, consider creating a new attribute...
// in case updating the existing one proves unsuccessful 
const posAttrib = new THREE.BufferAttribute(latPlusTileVerts, 3);
latPlusTile.geometry.setAttribute("position", posAttrib);

Answer №2

Just wanted to share my experience here in case it helps someone else who might be facing a similar issue. I recently came across the same problem and after referring to the Three.js documentation, I discovered that these two lines were crucial:

geometry.computeBoundingBox();
geometry.computeBoundingSphere();

It turned out that in my situation, frustum culling was causing my newly added geometry to disappear.

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

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...

Is it possible to utilize AJAX and cross-domain JSONP to determine if a URL is accessible?

I am currently utilizing JQuery to retrieve data from a URL and display it on my page asynchronously. The URL is sourced from a different domain, so I have implemented JSONP to acquire the necessary information. So far, this method has been functioning pro ...

Is there a method to hide an HTML form completely?

Is there a way to quickly hide an HTML form from a webpage once the submit button is clicked and replace it with the result of a .php file in the most efficient manner possible, with minimal code? ...

Updating interval time based on an external variable with jQuery

I have developed a JavaScript script where pressing a button triggers the continuous playback of an audio file. The audio, which is a 'beep' sound, serves as an alarm. The frequency at which the beep plays is determined by a setting located on a ...

I wonder, what is Mongoose's isModified function actually verifying?

I have come across this specific isModified check frequently while researching, and even after reviewing Mongoose's documentation, I still struggle to grasp its precise purpose or significance. Initially, I considered the possibility that the check w ...

What distinguishes between employing a div versus a canvas element for a three.js display?

While it is commonly believed that three.js requires the HTML5 <canvas> element, I have found success in using a simple <div> by assigning height and width properties and then adding the WebGLRenderer.domElement as its child within the HTML str ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Insert a numerical value into a list to make a series of numbers whole

I currently have an array of objects that looks like this: var arr = [ { "code": "10", }, { "code": "14", } ] My goal is to expand this array to contain 5 elements. The numbers should ran ...

Turn off the div element until a radio button option is selected, then activate it

Is there a way to disable a div and then activate it only after selecting a radio button option? I know how to hide and show the div when an option is selected, but using the hidden property is not ideal. Can someone suggest a possible solution? <div ...

Executing php class method through ajax with jQuery without requiring a php handler file

How can I trigger a PHP class method using AJAX with jQuery without the need for a separate PHP handler file? Here is my PHP Class animal.php:- <?php class animal { function getName() { return "lion"; } } ?> jQuery code snippet:- ...

What is the purpose of encasing the routes within the <Switch> element in react-router, when they seem to function perfectly fine without it

Currently utilizing react-router-dom version 5.2.0. As a practice, I typically enclose all my Route components within a Switch component. For instance: const MyRoutes = () => ( <Switch> <Route path='/route1' exact ...

Is Performance Enhanced by Exporting Meshes in Three.js?

Currently, I am working on a Three.js project and have noticed some performance lag in certain areas. The most significant lag occurs when rendering the text Meshes that I have created as follows: var text1Geo = new THREE.TextGeometry("Hello", {font: font ...

Retrieving multiple checkbox values using JavaScript

When submitting a form using ajax and jquery, I encountered an issue with multiple checkboxes that are not posting values to the database. Here is the relevant HTML/PHP code snippet: while($row = mysql_fetch_assoc( $result )) { echo '<input ...

Unable to append form data in React file upload process

const [image, setImage] = useState({ preview: "", file: "" }); const handleChange = (e) => { e.preventDefault(); if (e.target.files.length) { setImage({ preview: URL.createObjectURL(e.target ...

What is the best way to iterate through an array of images and upload them individually, ensuring that they do not have duplicate names

In my current code snippet, I am working with an array of images called images and uploading each image within that array. Everything seems to be working correctly, but I am encountering a minor issue where all the uploaded images end up having the same na ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Tips for preventing users from entering special characters into input fields

How can I prevent users from entering the # character into an HTML input field? I attempted to use the pattern attribute, but it does not seem to be effective. I included this pattern in my input element: pattern="[^-#]+" I expected that this would disa ...

What is the best way to implement an event listener for every button in a table row outcome?

I have a Rails application where I am populating a table using an @results variable, with each row representing a @result. My goal is to have buttons associated with each @result, and I'm attempting to use a JavaScript event listener for each button a ...