Engine API Reference - v2.23.0-beta.17
    Preparing search index...

    Class Asset<K>

    An Asset is the engine's record of a single resource: a texture, a material, a glTF container, a sound, a script and so on. Assets live in the application's AssetRegistry at AppBase#assets, which loads them on demand.

    An asset has five parts:

    • type selects the ResourceHandler that loads it and the type of resource.
    • file names the file that holds the data, when there is one.
    • data carries JSON that either is the resource, as for materials, or describes how to process the file, as for texture and model mappings.
    • options carries handler-specific load options.
    • resource holds the loaded object, such as a Texture. resources holds every object the handler produced when there is more than one, such as a cube map and its prefiltered levels.

    Loading is driven by the registry: call AssetRegistry#load, or set preload so the asset loads when added. Wait for the result with ready or listen for the load and error events. unload releases the resource.

    The type string also types the resource: new Asset('brick', 'texture', file) creates an Asset<'texture'> whose resource is a Texture once loaded, and app.assets.find('brick', 'texture') returns one. See AssetMap for the built-in types and for adding application-defined ones. An asset whose type is only known as a string has a resource of type unknown.

    const asset = new Asset('brick', 'texture', { url: 'textures/brick.png' });
    app.assets.add(asset);
    app.assets.load(asset);
    asset.ready((asset) => {
    material.diffuseMap = asset.resource;
    });

    Type Parameters

    Hierarchy (View Summary)

    Index
    • Create a new Asset record. Add it to the AssetRegistry with AssetRegistry#add so the application can find and load it.

      Type Parameters

      Parameters

      • name: string

        A non-unique but human-readable name which can be later used to retrieve the asset.

      • type: K

        The type of asset (an AssetType), which selects the resource handler and the type of Asset#resource. The types a developer commonly creates are:

        Types that the engine creates itself while loading, such as render or scene, are omitted here; every built-in type is listed in AssetMap. Any other string is accepted for an application-defined handler; see AssetMap for typing its resource.

      • Optionalfile: {
            contents?: ArrayBuffer;
            filename?: string;
            hash?: string;
            size?: number;
            url?: string;
        }

        Details about the file the asset is made from. At the least must contain the 'url' field. For assets that don't contain file data use null.

        • Optionalcontents?: ArrayBuffer

          Optional file contents. This is faster than wrapping the data in a (base64 encoded) blob. Currently only used by container assets.

        • Optionalfilename?: string

          The filename of the resource file or null if no filename was set (e.g from using AssetRegistry#loadFromUrl).

        • Optionalhash?: string

          The MD5 hash of the resource file data and the Asset data field or null if hash was set (e.g from using AssetRegistry#loadFromUrl).

        • Optionalsize?: number

          The size of the resource file or null if no size was set (e.g. from using AssetRegistry#loadFromUrl).

        • Optionalurl?: string

          The URL of the resource file that contains the asset data.

      • Optionaldata: any = {}

        JSON object or string with additional data about the asset. (e.g. for texture and model assets) or contains the asset data itself (e.g. in the case of materials).

      • Optionaloptions: { crossOrigin?: "anonymous" | "use-credentials" | null } = {}

        The asset handler options. For container options see ContainerHandler.

      Returns Asset<K>

      // an Asset<'texture'>: once loaded, asset.resource is a Texture
      const asset = new Asset("a texture", "texture", {
      url: "http://example.com/my/assets/here/texture.png"
      });
    id: number = ...

    The asset id.

    loaded: boolean = false

    True if the asset has finished attempting to load the resource. It is not guaranteed that the resources are available as there could have been a network error.

    loading: boolean = false

    True if the resource is currently being loaded.

    options: any = {}

    Optional JSON data that contains the asset handler options.

    registry: AssetRegistry | null = null

    The asset registry that this Asset belongs to.

    tags: Tags = ...

    Asset tags. Enables finding of assets by tags using the AssetRegistry#findByTag method.

    type: K

    The type of the asset: one of the AssetType names, or the name of an application-defined resource handler. See AssetMap.

    • get data(): any

      Gets optional asset JSON data.

      Returns any

    • set data(value: any): void

      Sets optional asset JSON data. This contains either the complete resource data (such as in the case of a material) or additional data (such as in the case of a model which contains mappings from mesh to material).

      Parameters

      • value: any

      Returns void

    • get preload(): boolean

      Gets whether to preload an asset.

      Returns boolean

    • set preload(value: boolean): void

      Sets whether to preload an asset. If true, the asset will be loaded during the preload phase of application initialization or when calling AssetRegistry#add.

      Parameters

      • value: boolean

      Returns void

    • get resource(): AssetResource<K> | undefined

      Gets the asset resource. Its type follows the asset's type: a Texture for an Asset<'texture'>, a Material for an Asset<'material'> and so on (see AssetMap), or unknown when the type is only known as a string. It is undefined until the asset has loaded and after Asset#unload, so narrow it before use unless the asset is known to be loaded, for example inside Asset#ready.

      Returns AssetResource<K> | undefined

    • set resource(value: AssetResource<K>): void

      Sets the asset resource. For example, a StandardMaterial or a Texture. The value is checked against the asset's type. As with the elements of an array, the check is bypassed when assigning through a variable typed as a plain Asset, so keep typed assets typed where their resource is assigned.

      Parameters

      Returns void

    • Fire an event, all additional arguments are passed on to the event listener.

      Parameters

      • name: string

        Name of event to fire.

      • Optionalarg1: any

        First argument that is passed to the event handler.

      • Optionalarg2: any

        Second argument that is passed to the event handler.

      • Optionalarg3: any

        Third argument that is passed to the event handler.

      • Optionalarg4: any

        Fourth argument that is passed to the event handler.

      • Optionalarg5: any

        Fifth argument that is passed to the event handler.

      • Optionalarg6: any

        Sixth argument that is passed to the event handler.

      • Optionalarg7: any

        Seventh argument that is passed to the event handler.

      • Optionalarg8: any

        Eighth argument that is passed to the event handler.

      Returns EventHandler

      Self for chaining.

      obj.fire('test', 'This is the message');
      
    • Return the URL required to fetch the file for this asset.

      Returns string | null

      The URL. Returns null if the asset has no associated file.

      const asset = app.assets.find("My Image", "texture");
      const img = "&lt;img src='" + asset.getFileUrl() + "'&gt;";
    • Test if there are any handlers bound to an event name.

      Parameters

      • name: string

        The name of the event to test.

      Returns boolean

      True if the object has handlers bound to the specified event name.

      obj.on('test', () => {}); // bind an event to 'test'
      obj.hasEvent('test'); // returns true
      obj.hasEvent('hello'); // returns false
    • Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event, if scope is not provided then all events with the callback will be unbound.

      Use this form to remove all listeners matching a name (and optionally callback/scope). To remove a single known subscription, prefer retaining the EventHandle returned by EventHandler#on / EventHandler#once and calling its EventHandle#off: it removes exactly that subscription and is faster (no scan of the callback list).

      Parameters

      • Optionalname: string

        Name of the event to unbind.

      • Optionalcallback: HandleEventCallback

        Function to be unbound.

      • Optionalscope: any

        Scope that was used as the this when the event is fired.

      Returns EventHandler

      Self for chaining.

      const handler = () => {};
      obj.on('test', handler);

      obj.off(); // Removes all events
      obj.off('test'); // Removes all events called 'test'
      obj.off('test', handler); // Removes all handler functions, called 'test'
      obj.off('test', handler, this); // Removes all handler functions, called 'test' with scope this
    • Attach an event handler to an event.

      Parameters

      • name: string

        Name of the event to bind the callback to.

      • callback: HandleEventCallback

        Function that is called when event is fired. Note the callback is limited to 8 arguments.

      • Optionalscope: any = ...

        Object to use as 'this' when the event is fired, defaults to current this.

      Returns EventHandle

      An event handle. For later removal, prefer retaining this handle and calling its EventHandle#off over EventHandler#off with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list).

      obj.on('test', (a, b) => {
      console.log(a + b);
      });
      obj.fire('test', 1, 2); // prints 3 to the console
      // preferred removal: retain the handle and call off() on it
      const evt = obj.on('test', (a, b) => {
      console.log(a + b);
      });
      // some time later
      evt.off();
    • Attach an event handler to an event. This handler will be removed after being fired once.

      Parameters

      • name: string

        Name of the event to bind the callback to.

      • callback: HandleEventCallback

        Function that is called when event is fired. Note the callback is limited to 8 arguments.

      • Optionalscope: any = ...

        Object to use as 'this' when the event is fired, defaults to current this.

      Returns EventHandle

      An event handle. For removal before it fires, prefer retaining this handle and calling its EventHandle#off over EventHandler#off with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list).

      obj.once('test', (a, b) => {
      console.log(a + b);
      });
      obj.fire('test', 1, 2); // prints 3 to the console
      obj.fire('test', 1, 2); // not going to get handled
    • Take a callback which is called as soon as the asset is loaded. If the asset is already loaded the callback is called straight away.

      The callback fires on success only, and a failed load still marks the asset as loaded while firing error rather than load. So a callback registered before the failure never runs, and one registered after it runs immediately with Asset#resource still null. Listen for the error event as well whenever a failure has to be handled, check asset.resource inside the callback, and never await this callback alone.

      Parameters

      • callback: AssetReadyCallback<K>

        The function called when the asset is ready. Passed the (asset) arguments.

      • Optionalscope: any

        Scope object to use when calling the callback.

      Returns void

      const asset = app.assets.find("My Asset");
      asset.ready((asset) => {
      // asset loaded
      });
      app.assets.load(asset);
    • Destroys the associated resource and marks asset as unloaded. The unload event also fires while the asset is loading, allowing resource handlers to cancel pending work.

      Returns void

      const asset = app.assets.find("My Asset");
      asset.unload();
      // asset.resource is null
    EVENT_ADDLOCALIZED: string = 'add:localized'

    Fired when we add a new localized asset id to the asset.

    asset.on('add:localized', (locale, assetId) => {
    console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`);
    });
    EVENT_CHANGE: string = 'change'

    Fired when one of the asset properties file, data, resource or resources is changed.

    asset.on('change', (asset, property, newValue, oldValue) => {
    console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`);
    });
    EVENT_ERROR: string = 'error'

    Fired if the asset encounters an error while loading.

    asset.on('error', (err, asset) => {
    console.error(`Error loading asset ${asset.name}: ${err}`);
    });
    EVENT_LOAD: string = 'load'

    Fired when the asset has completed loading.

    asset.on('load', (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
    });
    EVENT_PROGRESS: string = 'progress'

    Fired as the asset's file downloads, with the number of bytes received so far and the total expected. Only asset types whose file is fetched as binary data report progress: animation (GLB only), audio, binary, container, gsplat, model and texture. Textures loaded through an image element have no download progress, so they fire once at 0 and once at a fixed placeholder total, whether or not the file was downloaded.

    Please note:

    • downloads are skipped when asset.file.contents is supplied, so no progress is reported
    • totalBytes may not be reliable as it is based on the content-length header of the response
    asset.on('progress', (receivedBytes, totalBytes) => {
    console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`);
    });
    EVENT_REMOVE: string = 'remove'

    Fired when the asset is removed from the asset registry.

    asset.on('remove', (asset) => {
    console.log(`Asset removed: ${asset.name}`);
    });
    EVENT_REMOVELOCALIZED: string = 'remove:localized'

    Fired when we remove a localized asset id from the asset.

    asset.on('remove:localized', (locale, assetId) => {
    console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`);
    });
    EVENT_UNLOAD: string = 'unload'

    Fired just before the asset unloads the resource. This allows for the opportunity to prepare for an asset that will be unloaded. E.g. Changing the texture of a model to a default before the one it was using is unloaded.

    asset.on('unload', (asset) => {
    console.log(`Asset about to unload: ${asset.name}`);
    });