Application
Extends: AppBase
An Application represents and manages your PlayCanvas application. If you are developing using the PlayCanvas Editor, the Application is created for you. You can access your Application instance in your scripts. Below is a skeleton script which shows how you can access the application 'app' property inside the initialize and update functions:
// Editor example: accessing the pc.Application from a script
var MyScript = pc.createScript('myScript');
MyScript.prototype.initialize = function() {
// Every script instance has a property 'this.app' accessible in the initialize...
const app = this.app;
};
MyScript.prototype.update = function(dt) {
// ...and update functions.
const app = this.app;
};
If you are using the Engine without the Editor, you have to create the application instance manually.
// Engine-only example: create the application manually
const app = new pc.Application(canvas, options);
// Start the application's main loop
app.start();
Summary
Inherited
Properties
assets | The asset registry managed by the application. |
autoRender | When true, the application's render function is called every frame. |
batcher | The application's batch manager. |
elementInput | Used to handle input for ElementComponents. |
fillMode | The current fill mode of the canvas. |
gamepads | Used to access GamePad input. |
graphicsDevice | The graphics device used by the application. |
i18n | Handles localization. |
keyboard | The keyboard device. |
lightmapper | The run-time lightmapper. |
loader | The resource loader. |
maxDeltaTime | Clamps per-frame delta time to an upper bound. |
mouse | The mouse device. |
renderNextFrame | Set to true to render the scene on the next iteration of the main loop. |
resolutionMode | The current resolution mode of the canvas, Can be:
|
root | The root entity of the application. |
scene | The scene managed by the application. |
scenes | The scene registry managed by the application. |
scripts | The application's script registry. |
systems | The application's component system registry. |
timeScale | Scales the global time delta. |
touch | Used to get touch events input. |
xr | The XR Manager that provides ability to start VR/AR sessions. |
Methods
applySceneSettings | Apply scene settings to the current scene. |
configure | Load the application configuration file and apply application properties and fill the asset registry. |
destroy | Destroys application and removes all event listeners at the end of the current engine frame update. |
drawLine | Draws a single line. |
drawLineArrays | Renders an arbitrary number of discrete line segments. |
drawLines | Renders an arbitrary number of discrete line segments. |
fire | Fire an event, all additional arguments are passed on to the event listener. |
hasEvent | Test if there are any handlers bound to an event name. |
init | Initialize the app. |
isHidden | Queries the visibility of the window or tab in which the application is running. |
off | Detach an event handler from an event. |
on | Attach an event handler to an event. |
once | Attach an event handler to an event. |
preload | Load all assets in the asset registry that are marked as 'preload'. |
resizeCanvas | Resize the application's canvas element in line with the current fill mode. |
setAreaLightLuts | Sets the area light LUT tables for this app. |
setCanvasFillMode | Controls how the canvas fills the window and resizes when the window changes. |
setCanvasResolution | Change the resolution of the canvas, and set the way it behaves when the window is resized. |
setSkybox | Sets the skybox asset to current scene, and subscribes to asset load/change events. |
start | Start the application. |
update | Update the application. |
updateCanvasSize | Updates the GraphicsDevice canvas size to match the canvas size on the document page. |
Details
Constructor
Application(canvas, [options])
Create a new Application instance.
// Engine-only example: create the application manually
const app = new pc.Application(canvas, options);
// Start the application's main loop
app.start();
Parameters
canvas | HTMLCanvasElement | The canvas element. |
options | object | The options object to configure the Application. |
options.elementInput | ElementInput | Input handler for ElementComponents. |
options.keyboard | Keyboard | Keyboard handler for input. |
options.mouse | Mouse | Mouse handler for input. |
options.touch | TouchDevice | TouchDevice handler for input. |
options.gamepads | GamePads | Gamepad handler for input. |
options.scriptPrefix | string | Prefix to apply to script urls before loading. |
options.assetPrefix | string | Prefix to apply to asset urls before loading. |
options.graphicsDeviceOptions | object | Options object that is passed into the GraphicsDevice constructor. |
options.scriptsOrder | string[] | Scripts in order of loading first. |
Inherited
Properties
The asset registry managed by the application.
// Search the asset registry for all assets with the tag 'vehicle'
const vehicleAssets = this.app.assets.findByTag('vehicle');
When true, the application's render function is called every frame. Setting autoRender to false is useful to applications where the rendered image may often be unchanged over time. This can heavily reduce the application's load on the CPU and GPU. Defaults to true.
// Disable rendering every frame and only render on a keydown event
this.app.autoRender = false;
this.app.keyboard.on('keydown', function (event) {
this.app.renderNextFrame = true;
}, this);
The application's batch manager. The batch manager is used to merge mesh instances in the scene, which reduces the overall number of draw calls, thereby boosting performance.
The current fill mode of the canvas. Can be:
- FILLMODE_NONE: the canvas will always match the size provided.
- FILLMODE_FILL_WINDOW: the canvas will simply fill the window, changing aspect ratio.
- FILLMODE_KEEP_ASPECT: the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
Clamps per-frame delta time to an upper bound. Useful since returning from a tab deactivation can generate huge values for dt, which can adversely affect game state. Defaults to 0.1 (seconds).
// Don't clamp inter-frame times of 200ms or less
this.app.maxDeltaTime = 0.2;
Set to true to render the scene on the next iteration of the main loop. This only has an effect if AppBase#autoRender is set to false. The value of renderNextFrame is set back to false again as soon as the scene has been rendered.
// Render the scene only while space key is pressed
if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
this.app.renderNextFrame = true;
}
The current resolution mode of the canvas, Can be:
- RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
- RESOLUTION_FIXED: resolution of canvas will be fixed.
The root entity of the application.
// Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
const camera = this.app.root.findByName('Camera');
The scene managed by the application.
// Set the tone mapping property of the application's scene
this.app.scene.toneMapping = pc.TONEMAP_FILMIC;
The scene registry managed by the application.
// Search the scene registry for a item with the name 'racetrack1'
const sceneItem = this.app.scenes.find('racetrack1');
// Load the scene using the item's url
this.app.scenes.loadScene(sceneItem.url);
The application's component system registry. The Application constructor adds the following component systems to its component system registry:
- anim (AnimComponentSystem)
- animation (AnimationComponentSystem)
- audiolistener (AudioListenerComponentSystem)
- button (ButtonComponentSystem)
- camera (CameraComponentSystem)
- collision (CollisionComponentSystem)
- element (ElementComponentSystem)
- layoutchild (LayoutChildComponentSystem)
- layoutgroup (LayoutGroupComponentSystem)
- light (LightComponentSystem)
- model (ModelComponentSystem)
- particlesystem (ParticleSystemComponentSystem)
- rigidbody (RigidBodyComponentSystem)
- render (RenderComponentSystem)
- screen (ScreenComponentSystem)
- script (ScriptComponentSystem)
- scrollbar (ScrollbarComponentSystem)
- scrollview (ScrollViewComponentSystem)
- sound (SoundComponentSystem)
- sprite (SpriteComponentSystem)
// Set global gravity to zero
this.app.systems.rigidbody.gravity.set(0, 0, 0);
// Set the global sound volume to 50%
this.app.systems.sound.volume = 0.5;
Scales the global time delta. Defaults to 1.
// Set the app to run at half speed
this.app.timeScale = 0.5;
The XR Manager that provides ability to start VR/AR sessions.
// check if VR is available
if (app.xr.isAvailable(pc.XRTYPE_VR)) {
// VR is available
}
Methods
applySceneSettings(settings)
Apply scene settings to the current scene. Useful when your scene settings are parsed or generated from a non-URL source.
const settings = {
physics: {
gravity: [0, -9.8, 0]
},
render: {
fog_end: 1000,
tonemapping: 0,
skybox: null,
fog_density: 0.01,
gamma_correction: 1,
exposure: 1,
fog_start: 1,
global_ambient: [0, 0, 0],
skyboxIntensity: 1,
skyboxRotation: [0, 0, 0],
fog_color: [0, 0, 0],
lightmapMode: 1,
fog: 'none',
lightmapMaxResolution: 2048,
skyboxMip: 2,
lightmapSizeMultiplier: 16
}
};
app.applySceneSettings(settings);
Parameters
settings | object | The scene settings to be applied. |
settings.physics | object | The physics settings to be applied. |
settings.physics.gravity | number[] | The world space vector representing global gravity in the physics simulation. Must be a fixed size array with three number elements, corresponding to each axis [ X, Y, Z ]. |
settings.render | object | The rendering settings to be applied. |
settings.render.global_ambient | number[] | The color of the scene's ambient light. Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ]. |
settings.render.fog | string | The type of fog used by the scene. Can be: |
settings.render.fog_color | number[] | The color of the fog (if enabled). Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ]. |
settings.render.fog_density | number | The density of the fog (if enabled). This property is only valid if the fog property is set to FOG_EXP or FOG_EXP2. |
settings.render.fog_start | number | The distance from the viewpoint where linear fog begins. This property is only valid if the fog property is set to FOG_LINEAR. |
settings.render.fog_end | number | The distance from the viewpoint where linear fog reaches its maximum. This property is only valid if the fog property is set to FOG_LINEAR. |
settings.render.gamma_correction | number | The gamma correction to apply when rendering the scene. Can be: |
settings.render.tonemapping | number | The tonemapping transform to apply when writing fragments to the frame buffer. Can be: |
settings.render.exposure | number | The exposure value tweaks the overall brightness of the scene. |
settings.render.skybox | number, null | The asset ID of the cube map texture to be used as the scene's skybox. Defaults to null. |
settings.render.skyboxIntensity | number | Multiplier for skybox intensity. |
settings.render.skyboxLuminance | number | Lux (lm/m^2) value for skybox intensity when physical light units are enabled. |
settings.render.skyboxMip | number | The mip level of the skybox to be displayed. Only valid for prefiltered cubemap skyboxes. |
settings.render.skyboxRotation | number[] | Rotation of skybox. |
settings.render.lightmapSizeMultiplier | number | The lightmap resolution multiplier. |
settings.render.lightmapMaxResolution | number | The maximum lightmap resolution. |
settings.render.lightmapMode | number | The lightmap baking mode. Can be:
|
settings.render.ambientBake | boolean | Enable baking ambient light into lightmaps. |
settings.render.ambientBakeNumSamples | number | Number of samples to use when baking ambient light. |
settings.render.ambientBakeSpherePart | number | How much of the sphere to include when baking ambient light. |
settings.render.ambientBakeOcclusionBrightness | number | Brightness of the baked ambient occlusion. |
settings.render.ambientBakeOcclusionContrast | number | Contrast of the baked ambient occlusion. |
settings.render.ambientLuminance | number | Lux (lm/m^2) value for ambient light intensity. |
settings.render.clusteredLightingEnabled | boolean | Enable clustered lighting. |
settings.render.lightingShadowsEnabled | boolean | If set to true, the clustered lighting will support shadows. |
settings.render.lightingCookiesEnabled | boolean | If set to true, the clustered lighting will support cookie textures. |
settings.render.lightingAreaLightsEnabled | boolean | If set to true, the clustered lighting will support area lights. |
settings.render.lightingShadowAtlasResolution | number | Resolution of the atlas texture storing all non-directional shadow textures. |
settings.render.lightingCookieAtlasResolution | number | Resolution of the atlas texture storing all non-directional cookie textures. |
settings.render.lightingMaxLightsPerCell | number | Maximum number of lights a cell can store. |
settings.render.lightingShadowType | number | The type of shadow filtering used by all shadows. Can be:
|
settings.render.lightingCells | Vec3 | Number of cells along each world-space axis the space containing lights is subdivided into. Only lights with bakeDir=true will be used for generating the dominant light direction. |
configure(url, callback)
Load the application configuration file and apply application properties and fill the asset registry.
Parameters
url | string | The URL of the configuration file to load. |
callback | ConfigureAppCallback | The Function called when the configuration file is loaded and parsed (or an error occurs). |
destroy()
Destroys application and removes all event listeners at the end of the current engine frame update. However, if called outside of the engine frame update, calling destroy() will destroy the application immediately.
app.destroy();
drawLine(start, end, [color], [depthTest], [layer])
Draws a single line. Line start and end coordinates are specified in world-space. The line will be flat-shaded with the specified color.
// Render a 1-unit long white line
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLine(start, end);
// Render a 1-unit long red line which is not depth tested and renders on top of other geometry
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLine(start, end, pc.Color.RED, false);
// Render a 1-unit long white line into the world layer
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
const worldLayer = app.scene.layers.getLayerById(pc.LAYERID_WORLD);
app.drawLine(start, end, pc.Color.WHITE, true, worldLayer);
Parameters
start | Vec3 | The start world-space coordinate of the line. |
end | Vec3 | The end world-space coordinate of the line. |
color | Color | The color of the line. It defaults to white if not specified. |
depthTest | boolean | Specifies if the line is depth tested against the depth buffer. Defaults to true. |
layer | Layer | The layer to render the line into. Defaults to LAYERID_IMMEDIATE. |
drawLineArrays(positions, colors, [depthTest], [layer])
Renders an arbitrary number of discrete line segments. The lines are not connected by each subsequent point in the array. Instead, they are individual segments specified by two points.
// Render 2 discrete line segments
const points = [
// Line 1
0, 0, 0,
1, 0, 0,
// Line 2
1, 1, 0,
1, 1, 1
];
const colors = [
// Line 1
1, 0, 0, 1, // red
0, 1, 0, 1, // green
// Line 2
0, 0, 1, 1, // blue
1, 1, 1, 1 // white
];
app.drawLineArrays(points, colors);
Parameters
positions | number[] | An array of points to draw lines between. Each point is represented by 3 numbers - x, y and z coordinate. |
colors | number[] | An array of colors to color the lines. This must be the same length as the position array. The length of the array must also be a multiple of 2. |
depthTest | boolean | Specifies if the lines are depth tested against the depth buffer. Defaults to true. |
layer | Layer | The layer to render the lines into. Defaults to LAYERID_IMMEDIATE. |
drawLines(positions, colors, [depthTest], [layer])
Renders an arbitrary number of discrete line segments. The lines are not connected by each subsequent point in the array. Instead, they are individual segments specified by two points. Therefore, the lengths of the supplied position and color arrays must be the same and also must be a multiple of 2. The colors of the ends of each line segment will be interpolated along the length of each line.
// Render a single line, with unique colors for each point
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLines([start, end], [pc.Color.RED, pc.Color.WHITE]);
// Render 2 discrete line segments
const points = [
// Line 1
new pc.Vec3(0, 0, 0),
new pc.Vec3(1, 0, 0),
// Line 2
new pc.Vec3(1, 1, 0),
new pc.Vec3(1, 1, 1)
];
const colors = [
// Line 1
pc.Color.RED,
pc.Color.YELLOW,
// Line 2
pc.Color.CYAN,
pc.Color.BLUE
];
app.drawLines(points, colors);
Parameters
positions | Vec3[] | An array of points to draw lines between. The length of the array must be a multiple of 2. |
colors | Color[] | An array of colors to color the lines. This must be the same length as the position array. The length of the array must also be a multiple of 2. |
depthTest | boolean | Specifies if the lines are depth tested against the depth buffer. Defaults to true. |
layer | Layer | The layer to render the lines into. Defaults to LAYERID_IMMEDIATE. |
fire(name, [arg1], [arg2], [arg3], [arg4], [arg5], [arg6], [arg7], [arg8])
Fire an event, all additional arguments are passed on to the event listener.
obj.fire('test', 'This is the message');
Parameters
name | string | Name of event to fire. |
arg1 | * | First argument that is passed to the event handler. |
arg2 | * | Second argument that is passed to the event handler. |
arg3 | * | Third argument that is passed to the event handler. |
arg4 | * | Fourth argument that is passed to the event handler. |
arg5 | * | Fifth argument that is passed to the event handler. |
arg6 | * | Sixth argument that is passed to the event handler. |
arg7 | * | Seventh argument that is passed to the event handler. |
arg8 | * | Eighth argument that is passed to the event handler. |
Returns
EventHandlerSelf for chaining.
hasEvent(name)
Test if there are any handlers bound to an event name.
obj.on('test', function () { }); // bind an event to 'test'
obj.hasEvent('test'); // returns true
obj.hasEvent('hello'); // returns false
Parameters
name | string | The name of the event to test. |
Returns
booleanTrue if the object has handlers bound to the specified event name.
init(appOptions)
Initialize the app.
Parameters
appOptions | AppOptions | Options specifying the init parameters for the app. |
isHidden()
Queries the visibility of the window or tab in which the application is running.
Returns
booleanTrue if the application is not visible and false otherwise.
off([name], [callback], [scope])
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.
const handler = function () {
};
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
Parameters
name | string | Name of the event to unbind. |
callback | HandleEventCallback | Function to be unbound. |
scope | object | Scope that was used as the this when the event is fired. |
Returns
EventHandlerSelf for chaining.
on(name, callback, [scope])
Attach an event handler to an event.
obj.on('test', function (a, b) {
console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console
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. |
scope | object | Object to use as 'this' when the event is fired, defaults to current this. |
Returns
EventHandlerSelf for chaining.
once(name, callback, [scope])
Attach an event handler to an event. This handler will be removed after being fired once.
obj.once('test', function (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
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. |
scope | object | Object to use as 'this' when the event is fired, defaults to current this. |
Returns
EventHandlerSelf for chaining.
preload(callback)
Load all assets in the asset registry that are marked as 'preload'.
Parameters
callback | PreloadAppCallback | Function called when all assets are loaded. |
resizeCanvas([width], [height])
Resize the application's canvas element in line with the current fill mode.
- In FILLMODE_KEEP_ASPECT mode, the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
- In FILLMODE_FILL_WINDOW mode, the canvas will simply fill the window, changing aspect ratio.
- In FILLMODE_NONE mode, the canvas will always match the size provided.
Parameters
width | number | The width of the canvas. Only used if current fill mode is FILLMODE_NONE. |
height | number | The height of the canvas. Only used if current fill mode is FILLMODE_NONE. |
Returns
objectA object containing the values calculated to use as width and height.
setAreaLightLuts(ltcMat1, ltcMat2)
Sets the area light LUT tables for this app.
Parameters
ltcMat1 | number[] | LUT table of type |
ltcMat2 | number[] | LUT table of type |
setCanvasFillMode(mode, [width], [height])
Controls how the canvas fills the window and resizes when the window changes.
Parameters
mode | string | The mode to use when setting the size of the canvas. Can be:
|
width | number | The width of the canvas (only used when mode is FILLMODE_NONE). |
height | number | The height of the canvas (only used when mode is FILLMODE_NONE). |
setCanvasResolution(mode, [width], [height])
Change the resolution of the canvas, and set the way it behaves when the window is resized.
Parameters
mode | string | The mode to use when setting the resolution. Can be:
|
width | number | The horizontal resolution, optional in AUTO mode, if not provided canvas clientWidth is used. |
height | number | The vertical resolution, optional in AUTO mode, if not provided canvas clientHeight is used. |
setSkybox(asset)
Sets the skybox asset to current scene, and subscribes to asset load/change events.
Parameters
asset | Asset | Asset of type |
start()
Start the application. This function does the following:
- Fires an event on the application named 'start'
- Calls initialize for all components on entities in the hierarchy
- Fires an event on the application named 'initialize'
- Calls postInitialize for all components on entities in the hierarchy
- Fires an event on the application named 'postinitialize'
- Starts executing the main loop of the application
This function is called internally by PlayCanvas applications made in the Editor but you will need to call start yourself if you are using the engine stand-alone.
app.start();
update(dt)
Update the application. This function will call the update functions and then the postUpdate functions of all enabled components. It will then update the current state of all connected input devices. This function is called internally in the application's main loop and does not need to be called explicitly.
Parameters
dt | number | The time delta in seconds since the last frame. |
updateCanvasSize()
Updates the GraphicsDevice canvas size to match the canvas size on the document page. It is recommended to call this function when the canvas size changes (e.g on window resize and orientation change events) so that the canvas resolution is immediately updated.