How to serialize a subset of scene

Description

Currently there is a SceneSerializer that serializes a scene to a json object, where almost all babylon-specify properties can be kept and transfered to another context.
But since both Serialize and SerializeAsync accepts only Scene as input, it’s only possible to serialize the whole scene.
There is a doNotSerialize prop in many objects in scene, but instead of setting which objects not to serialize, it would be better to have an api that serializes only what the user wants.
After a quick look into the source code, maybe it’s possible for SceneSerializer to have a Serialize(IAssetContainer) or something similar, where users can collect what they want to a IAssetContainer and serialize it. The remaining scene-specified code will only run if the input is a Scene.

Alternatives

  • Polyfill or extend IAssetContainer to have props and methods required in Serialize, and cast to any.
Example

export interface ISubsetScene extends IAssetContainer {
    getEngine(): AbstractEngine;
    clearColor: Color3;
    ambientColor: Color3;
    gravity: Color3;
    fogColor: Color3;
    isPhysicsEnabled(): false;
    getPhysicsEngine(): any;
    activeCamera: {
        id: null;
    };
    getGeometries(): Geometry[];
    actionManager: null | {
        serialize(_str: string): null;
    }
    _serializableComponents: [];
    spriteManagers: null;
    [misc: string]: boolean | void;
}

export class SubsetScene extends AbstractAssetContainer implements ISubsetScene {

    _serializableComponents: [];
    actionManager: { serialize(_str: string): null } | null;
    activeCamera: { id: null };
    ambientColor: Color3;
    clearColor: Color3;
    fogColor: Color3;
    gravity: Color3;
    spriteManagers: null;

    getEngine(): AbstractEngine {
        return this.meshes[0].getScene().getEngine();
    }

    getGeometries(): Geometry[] {
        return Array.from(new Set(this.meshes.map(e=>e.geometry).filter(Boolean)));
    }

    getPhysicsEngine(): any {
        return null;
    }

    isPhysicsEnabled(): false {
        return false;
    }

}
  • Manually collect and set what users do not want to serialize, set doNotSerialize, and revert it back to the original value (not always true) after serialization.
  • Serialize the whole scene, costing a lot of extra compute and memory, and cleanup the serialized json.

cc @alexchuber

I like the idea of serializing AssetContainer and would be happy to review a PR or discuss the implementation further :slight_smile: But, before we get into that, what are your thoughts on the current SceneSerializer.SerializeMesh API?

1 Like

It’s good. Multiple nodes with hierarchy, material, geometry, skeleton, but it lacks morphTargetManagers, animationGroups, and particleSystems.