Web Worker and Vector3

More of a PSA than a question. Comlink does an excellent job of helping me interact with my web worker. BUT! It does not work perfectly with Babylon. For some reason it keeps serializing my Vector3s and then my Vector3 methods throw errors. So far I have only had this issue with Vector3. Anyone seen this before or know why this might happen?

Edit: Upon further investigation, this is an issue with web workers in general. If I try to pass a Vector3 using postMessage I get the same result. Web workers serialize all objects when they pass them back or forth and then deserialize them on the other side. This works fine for everything I have seen so far, except Vector3.

See it in action here: https://playground.babylonjs.com/#6MIXV3#2

What are we supposed to see?

I have no error and this output in the console:
image

That’s in Chrome and Firefox.

Look again. Drop those arrows down and you will see one the one labeled “e” is a Vector3 with all of its properties and methods, while the other is just a generic object.

Edit: I updated the example to make the issue clearer https://playground.babylonjs.com/#6MIXV3#2

That’s because the postMessage function doesn’t deep clone the entire structure(prototypes etc).
It only sends a simple object with x,y and z values. Sending the entire class would would create crazy overhead, and wouldn’t even be straightforward. You have to create an actual vector in the worker as well. Something like this:
var vec = new BABYLON.Vector3().copyFrom(e.data);

1 Like

I’m probably just using Comlink wrong then. It handles all of the converting back and forth for everything else in my worker and I’m not doing any manual serialization/deserialization. There’s just a couple places where these Vector3 had me stumped. Your solution works though, and it’s what I ended up doing anyway. Thanks for checking it out.

1 Like