Navigating THREE.Mesh objects within a worker: Best practices

I have successfully created buildings in three.js, but I am now facing challenges due to its single-threaded nature when handling large data sets. As a solution, I decided to use a web worker to process the geometry separately and send it back to the main thread.

However, I encountered an error message that reads:

error: buildingTileProcessor.js:332 Uncaught DataCloneError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': An object could not be cloned.

After researching, I realized that the THREE.Mesh objects are too complex for the data clone algorithm. I need help figuring out how to send back these Mesh objects without errors.

Has anyone else experienced this issue before? Any suggestions on how to resolve it or insights on using Parallel.js, another library utilizing web workers?

Answer №1

Sending certain objects from a WebWorker scope/thread back to the main scope/thread is not allowed. More information on this can be found here:

aMessage

To deliver an object to the worker, it should be in the data field in the event received by the DedicatedWorkerGlobalScope.onmessage handler. This object can be any value or JavaScript object handled by the structured clone algorithm, even those with cyclical references.

transferList (Optional)

An optional array of Transferable objects that transfers ownership. Once transferred, the object becomes unusable (neutered) where it originated and can only be accessed by the receiving worker.

Only MessagePort and ArrayBuffer objects are transferable. ·Null` is not a valid value for transferList.

Read more about the structured clone algorithm here:

In the section on Things that don't work with structured clones, you'll find the explanation for your error.

I encountered a similar issue and decided against using web workers. If you have a workaround, I'd love to hear about it.


Note: One potential solution is creating a THREE.BufferGeometry and then sending the buffer attributes as transferable objects back to the main thread. It's technically feasible but requires custom code to implement.

UPDATE

Responding to your comment, here's an update:

If you convert a THREE.Geometry to a THREE.BufferGeometry using the fromGeometry method, you cannot directly send the buffer geometry as transferable. However, you can send the buffer arrays from the buffer attributes (THREE.BufferAttribute) as transferables and reconstruct the buffer attributes and geometry in the main thread using the buffer arrays received from your worker.

Although untested, this approach should be theoretically possible. The performance improvement remains uncertain, but it's worth experimenting with.

var bufferGeometry = THREE.BufferGeometry().fromGeometry( geometry );    

// Access buffer attributes holding buffer arrays.
// Collect them by name (ie. color, normal, position, etc )
var attribute = bufferGeometry.getAttribute( name );
var bufferArray = attribute.array;

// Index attribute access:
var indexAttribute = bufferGeometry.getIndex();
var indexArray = indexAttribute.array;

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

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 ...

Retrieve JSON data from an external link and showcase it within a div, unfortunately encountering an issue with the functionality

Encountering the error message "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access" Check out the plunker link for more information: http ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

Loop variables undergoing change

I am currently working on a loop that fetches data from an API and then processes it to populate a simple array with the retrieved information. Promise.all(promises.map(obj => API.functionName(obj))).then((response) => { var index = startingDate; ...

When transitioning to the production environment, Nuxt.js fails to load images

I am currently working on developing a rather large app. Everything was running smoothly in the development environment without any errors. However, upon switching to the production environment, I started encountering numerous errors. Nuxt seems to be havi ...

Mastering the Art of Content Swapping in SPA

Hey there! I'm in the process of creating a webpage using tornado io and incorporating various graphs. To add some single page app magic, I decided to swap out content within a div like so: <div id="chartType"> Chart goes here</div> <a ...

Incorporating CSS Styles in EJS

Struggling with connecting my CSS files while using EJS. I've checked out another solution but still can't seem to get it right. Here is the code I used as a reference for my CSS file. EJS <html> <head> <meta charset="utf-8 ...

Encountering an issue... invariant.js:42 Error: A `string` value was received instead of a function for the `onClick` listener

Currently, I am working on creating a form that allows users to build quizzes without any restrictions on the number of questions they must include. To achieve this, I plan to add an "add question" button at the bottom of the quiz form, allowing users to d ...

Clicking on ajax will disable the submit button and then re-enable it

Hey everyone, I've got this function that's working great but I'm encountering a small problem. $(document).ready(function(){ $("input[type='submit']").attr("disabled", false); $("form").submit(function(){ $("input[type='s ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

Nodejs is utilized to alter the data format as it is transferred from the client to the server

I'm encountering an issue with transmitting my data to the server using Node.js. I have a feeling that there are discussions on this topic already, but I'm unsure of what to search for to locate them... Here's a brief overview of my applica ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Vue.js - The table updates successfully, however, the data for the selected checkboxes remains unchanged

Encountered a persistent bug that is giving me some trouble. I have a table with rows that can be selected, and when a checkbox is checked, the total amount in the column should be calculated. However, whenever there is a change in the table data through ...

Relaying event arguments from client-side JavaScript to server-side code-behind through ClientScript.GetPostBackEventReference

My goal is to initiate a postback using JavaScript and also pass event arguments. While I have managed to trigger the postback successfully, I am facing issues with passing event args. The function below is not functioning as expected. It seems to be enco ...

The Javascript eval method throws a ReferenceError when the variable is not defined

In my constructor, I was trying to create a dynamic variable from a string. Everything was working smoothly until I suddenly encountered this error out of nowhere. I didn't make any changes that could potentially disrupt the system, and the variables ...

Install the following packages using npm: tailwindcss, postcss, autoprefixer, error, and next

npm ERR! code ERESOLVE npm ERR! ERESOLVE could not find a solution to the problem npm ERR! npm ERR! While trying to resolve: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/react npm ERR! requires react@">=16.8 ...

Using ASP.NET to retrieve data with AJAX and pass parameters to a web method

Looking for assistance with a web method I have created: [WebMethod] [ScriptMethod(UseHttpGet = true)] public static string test(string Name, int? Age) { return "returned value"; } Below is the ajax call I am attempting: $.ajax({ type: "GET", ur ...

Access the angular controller using the radio button option

I am looking to showcase data in an HTML table retrieved from an Angular controller. I have the controller set up but I am unsure about how to display the data when a radio button is selected. <div class="radio"> <label class="radio-inline" ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...