App - Verge3D User Manual - Soft8Soft
Description: App is the main class to create and manage your Verge3D applications using JavaScript.

EventDispatcher →

# App

App class allows you to set up your 3D application more easily. It includes code to init WebGL renderer, load glTF scenes, auto-start animations as well as logic for basic camera controls.

## Example

`// loaded GLTF 2.0 asset const url = 'template.gltf'; // construct a new application with simple rotating preloader const app = new v3d.App('v3d-container', null, new v3d.SimplePreloader({ container: 'v3d-container' })); // load main scene app.loadScene(url, function() { app.enableControls(); app.run(); runCode(); }); function runCode() { // place your own code here }`

## Constructor

### App(container : String | HTMLElement, ctxSettings : Object, preloader : Preloader)

container
  The ID of an HTML-element or the HTML-element itself to contain the canvas.
ctxSettings
  The WebGL context attributes to be passed in the `canvas.getContext()` method:
  alpha
    Use transparent canvas. Default is `false`.
  antialias
    Enable multi-sampled anti-aliasing (MSAA). Default is `true`.
  depth
    Use depth buffer. Default is `true`.
  desynchronized
    Create desynchronized context for CAD-like applications. Default is `false`.
  failIfMajorPerformanceCaveat
    Fail to create a 3D context if the target device is slow (uses software rendering). Default is `false`.
  powerPreference
    Prefer high-end (`"high-performance"`) or low-end (`"low-power"`) graphics on dual-GPU systems. Default is `"default"`.
  premultipliedAlpha
    Use premultiplied alpha for rendering. Default is `true`.
  preserveDrawingBuffer
    Preserve content of the 3D canvas between frames. Default is `false`.
  stencil
    Allow stencil buffer to be used for rendering. Default is `true`.
preloader
  The instance of application's Preloader class.

Verge3D application constructor. This constructor does the following:

1. Creates a new container element (if necessary).
2. Checks whether WebGL technology is supported, if not displays an error dialog.
3. Initializes an application clock.
4. Creates a new 3D canvas with WebGL 1.0 or WebGL 2.0 context and adds it to the container element.
5. Initializes a glTF Loader.
6. Prepares texture compression module.
7. Initializes methods for accelerated raycasting (BVH).
8. Adds an app instance to `v3d.apps` list (in case of non-modularized engine).

## Properties

### # .aaMethod : String

Anti-aliasing method used to improve the visual quality of the rendered scene, one of:

- 'AUTO'
- 'MSAA4'
- 'MSAA8'
- 'MSAA16'
- 'FXAA'

This value is set by .loadScene so consider it read-only.

### # .actions : Array

Array of animation actions used to schedule app animations. Instead of accessing this list directly, you should use the SceneUtils.getAnimationActionByName method to search for an action by its clip name.

### # .camera : Camera

Application main camera. Do not replace this property directly if you need to change the main camera. Instead use the .setCamera method.

### # .clearBkgOnLoad : Boolean

Set the scene background to `null` after loading a glTF scene. Default is `false`.

### # .clock : Clock

Application Clock object.

### # .container : HTMLElement

A container element. This is a parent element for 3D canvas used for rendering operations.

### # .compileCallbacks : Array

Array of functions which will be called just before shader compilation. Shader compilation occurs during scene loading right after all assets (glTF metadata, binary, textures) has been fetched.

Use compile callback to enable post-processing or add fog, since adding these effects in runtime can negatively affect performance.

`function initFog(appInstance) { appInstance.scene.fog = new v3d.FogExp2('green', 0.01); } // loaded GLTF 2.0 asset const url = 'my_scene.gltf'; // construct a new application with simple rotating preloader const app = new v3d.App('v3d-container', null, new v3d.SimplePreloader({ container: 'v3d-container' })); // initialize fog just before shader compilation app.compileCallbacks.push(initFog); // load main scene app.loadScene(url, function() { app.enableControls(); app.run(); });`

### # .controls : Object

Application camera controls. Use .enableControls to assign this value.

### # .cssRenderer : CSS3DRenderer

Application's CSS renderer class instance. Default is `null`, meaning no CSS-transformed objects are present in the app. This property should never be assigned directly, instead use the .enableCSSRenderer method.

### # .cssScene : Scene

Scene which contains CSS-transformed objects. Default is `null`, meaning no CSS-transformed objects are present in the app. This property should never be assigned directly, instead use the .enableCSSRenderer method.

### # .disableRenderTrigger : Integer

Used to implement delay when using .disableRendering with non-zero parameter `after`. Do not modify.

### # .elapsed : Float

Time in seconds passed since the last frame.

### # .enableRender : Boolean

Read only, `true` if the rendering is enabled, otherwise `false`. To enable/disable the actual rendering use the .enableRendering and .disableRendering methods.

### # .frame : Integer

Current rendering frame of the application.

### # .frameRateDivider : Float

Application FPS divider. Use .setFrameRateDivider to set this value.

### # .loader : GLTFLoader

Application's glTF loader instance.

### # .mixer : AnimationMixer

Mixer used to play animations loaded from glTF data.

### # .preloader : Preloader

App preloader instance (exists only during the scene loading).

### # .registerServiceKeys : Boolean

Register the service keys like triple tilda (~~~) which displays service menu. Default is `true`. If you need to disable service keys, set this value to `false` right after making a new App instance.

`const app = new v3d.App(containerId, ctxSettings, preloader); app.registerServiceKeys = false;`

If you need to disable the service keys for the running application, use the AppUtils.unregisterServiceKeys method.

### # .renderCallbacks : Array

Array of functions which will be called every time when rendering frame begins.

### # .renderer : WebGLRenderer

Application's WebGL renderer class instance.

### # .scene : Scene

Application main scene.

### # .ssaaOnPause : Boolean

Trigger SSAA (supersample anti-aliasing) upon rendering pause. Default is `false`.

### # .stats : Stats

Instance of the Stats class used to display FPS counter element. Created and destroyed with .showFPS and .hideFPS methods.

### # .useHDR : Boolean

Whether HDR rendering is enabled for the app or not. HDR rendering is enabled when a) it is requested by the main glTF scene and b) it is supported by the target hardware.

### # .worldCubemapRes : Integer

Resolution of the cubemap texture representing the world material. Default is `1024`.

### # .xrCameraParent : Object3D

AR/VR camera parent used to move the camera in WebXR session.

### # .xrControllers : Array

Array of controller objects for the active WebXR session.

### # .xrSession : XRSession

Active WebXR session. Never set XR session directly, use .initWebXR method.

## Methods

### # .animate()

Handler for scene updates: rendering, animations and camera controls. Do not change unless you know what you are doing.

### # .appendScene(url : String, loadCb : Function, progressCb : Function, errorCb : Function, loadCameras : Boolean, loadLights : Boolean)

Append the scene from the specified glTF file to the current scene. The `loadCb` callback will receive the loaded scene as a parameter after the loading is finished

If there is no active scene in the application, then nothing will be appended.

Parameters `loadCameras` and `loadLights` are used to specify if cameras and lights will be appended from the loaded scene. Both parameters are `true` by default.

### # .assignClippingPlanes(scene : Scene)

Prepare clipping planes for the given scene.

### # .disableCSSRenderer()

Disposes .cssRenderer and .cssScene instances and reinitialize application controls back to normal operation.

### # .disablePostprocessing(keepOutline : Boolean, keepGTAO : Boolean)

Disable all post-processing effects (except outline when `keepOutline=true` or ambient occlusion when `keepGTAO=true`).

### # .disableRendering(after : Integer)

Disable graphics updates in the animation loop after the given amount of frames (specify 0 to disable immediately). The controls and the animation mixer will keep being updated and the render callbacks will keep being called.

### # .dispose()

Unloads the scene (by calling unload) and disposes the whole application, which includes cleaning up the application's renderer and removing the canvas element from the DOM. Emits the dispose event.

The application is no longer usable after disposing. This approach is best suited for cases where the complete clean up is needed.

### # .disposeEnvironment()

Dispose environment and background buffers.

### # .enableControls(element : HTMLElement)

Enable controls for the main app camera. Depending on the control type specified for the camera this method will give you 'ORBIT', 'FLYING', 'FIRST_PERSON', or static camera.

The optional `element` parameter is used to specify the canvas element to assign mouse/keyboard/touch events. If not specified, controls will be assigned on the .domElement element of the app's .renderer instance.

### # .enableCSSRenderer()

Create new .cssRenderer and .cssScene instances and reinitialize application controls to operate with CSS transformed objects.

This method is usually executed by the create object → plane with html puzzle.

### # .enablePostprocessing(effects : Array)

Enable the given post-processing effects. Each effect represented by an object with the following properties:

Afterimage
  `{ type: 'afterimage', damp: 0.85 }`
Bloom
  `{ type: 'bloom', threshold: 0.8, strength: 0.3, radius: 0.5 }`
Brightness/Contrast
  `{ type: 'brightnessContrast', brightness: 0.1, contrast: 0.3 }`
DOF
  `{ type: 'dof', focus: 10, aperture: 1, maxblur: 0.001, depthLeakThreshold: 0.2 }`
Grayscale
  `{ type: 'grayscale' }`
GTAO
  `{ type: 'gtao', distance: 0.2, factor: 1.0, precision: 0.250, bentNormals: true, bounceApprox: true }`
Outline
  `{ type: 'outline', edgeStrength: 3.0, edgeGlow: 0.0, edgeThickness: 1.0, pulsePeriod: 0.0, visibleEdgeColor: new Vector4(1, 1, 1, 1), hiddenEdgeColor: new Vector4(0.1, 0.04, 0.02, 1) }`
SSR (reflection or refraction)
  `{ type: 'ssr', useRefract: false, objects: [], steps: 100, stride: 5, binarySearchSteps: 4, thickness: 0.01, maxDistance: 100, renderTargetScale: 0.5, jitter: 0.1, renderAfter: [] }`

### # .enableRendering()

Enable graphics updates in the animation loop.

### # .enableSSAA(sampleLevel : Integer, iterative : Boolean)

Enable supersample anti-aliasing. The number of samples is calculated as 2^sampleLevel (e.g specify 4 to enable 16x SSAA).

### # .endWebXR()

End WebXR session.

### # .generateRTargetPMREM(cubeRT : WebGLRenderTarget) → WebGLRenderTarget

Convert cubemap render target `cubeRT` to PMREM render target. This method executed by .updateEnvironment and rarely needed on its own.

### # .getCamera(tryXrIfAvail : Boolean) → Camera

Returns the main app camera. This method is recommended over accessing .camera property directly since it works for both regular rendering and WebXR mode (AR/VR). To return AR/VR camera specify `tryXrIfAvail=true`.

### # .getHeight() → Float

Return calculated container element height.

### # .getWidth() → Float

Return calculated container element width.

### # .hideFPS()

Hide frame rate counter.

### # .initWebXR(mode : String, referenceSpaceType : String, successCb : Function, failureCb : Function, exitCb : Function, options : Object)

- mode — `"immersive-vr"` for VR session, `"immersive-ar"` for AR session.
- referenceSpaceType — one of `"viewer"`, `"local"`, `"local-floor"`, `"bounded-floor"`, `"unbounded"`.
- successCb — callback executed on success.
- failureCb — callback executed when the method fails.
- exitCb — callback executed when the user leaves WebXR session.
- options — dictionary object with additional params, such as `domOverlay` to enable HTML in AR mode.

Initialize a WebXR session (AR or VR).

### # .loadScene(url : String, loadCb : Function, progressCb : Function, errorCb : Function)

Load the glTF scene. The loadCb callback will receive the loaded scene as a parameter after the loading is finished. Emits the sceneLoad event.

If there already is an active scene (e.g. loaded before via the .loadScene method), then use .unload first to avoid conflicts between the existed scene and the loaded one.

### # .onResize()

Handler for canvas resize event. Do not change unless you know what you are doing. If you just need to add custom logic on app resize, use the following snippet:

`const onResizeOld = app.onResize; app.onResize = function() { // execute existing resize logic onResizeOld.call(app); // place your own code here console.log("Resized!"); }`

### # .pause()

Pauses the application: animation, controls, render callbacks and rendering. Emits the pause event.

### # .printPerformanceInfo(delta : Float)

Estimate and print out a rendering performance profile. `delta` is an optional period of estimation in seconds (default `1`).

### # .render()

Handler for scene rendering. Do not change unless you know what you are doing. Emits the beforeRender and afterRender events.

### # .resume()

Resumes the application: animation, controls, render callbacks and rendering. Emits the resume event.

### # .run()

Starts the application by removing the preloader and starting the rendering cycle.

### # .setCamera(camera : Camera) → Camera

Set the active camera and switch the app controls based on settings assigned on the camera. Also, if the app has postprocessing is enabled, updates the camera for the corresponding post-processing passes.

### # .setFrameRateDivider(divider : Integer)

Lowers the maximum frame by dividing it by a specified integer number. By default the engine tries to render scenes at 60 frames per second. If the divider is set to 2, for example, the FPS will be topped out to 30.

### # .showFPS()

Show frame rate counter.

### # .unload(rootObj : Object3D)

rootObj — (optional) an object to unload along with its children; if no object is given or the given object is the main application scene then the method performs full scene cleanup.

Unloads either a part or the whole scene depending on the parameters.

If the given `rootObj` is one of the scene objects, then this method removes the given object and its descendants from the scene and also frees the related resources (geometries, materials, textures, etc...). If the given `rootObj` is the scene instance itself, then this method performs full scene cleanup, which includes disposing all objects, the scene's environment, cameras and camera controls, animations, postprocessing, internal WebGL objects, etc...

After the application's scene was fully unloaded the .loadScene method can be used to load a completely new scene. This approach is best suited for loading/unloading multiple scenes without disposing the whole application.

### # .updateConstraints(scene : Scene)

Update constraints on the scene. Normally, you don't need to use this method, since all constraints updated during scene load (by the .loadScene and .appendScene methods).

### # .updateEnvironment(wMat : Material)

Update world environment from the specified material. Such material is usually stored in the Scene.worldMaterial property.

### # .updateReflectionProbes(object3d : Object3D)

object3d — an object or a scene for searching probe objects among its descendants.

Update all CubeReflectionProbe objects that are descendants of the given `object3d` object.

## Events

### #afterFirstRender

An event emitted right after the first frame rendered. You can subscribe to it as follows: `app.addEventListener('afterFirstRender', e => ...); // properties of e: type ('afterFirstRender'), target (instance of App)`

### #afterRender

An event emitted after each frame rendered (in the beginning of the render method). You can subscribe to it as follows: `app.addEventListener('afterRender', e => ...); // properties of e: type ('afterRender'), target (instance of App)`

### #beforeRender

An event emitted before each frame rendered (in the end of the render method). You can subscribe to it as follows:

`app.addEventListener('beforeRender', e => ...); // properties of e: type ('beforeRender'), target (instance of App)`

### #dispose

An event emitted right after the application is disposed via the dispose method. You can subscribe to it as follows:

`app.addEventListener('dispose', e => ...); // properties of e: type ('dispose'), target (instance of App)`

### #pause

An event emitted when the application is paused via the pause method. You can subscribe to it as follows:

`app.addEventListener('pause', e => ...); // properties of e: type ('pause'), target (instance of App)`

### #resume

An event emitted when the application is resumed via the resume method. You can subscribe to it as follows:

`app.addEventListener('resume', e => ...); // properties of e: type ('resume'), target (instance of App)`

### #sceneLoad

An event emitted after the app's scene is done loading, parsing and all its shaders are compiled. This event is emitted as a result of calling the loadScene method. You can subscribe to it as follows:

`app.addEventListener('sceneLoad', e => ...); // properties of e: type ('sceneLoad'), target (instance of App)`

## Puzzles

Check out the following puzzles to handle your app in a visual way:

- configure application — to set up app initialization.
- load scene — to load a new scene.
- append scene — to append some asset to the app.
- enable rendering/disable rendering — to enable/disable rendering (with optional anti-aliasing).
- postprocessing — to enable/disable various post-processing effects.

## Source

The source code for this module is freely available in the `src/extras/App.js` file inside the Verge3D's installation folder.