WonderlandEngine

Main Wonderland Engine instance.

Controls the canvas, rendering, and JS <-> WASM communication.

Properties

Methods


Properties

._mainSceneVersion: number

Incremented every time a new main scene is loaded.


.autoHotReload: boolean

If true, automatically reloads the scene sent by the editor socket.

Note: The onHotReloadRequest emitter is notified after the scene is re-loaded.

To use custom hot-reload code, set this boolean to false and add the reloading code


.erasePrototypeOnDestroy: boolean

1.1.1+

If true, Texture, Object3D, and Component instances have their prototype erased upon destruction.

Object

engine.erasePrototypeOnDestroy = true;

const obj = engine.scene.addObject();
obj.name = 'iamalive';
console.log(obj.name); // Prints 'iamalive'

obj.destroy();
console.log(obj.name); // Throws an error

Component

Components will also be affected:

class MyComponent extends Component {
    static TypeName = 'my-component';
    static Properties = {
        alive: Property.bool(true)
    };

    start() {
        this.destroy();
        console.log(this.alive) // Throws an error
    }
}

A component is also destroyed if its ancestor gets destroyed:

class MyComponent extends Component {
    ...
    start() {
        this.object.parent.destroy();
        console.log(this.alive) // Throws an error
    }
}

Note: Native components will not be erased if destroyed via object destruction:

const mesh = obj.addComponent('mesh');
obj.destroy();
console.log(mesh.active) // Doesn't throw even if the mesh is destroyed

.i18n: I18N

Access to internationalization.


.legacyMaterialSupport: boolean

If true, the materials will be wrapped in a proxy to support pre-1.2.0 material access, i.e.,

const material = new Material(engine, 'Phong Opaque');
material.diffuseColor = [1.0, 0.0, 0.0, 1.0];

If false, property accessors will not be available and material properties should be accessed via methods, i.e.,

const PhongOpaque = engine.materials.getTemplate('Phong Opaque');
const material = new PhongOpaque();
material.setDiffuseColor([1.0, 0.0, 0.0, 1.0]);
...
const diffuse = material.getDiffuseColor();

When disabled, reading/writing to materials is slightly more efficient on the CPU.


.loadUncompressedImagesAsBitmap: boolean

If true, uncompressed images will be automatically converted to ImageBitmap before upload to the GPU.

For more information, have a look at the ImageBitmap documentation.


.onHotReloadRequest: Emitter<[string]>

Triggered when a hot reload is requested.

When using the Wonderland Editor, this will be triggered when packaging the project.

Note: When autoHotReload is true, the emitter is notified after the scene is reloaded.

To customize the hot reload behavior, set the autoHotReload to false, and use this emitter:

this.engine.onHotReloadRequest.add(async (filename: string) => {
    // This handler can be used to re-download a scene, download components,
    // fetch an API, anything!
    await this.loadMainScene(filename);
});

.onLoadingScreenEnd: RetainEmitter<void[]>

RetainEmitter signalling the end of the loading screen.

Listeners get notified when the first call to () is invoked. At this point the new scene has not become active, and none of its resources or components are initialized.

Compared to onSceneLoaded, this does not wait for all components to be fully initialized and activated. Any handler added inside (), () or () will be called immediately.

Usage:

this.engine.onLoadingScreenEnd.add(() => console.log("Wait is over!"));

.onResize: Emitter<void[]>

Emitter for canvas / main framebuffer resize events.

Usage from within a component:

this.engine.onResize.add(() => {
    const canvas = this.engine.canvas;
    console.log(`New Size: ${canvas.width}, ${canvas.height}`);
});

Note: The size of the canvas is in physical pixels, and is set via resize.


.onSceneActivated: Emitter<[Scene, Scene]>

Emitter for scene activated events.

This listener is notified with the old scene as first parameter, and the new scene as second.

This listener is notified after all resources are loaded and all components had their () as well as (if active) () and () methods called.

Usage from within a component:

this.engine.onSceneActivated.add((oldScene, newScene) => {
    console.log(`Scene switch from ${oldScene.filename} to ${newScene.filename}`);
});

.onSceneLoaded: Emitter<void[]>

Emitter for scene loaded events.

Listeners get notified when a call to () finishes. At this point all resources are loaded and all components had their () as well as (if active) () and () methods called.

Usage from within a component:

this.engine.onSceneLoaded.add(() => console.log("Scene switched!"));

Deprecated: Use onSceneActivated instead.


.arSupported: boolean

Whether AR is supported by the browser.


.audioClips: ResourceManager<AudioClip>

AudioClip resources


.autoResizeCanvas: boolean

true if the canvas is automatically resized by the engine.

.autoResizeCanvas


.canvas: HTMLCanvasElement

Canvas element that Wonderland Engine renders to.


.fonts: ResourceManager<Font>

Font resources


.graphicsApi: GraphicsApi

1.5.0+

Graphics API used for rendering.


.images: ImageLike[]

Get all uncompressed images.


.imagesPromise: Promise<ImageLike[]>

Promise that resolve once all uncompressed images are loaded.

This is equivalent to calling images, and wrapping each load listener into a promise.


.log: Logger

Engine Logger. Use it to turn on / off logging.


.materials: MaterialManager

Material resources


.meshes: MeshManager

Mesh resources


.morphTargets: ResourceManager<MorphTargets>

Morph target set resources


.onXRSessionEnd: Emitter<void[]>

Emitter for WebXR session end events.

Usage from within a component:

this.engine.onXRSessionEnd.add(() => console.log("XR session ended."));

.onXRSessionStart: Emitter<[XRSession, XRSessionMode]>

RetainEmitter for WebXR session start events.

Usage from within a component:

this.engine.onXRSessionStart.add((session, mode) => console.log(session, mode));

By default, this emitter is retained and will automatically call any callback added while a session is already started:

// XR session is already active.
this.engine.onXRSessionStart.add((session, mode) => {
    console.log(session, mode); // Triggered immediately.
});

.particleEffects: ParticleEffectManager

Particle effect resources


.physics: null | Physics

Physics manager, only available when physx is enabled in the runtime.


.pipelines: PipelineManager

Pipeline resources


.probeVolumeScenarios: ProbeVolumeScenarioManager

Probe volume scenarios resources


.runtimeVersion: Version

Retrieves the runtime version.


.scene: Scene

Currently active scene.


.textures: TextureManager

Texture resources


.vrSupported: boolean

Whether VR is supported by the browser.


.xr: null | XRSessionState

WebXR related state, null if no XR session is active.


.xrBaseLayer: null | XRProjectionLayer | XRWebGLLayer

Current WebXR base layer or null if no session active.

Deprecated: Use baseLayer on the xr object instead.


.xrFrame: null | XRFrame

Current WebXR frame or null if no session active.

Deprecated: Use frame on the xr object instead.


.xrFramebuffer: null | WebGLFramebuffer

Current WebXR framebuffer or null if no session active.

Deprecated: Use framebuffers on the xr object instead.


.xrFramebufferScaleFactor: number

WebXR framebuffer scale factor.

.xrFramebufferScaleFactor


.xrSession: null | XRSession

Current WebXR session or null if no session active.

Deprecated: Use session on the xr object instead.



Methods

.destroy() ⇒ void

1.4.6+

Destroy the engine explicitly.


.getComponentClass<T>(typename: string) ⇒ null | ComponentConstructor<T>

Retrieve the registered component from its type name.

Returns: The class if a component was registered with given name, null otherwise.

ParamTypeDescription
typenamestringThe component TypeName property
Template ParamType Definition
Textends Component<T>

.isRegistered(typeOrClass: string | ComponentConstructor<Component>) ⇒ boolean

Checks whether the given component is registered or not.

Returns: true if the component is registered, false otherwise.

ParamTypeDescription
typeOrClassstring | ComponentConstructor<Component>A string representing the component typename (e.g., 'cursor-component'), or a component class (e.g., CursorComponent).

.loadGLTF(opts: Object, progress: ProgressCallback) ⇒ Promise<PrefabGLTF>

Create a glTF scene from a URL.

Note: Loading glTF files requires enableRuntimeGltf to be checked in the editor Project Settings.

Note: This method is a wrapper around loadGLTFFromBuffer.

Returns: A new loaded PrefabGLTF.

ParamTypeDescription
optsObject
progressProgressCallbackOptional progress callback.

.loadGLTFFromBuffer(options: InMemoryLoadOptions & GLTFOptions) ⇒ PrefabGLTF | Promise<PrefabGLTF>

.loadGLTFFromBuffer(options: InMemoryLoadOptions & GLTFOptions & { async: ‘true’; }) ⇒ Promise<PrefabGLTF>

.loadGLTFFromBuffer(options: InMemoryLoadOptions & GLTFOptions & { async: ‘false’; }) ⇒ PrefabGLTF

Similar to loadGLTF, but loading is done from an ArrayBuffer.

Note: Loading glTF files requires enableRuntimeGltf to be checked in the editor Project Settings.

Returns: A new loaded PrefabGLTF.

ParamTypeDescription
optionsInMemoryLoadOptions & GLTFOptionsAn object containing the buffer and extra glTF metadata.

.loadMainScene(options: Object, progress: ProgressCallback) ⇒ Promise<Scene>

Load the scene from a URL, as the main scene of a new Scene.

Usage

// The method returns the main scene
const scene = await engine.loadMainScene();

Destruction

Loading a new main scene entirely resets the state of the engine, and destroys:

  • All loaded scenes, prefabs, and gltf files
  • Meshes
  • Textures
  • Materials

Note: This method can only load Wonderland Engine .bin files.

Returns: The main scene of the new Scene.

ParamTypeDescription
optionsObjectThe URL pointing to the scene to load or an object holding additional loading options.
progressProgressCallbackOptional progress callback. When setting a custom callback, you need to manually call setLoadingProgress to get progress updates in the loading screen.

.loadMainSceneFromBuffer(options: InMemoryLoadOptions & ActivateOptions) ⇒ Promise<Scene>

Similar to loadMainScene, but loading is done from an ArrayBuffer.

Returns: The main scene of the new Scene.

ParamTypeDescription
optionsInMemoryLoadOptions & ActivateOptionsAn object containing the buffer and extra metadata.

.loadPrefab(options: LoadOptions<{ _ }>, progress: ProgressCallback) ⇒ Promise<Prefab>

Load a Prefab from a URL.

Usage

const prefab = await engine.loadPrefab('Prefab.bin');

Note: This method can only load Wonderland Engine .bin files.

Note: This method is a wrapper around loadPrefabFromBuffer.

Returns: The loaded Prefab.

ParamTypeDescription
optionsLoadOptions<{ _ }>
progressProgressCallbackOptional progress callback.

.loadPrefabFromBuffer(options: InMemoryLoadOptions) ⇒ Prefab

Similar to loadPrefab, but loading is done from an ArrayBuffer.

Returns: A new loaded Prefab.

ParamTypeDescription
optionsInMemoryLoadOptionsAn object containing the buffer and extra metadata.

.loadScene(options: LoadOptions<{ _ }>, progress: ProgressCallback) ⇒ Promise<Scene>

Load a scene from a URL.

At the opposite of loadMainScene, the scene loaded will be added to the list of existing scenes, and its resources will be made available for other scenes/prefabs/gltf to use.

Resources Sharing

Upon loading, the scene resources are added in the engine, and references to those resources are updated.

It’s impossible for a scene loaded with this method to import pipelines. Thus, the loaded scene will reference existing pipelines in the main scene, based on their names.

Usage

const scene = await engine.loadScene('Scene.bin');

Note: This method can only load Wonderland Engine .bin files.

Returns: A new loaded Scene.

ParamTypeDescription
optionsLoadOptions<{ _ }>The URL pointing to the scene to load or an object holding additional loading options.
progressProgressCallbackOptional progress callback.

.loadSceneFromBuffer(options: InMemoryLoadOptions) ⇒ Scene

Similar to loadScene, but loading is done from an ArrayBuffer.

Throws: If the scene is streamable.

Returns: A new loaded Scene.

ParamTypeDescription
optionsInMemoryLoadOptionsAn object containing the buffer and extra metadata.

.nextFrame(fixedDelta: number) ⇒ void

Run the next frame.

Note: The engine automatically schedules next frames. You should only use this method for testing.

ParamTypeDescription
fixedDeltanumberThe elapsed time between this frame and the previous one.

.offerXRSession(mode: XRSessionMode, features: string[], optionalFeatures: string[]) ⇒ Promise<XRSession>

1.1.5+

Offer an XR session.

Adds an interactive UI element to the browser interface to start an XR session. Browser support is optional, so it’s advised to still allow requesting a session with a UI element on the website itself.

Note: Please use this call instead of directly calling navigator.xr.offerSession(). Wonderland Engine requires to be aware that a session is started, and this is done through this call.

Returns: A promise resolving with the XRSession, a string error message otherwise.

ParamTypeDescription
modeXRSessionModeThe XR mode.
featuresstring[]An array of required features, e.g., ['local-floor', 'hit-test'].
optionalFeaturesstring[]An array of optional features, e.g., ['bounded-floor', 'depth-sensing'].

.registerBundle(url: string, nocache: boolean) ⇒ Promise<void>

Register a component bundle

The module must be of the form:

export default function(engine) {
    engine.registerComponent(MyComponent);
    ...
}

Alternatively, you can manually register a component bundle:

const registerBundle = (await import(url)).default;
registerBundle(engine);
ParamTypeDescription
urlstringThe URL of the module to register.
nocachebooleanIf true, force browser to re-download the file.

.registerComponent(…classes: ComponentConstructor<Component>[][]) ⇒ void

1.0.0+

Register a custom JavaScript component type.

You can register a component directly using a class inheriting from Component:

import { Component, Type } from '@wonderlandengine/api';

export class MyComponent extends Component {
    static TypeName = 'my-component';
    static Properties = {
        myParam: {type: Type.Float, default: 42.0},
    };
    init() {}
    start() {}
    update(dt) {}
    onActivate() {}
    onDeactivate() {}
    onDestroy() {}
});

// Here, we assume we have an engine already instantiated.
// In general, the registration occurs in the `index.js` file in your
// final application.
engine.registerComponent(MyComponent);
ParamTypeDescription
classesComponentConstructor<Component>[]Custom component(s) extending Component.

.requestXRSession(mode: XRSessionMode, features: string[], optionalFeatures: string[]) ⇒ Promise<XRSession>

Request an XR session.

Note: Please use this call instead of directly calling navigator.xr.requestSession(). Wonderland Engine requires to be aware that a session is started, and this is done through this call.

Returns: A promise resolving with the XRSession, a string error message otherwise.

ParamTypeDescription
modeXRSessionModeThe XR mode.
featuresstring[]An array of required features, e.g., ['local-floor', 'hit-test'].
optionalFeaturesstring[]An array of optional features, e.g., ['bounded-floor', 'depth-sensing'].

.resize(width: number, height: number, devicePixelRatio: number) ⇒ void

Resize the canvas and the rendering context.

Note: The width and height parameters will be scaled by the devicePixelRatio value. By default, the pixel ratio used is window.devicePixelRatio.

ParamTypeDescription
widthnumberThe width, in CSS pixels.
heightnumberThe height, in CSS pixels.
devicePixelRationumberThe pixel ratio factor.

.setLoadingProgress(percentage: number) ⇒ void

1.2.1+

Update the loading screen progress bar.

ParamTypeDescription
percentagenumber

.start() ⇒ void

Start the engine if it’s not already running.

When using the loadRuntime function, this method is called automatically.


.switchTo(scene: Scene, opts: ActivateOptions) ⇒ Promise<void>

1.2.0+

Switch the current active scene.

Once active, the scene will be updated and rendered on the canvas.

The currently active scene is accessed via scene:

import {Component} from '@wonderlandengine/api';

class MyComponent extends Component{
    start() {
        console.log(this.scene === this.engine.scene); // Prints `true`
    }
}

Note: This method will throw if the scene isn’t activatable.

Component Lifecycle

Marking a scene as active will:

  • Call onDeactivate for all active components of the previous scene
  • Call onActivate for all active components of the new scene

Usage

const scene = await engine.loadScene('Scene.bin');
engine.switchTo(scene);

Returns: A promise that resolves once the scene is ready.

ParamTypeDescription
sceneScene
optsActivateOptions

.toString() ⇒ string


.wrapObject(objectId: number) ⇒ Object3D

Wrap an object ID using Object.

Note: This method performs caching and will return the same instance on subsequent calls.

Returns: The object

Deprecated: Use wrap instead.

ParamTypeDescription
objectIdnumberID of the object to create.