Our goal is serializing a mesh, and use JSON.stringify()
to covert it to string, and then we use SceneLoader.ImportMesh()
to load the string data re-displaying the mesh.
note:
the argumentsceneFilename
is able to be parsed by starting with “data:” following by the stringified version of the scene or a File object (default: empty string),
Github repo: GitHub - hjlld/serializing-mesh-babylonjs-es6-moudle
-
Because of all the js file inside the dist version of @babylonjs/core require an external module ‘ts-lib’, so they cannot be imported directly in browser in runtime. (But Why???) so i can’t realize it in the Playground, but i’ll give a minimum repository on Github.
-
AbstractMesh.getPhysicsImpostor()
is not defined in the classAbstractMesh
but in the filebabylon.physicsEngineComponent.ts
, which is necessary forSceneSerializer.SerializeMesh(mesh)
. So if your scene doesn’t need physics but serializing meshes, you will get an errorthis.getPhysicsImpostor is not a function
.
There is a TODO decorator in the source code, so temporarily we can do polyfill with:
// `mesh` is the mesh pending to serialize
mesh.__proto__.getPhysicsImpostor = function () {
return this.physicsImpostor;
};
- When above done, then we’ll meet the next problem:
Uncaught TypeError: Cannot read property 'plugin' of undefined
at Function.SceneLoader._loadData (sceneLoader.ts:364)
it seems like there’s no default plugin for loading a stringified data directly, because in the ES6 version, the default value of SceneLoader._registeredPlugins
is an empty object.
But according to this tutorial, the result of SceneSerializer.Serialize()
is actually the content of .babylon
file which can be loaded by the plugin babylonFileLoader
.
But which default plugin is for serialized mesh? let’s have a try:
import '@babylonjs/core/Loading/Plugins/babylonFileLoader'
then we get no errors, hoory!
=== EDIT ===
when we import stringfied data, we must not give the new mesh a name, we should always make the first argument meshNames
as an empty string.
SceneLoader.ImportMesh('', '', `data:${JSON.stringify(obj)}`, scene) //correct
SceneLoader.ImportMesh('mesh', '',`data:${JSON.stringify(obj)}`, scene) //wrong
now we finaly kick our goal!
- some other suggestions:
① many classes do not have serialize
method, and some other classes can be serialized but have no method for restoring or re-parsing to the original, it’s really rare. When we deal with web workers, or save content into IndexedDB, we really depend on the serialization feature.
② in umd mode, babylon.js is a great engine library, because it can guide the developers step by step to reach their goal. but in es6 module, developers have to looking for the right modules to import by reading the source code, which is really a puzzle slowing down the fast build. should we have a more detailed tutorial for es6 developers?