The API reference of the PlayCanvas Engine, playcanvas 2.23.1 on npm: its classes, interfaces, type aliases and functions by category, and its constants.
The same pages as Markdown, for AI agents: llms-full.txt.
Class · extends AnimNode · category: Animation
AnimBlendTrees are used to store and blend multiple AnimNodes together. BlendTrees can be the child of other AnimBlendTrees, in order to create a hierarchy of AnimNodes. It takes a blend type as an argument which defines which function should be used to determine the weights of each of its children, based on the current parameter value.
The blend type is one of ANIM_BLEND_1D, ANIM_BLEND_2D_DIRECTIONAL,
ANIM_BLEND_2D_CARTESIAN and ANIM_BLEND_DIRECT, each implemented by a subclass.
Every child sits at a point on the parameter axis or plane, and the tree weights the children by
where the current parameter values fall among those points. With syncAnimations set, the
children's playback speeds are synchronized so that a walk and a run cycle stay in step while
blending. Blend trees are described in the AnimStateGraph and built when it loads.
new AnimBlendTree(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)
Create a new AnimBlendTree instance.
Parameters
state (AnimState): The AnimState that this AnimBlendTree belongs to.parent (AnimBlendTree | null): The parent of the AnimBlendTree. If not null, the
AnimNode is stored as part of a AnimBlendTree hierarchy.name (string): The name of the BlendTree. Used when assigning an AnimTrack
to its children.point (number | Vec2): The coordinate/vector that's used to determine the weight of
this node when it's part of an AnimBlendTree.parameters (string[]): The anim component parameters which are used to calculate the
current weights of the blend trees children.children (any[]): The child nodes that this blend tree should create. Can either
be of type AnimNode or AnimBlendTree.syncAnimations (boolean): If true, the speed of each blended animation will be
synchronized.createTree (Function): Used to create child blend trees of varying types.findParameter (Function): Used at runtime to get the current parameter values.Class · extends AnimBlendTree · category: Animation
An AnimBlendTree that calculates its weights using the 1D algorithm from chapter 6 of Rune Skovbo Johansen's thesis.
The children sit at points along a single parameter, and the two whose points bracket the current value share the weight between them. This is the tree for one-dimensional blends such as idle, walk and run driven by a speed parameter.
new AnimBlendTree1D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)
Create a new BlendTree1D instance.
Parameters
state (AnimState): The AnimState that this AnimBlendTree belongs to.parent (AnimBlendTree | null): The parent of the AnimBlendTree. If not null, the
AnimNode is stored as part of a AnimBlendTree hierarchy.name (string): The name of the BlendTree. Used when assigning an AnimTrack
to its children.point (number | Vec2): The coordinate/vector that's used to determine the weight of
this node when it's part of an AnimBlendTree.parameters (string[]): The anim component parameters which are used to calculate the
current weights of the blend trees children.children (any[]): The child nodes that this blend tree should create. Can either
be of type AnimNode or AnimBlendTree.syncAnimations (boolean): If true, the speed of each blended animation will be
synchronized.createTree (Function): Used to create child blend trees of varying types.findParameter (Function): Used at runtime to get the current parameter values.Class · extends AnimBlendTree · category: Animation
An AnimBlendTree that calculates its weights using the 2D Cartesian algorithm from chapter 6, section 3 of Rune Skovbo Johansen's thesis.
The children sit at points on a plane defined by two parameters, and weights are computed from where the current parameter point lies among them, treating the two axes as independent. Use it when the parameters are unrelated quantities, such as forward speed against turn rate.
new AnimBlendTreeCartesian2D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)Class · extends AnimBlendTree · category: Animation
An AnimBlendTree that calculates normalized weight values based on the total weight. Each child's weight is read from its own parameter and the weights are then normalized to sum to one, so the mix is driven explicitly rather than by a position in parameter space.
new AnimBlendTreeDirect(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)Class · extends AnimBlendTree · category: Animation
An AnimBlendTree that calculates its weights using the 2D directional algorithm from chapter 6 of Rune Skovbo Johansen's thesis.
The children's points are treated as directions from the origin, so the weights follow the angle and magnitude of the current parameter point. Use it when the two parameters form a direction, such as a movement vector driving an eight-way locomotion set.
new AnimBlendTreeDirectional2D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)Class · extends Component · category: Animation
The AnimComponent enables an Entity to play back animations on models and entity properties. Animations are driven by animation state graphs, which can be authored in the PlayCanvas Editor or constructed programmatically, and support blending between multiple layers and clips.
You should never need to use the AnimComponent constructor directly. To add an AnimComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('anim', {
activate: true,
speed: 1
});
Once the AnimComponent is added to the entity, you can access it via the Entity#anim property:
entity.anim.speed = 2; // Play animations at double speed
console.log(entity.anim.speed); // Get the playback speed and print it
Relevant Engine API examples:
get activate(): boolean
set activate(value: boolean)
Gets whether the first animation will begin playing when the scene is loaded.
get baseLayer(): AnimComponentLayer | null
Returns the base layer of the state graph.
get layers(): readonly AnimComponentLayer[]
Returns the animation layers available in this anim component. Use addLayer or loadStateGraph to change layers.
get normalizeWeights(): boolean
set normalizeWeights(value: boolean)
Gets whether the animation component will normalize the weights of its layers by their sum total.
get playable(): boolean
Returns whether all component layers are currently playable.
get playing(): boolean
set playing(value: boolean)
Gets whether to play or pause all animations in the component.
get rootBone(): Entity
set rootBone(value: Entity)
Gets the entity that this anim component should use as the root of the animation hierarchy.
get speed(): number
set speed(value: number)
Gets the speed multiplier for animation play back speed.
addLayer(name: string, weight?: number, mask?: any[], blendType?: string): AnimComponentLayer
Adds a new anim component layer to the anim component.
Parameters
name (string): The name of the layer to create.weight (number, optional): The blending weight of the layer. Defaults to 1.mask (any[], optional): A list of paths to bones in the model which should be animated in
this layer. If omitted the full model is used. Defaults to null.blendType (string, optional): Defines how properties animated by this layer blend with
animations of those properties in previous layers. Defaults to ANIM_LAYER_OVERWRITE.Returns AnimComponentLayer: The created anim component layer.
assignAnimation(nodePath: string, animTrack: AnimTrack, layerName?: string, speed?: number, loop?: boolean): void
Associates an animation with a state or blend tree node in the loaded state graph. If all states are linked and the activate value was set to true then the component will begin playing. If no state graph is loaded, a default state graph will be created with a single state based on the provided nodePath parameter.
Parameters
nodePath (string): Either the state name or the path to a blend tree node that this
animation should be associated with. Each section of a blend tree path is split using a
period (.) therefore state names should not include this character (e.g "MyStateName" or
"MyStateName.BlendTreeNode").animTrack (AnimTrack): The animation track that will be assigned to this state and
played whenever this state is active.layerName (string, optional): The name of the anim component layer to update. If omitted the
default layer is used. If no state graph has been previously loaded this parameter is
ignored.speed (number, optional, default 1): Update the speed of the state you are assigning an animation to.
Defaults to 1.loop (boolean, optional, default true): Update the loop property of the state you are assigning an
animation to. Defaults to true.findAnimationLayer(name: string): AnimComponentLayer
Finds an AnimComponentLayer in this component.
Parameters
name (string): The name of the anim component layer to find.Returns AnimComponentLayer: Layer.
getBoolean(name: string): boolean
Returns a boolean parameter value by name.
Parameters
name (string): The name of the boolean to return the value of.Returns boolean: A boolean.
getFloat(name: string): number
Returns a float parameter value by name.
Parameters
name (string): The name of the float to return the value of.Returns number: A float.
getInteger(name: string): number
Returns an integer parameter value by name.
Parameters
name (string): The name of the integer to return the value of.Returns number: An integer.
getTrigger(name: string): boolean
Returns a trigger parameter value by name.
Parameters
name (string): The name of the trigger to return the value of.Returns boolean: A boolean.
loadStateGraph(stateGraph: any): void
Initializes component animation controllers using the provided state graph.
Parameters
stateGraph (any): The state graph asset to load into the component. Contains the
states, transitions and parameters used to define a complete animation controller.Example
entity.anim.loadStateGraph({
"layers": [
{
"name": layerName,
"states": [
{
"name": "START",
"speed": 1
},
{
"name": "Initial State",
"speed": speed,
"loop": loop,
"defaultState": true
}
],
"transitions": [
{
"from": "START",
"to": "Initial State"
}
]
}
],
"parameters": {}
});
rebind(): void
Rebind all of the components layers.
removeNodeAnimations(nodeName: string, layerName?: string): void
Removes animations from a node in the loaded state graph.
Parameters
nodeName (string): The name of the node that should have its animation tracks removed.layerName (string, optional): The name of the anim component layer to update. If omitted the
default layer is used.removeStateGraph(): void
Removes all layers from the anim component.
reset(): void
Reset all of the components layers and parameters to their initial states. If a layer was playing before it will continue playing.
resetTrigger(name: string): void
Resets the value of a trigger parameter that was defined in the animation components state graph to false.
Parameters
name (string): The name of the parameter to set.setBoolean(name: string, value: boolean): void
Sets the value of a boolean parameter that was defined in the animation components state graph.
Parameters
name (string): The name of the parameter to set.value (boolean): The new boolean value to set this parameter to.setFloat(name: string, value: number): void
Sets the value of a float parameter that was defined in the animation components state graph.
Parameters
name (string): The name of the parameter to set.value (number): The new float value to set this parameter to.setInteger(name: string, value: number): void
Sets the value of an integer parameter that was defined in the animation components state graph.
Parameters
name (string): The name of the parameter to set.value (number): The new integer value to set this parameter to.setTrigger(name: string, singleFrame?: boolean): void
Sets the value of a trigger parameter that was defined in the animation components state graph to true.
Parameters
name (string): The name of the parameter to set.singleFrame (boolean, optional, default false): If true, this trigger will be set back to false at the end
of the animation update. Defaults to false.entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Animation
An AnimComponentLayer is one layer of an AnimComponent. It runs the state machine that
the AnimStateGraph defines for that layer and contributes the result to the entity's
final pose with a weight, either overwriting the layers beneath it or adding to them
according to blendType. A mask limits which nodes of the hierarchy the layer
animates, which is how an upper-body action plays on top of a full-body locomotion layer. The
first layer is AnimComponent#baseLayer; add more with AnimComponent#addLayer.
Playback is per layer: play starts a named state, transition blends to another state over a given time, pause and reset act on the current state, and activeState, activeStateProgress and transitioning report where the layer is. assignAnimation binds an AnimTrack to a state, or to a node inside a blend tree using a dotted path, and blendToWeight fades the whole layer in or out.
Example
// Fade in an upper-body layer and play its 'Wave' state over the base layer
const layer = entity.anim.findAnimationLayer('UpperBody');
layer.blendToWeight(1, 0.3);
layer.play('Wave');
get activeState(): string
Gets the currently active state name.
get activeStateCurrentTime(): number
set activeStateCurrentTime(time: number)
Gets the active state's time in seconds.
get activeStateDuration(): number
Gets the currently active states duration.
get activeStateProgress(): number
Gets the currently active state's progress as a value normalized by the state's animation duration. Looped animations will return values greater than 1.
get mask(): any
set mask(value: any)
Gets the mask of bones which should be animated or ignored by this layer.
get name(): string
Returns the name of the layer.
get playable(): boolean
Returns true if a state graph has been loaded and all states in the graph have been assigned animation tracks.
get playing(): boolean
set playing(value: boolean)
Gets whether this layer is currently playing.
get previousState(): string | null
Gets the previously active state name.
get states(): string[]
Gets all available states in this layers state graph.
get transitioning(): boolean
Gets whether the anim component layer is currently transitioning between states.
get transitionProgress(): number | null
Gets the progress, if the anim component layer is currently transitioning between states. Otherwise returns null.
get weight(): number
set weight(value: number)
Sets the blending weight of this layer.
assignAnimation(nodePath: string, animTrack: AnimTrack, speed?: number, loop?: boolean): void
Assigns an animation track to a state or blend tree node in the current graph. If a state for the given nodePath doesn't exist, it will be created. If all states nodes are linked and the AnimComponent#activate value was set to true then the component will begin playing.
Parameters
nodePath (string): Either the state name or the path to a blend tree node that this
animation should be associated with. Each section of a blend tree path is split using a
period (.) therefore state names should not include this character (e.g "MyStateName" or
"MyStateName.BlendTreeNode").animTrack (AnimTrack): The animation track that will be assigned to this state and
played whenever this state is active.speed (number, optional): Update the speed of the state you are assigning an animation to.
Defaults to 1.loop (boolean, optional): Update the loop property of the state you are assigning an
animation to. Defaults to true.blendToWeight(weight: number, time: number): void
Blend from the current weight value to the provided weight value over a given amount of time.
Parameters
weight (number): The new weight value to blend to.time (number): The duration of the blend in seconds.getAnimationAsset(stateName: string): { asset: number }
Returns an object holding the animation asset id that is associated with the given state.
Parameters
stateName (string): The name of the state to get the asset for.Returns { asset: number }: An object containing the animation asset id associated with the given state.
pause(): void
Pause the animation in the current state.
play(name?: string): void
Start playing the animation in the current state.
Parameters
name (string, optional): If provided, will begin playing from the start of the state with
this name.rebind(): void
Rebind any animations in the layer to the currently present components and model of the anim components entity.
removeNodeAnimations(nodeName: string): void
Removes animations from a node in the loaded state graph.
Parameters
nodeName (string): The name of the node that should have its animation tracks removed.reset(): void
Reset the animation component to its initial state, including all parameters. The system will be paused.
transition(to: string, time?: number, transitionOffset?: number): void
Transition to any state in the current layers graph. Transitions can be instant or take an optional blend time.
Parameters
to (string): The state that this transition will transition to.time (number, optional, default 0): The duration of the transition in seconds. Defaults to 0.transitionOffset (number, optional, default null): If provided, the destination state will begin playing
its animation at this time. Given in normalized time, based on the states duration & must be
between 0 and 1. Defaults to null.Class · extends ComponentSystem · category: Animation
Manages the AnimComponents of an application and advances their state graphs each
frame. Reach it through app.systems.anim; components are created with
Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Animation
Animation curve links an input data set to an output data set and defines the interpolation method to use. The paths name the targets the curve drives, input and output index into the owning AnimTrack's keyframe time and value data, and interpolation is one of INTERPOLATION_STEP, INTERPOLATION_LINEAR or INTERPOLATION_CUBIC.
new AnimCurve(paths: AnimCurvePath[], input: number, output: number, interpolation: number)
Create a new animation curve.
Parameters
paths (AnimCurvePath[]): Array of paths identifying the targets of this curve, for
example the local position of a node.
input (number): Index of the curve which specifies the key data.
output (number): Index of the curve which specifies the value data.
interpolation (number): The interpolation method to use. One of the following:
get input(): number
The index of the AnimTrack input which contains the key data for this curve.
get interpolation(): number
The interpolation method used by this curve.
get output(): number
The index of the AnimTrack input which contains the key data for this curve.
get paths(): AnimCurvePath[]
The list of paths which identify targets of this curve.
Class · category: Animation
Wraps a set of data used in animation: a flat data array read components values at a time, so a three-component set holds positions and a four-component set holds quaternions. An AnimTrack keeps its keyframe times and values as AnimData that its curves index into.
new AnimData(components: number, data: number[] | Float32Array<ArrayBufferLike>)
Create a new animation AnimData instance.
Parameters
components (number): Specifies how many components make up an element of data. For
example, specify 3 for a set of 3-dimensional vectors. The number of elements in data array
must be a multiple of components.data (number[] | Float32Array<ArrayBufferLike>): The set of data.get components(): number
Gets the number of components that make up an element.
get data(): number[] | Float32Array<ArrayBufferLike>
Gets the data.
Class · category: Animation
AnimEvents stores a sorted array of animation events which should fire sequentially during the
playback of an AnimTrack. Each event is an object with a name and a time in
seconds plus any extra properties you attach. When playback passes an event's time it is fired
on the AnimComponent under the event's name, so a script listens with
entity.anim.on('footstep', callback) and receives the event object.
new AnimEvents(events: any[])
Create a new AnimEvents instance.
Parameters
events (any[]): An array of animation events.Example
const events = new AnimEvents([
{
name: 'my_event',
time: 1.3, // given in seconds
// any additional properties added are optional and will be available in the EventHandler callback's event object
myProperty: 'test',
myOtherProperty: true
}
]);
animTrack.events = events;
Class · category: Animation
AnimNodes are used to represent a single animation track in the current state. Each state can contain multiple AnimNodes, in which case they are stored in a BlendTree hierarchy, which will control the weight (contribution to the states final animation) of its child AnimNodes.
animTrack is the clip the node plays, speed multiplies its playback rate, and
weight is set by the parent blend tree, or is one for a node that is the state's only
animation.
new AnimNode(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | number[], speed?: number)
Create a new AnimNode instance.
Parameters
state (AnimState): The AnimState that this BlendTree belongs to.parent (AnimBlendTree | null): The parent of the AnimNode. If not null, the AnimNode
is stored as part of an AnimBlendTree hierarchy.name (string): The name of the AnimNode. Used when assigning an AnimTrack to
it.point (number | number[]): The coordinate/vector that's used to determine the weight of
this node when it's part of an AnimBlendTree.speed (number, optional, default 1): The speed that its AnimTrack should play at. Defaults to 1.Class · category: Animation
Defines a single state that the controller can be in. Each state contains either a single AnimNode or an AnimBlendTree of multiple AnimNodes, which will be used to animate the Entity while the state is active. An AnimState will stay active and play as long as there is no AnimTransition with its conditions met that has that AnimState as its source state.
speed and loop control the playback of the state's tracks. States are defined in
the AnimStateGraph and entered either by a transition or directly with
AnimComponentLayer#play.
new AnimState(controller: AnimController, name: string, speed?: number, loop?: boolean, blendTree?: any)
Create a new AnimState instance.
Parameters
controller (AnimController): The controller this AnimState is associated with.name (string): The name of the state. Used to find this state when the controller
transitions between states and links animations.speed (number, optional, default 1): The speed animations in the state should play at. Individual
AnimNodes can override this value.loop (boolean, optional, default true): Determines whether animations in this state should loop.blendTree (any, optional): If supplied, the AnimState will recursively build a
AnimBlendTree hierarchy, used to store, blend and play multiple animations.Class · category: Animation
An asset resource which represents an anim state graph. It can be loaded into an anim component using the AnimComponent#loadStateGraph method.
The graph is data, not behavior. It lists its layers, each with its states, the
transitions between them and their conditions, and the parameters those conditions read.
Loading it into a component builds the runtime AnimState, AnimTransition and
AnimBlendTree objects, and AnimComponent#assignAnimation then attaches an
AnimTrack to each state. One graph can drive any number of components.
Scripts can retrieve an AnimStateGraph instance from assets of type 'animstategraph'. An AnimStateGraph can then be loaded into an anim component as follows:
const animStateGraph = app.assets.get(ASSET_ID).resource;
const entity = new Entity();
entity.addComponent('anim');
entity.anim.loadStateGraph(animStateGraph);
Class · category: Animation
An AnimTrack stores the curve data necessary to animate a set of target nodes. It can be linked to the nodes it should animate using the AnimComponent#assignAnimation method.
A track is the engine's animation clip: a name, a duration in seconds and a list
of curves, each of which reads keyframe times from one of the inputs and values
from one of the outputs, and writes the result to a target path such as a node's local
position or a component property. Optional events fire at set times during playback.
Tracks come from animation assets, GLB animations among them, and are what an
AnimState plays; one track can be assigned in any number of components.
static EMPTY: AnimTrack
This AnimTrack can be used as a placeholder track when creating a state graph before having all associated animation data available.
get curves(): AnimCurve[]
Gets the list of curves contained in the AnimTrack.
get duration(): number
Gets the duration of the AnimTrack.
get events(): AnimEvents
set events(animEvents: AnimEvents)
Gets the animation events that will fire during the playback of this anim track.
get inputs(): AnimData[]
Gets the list of curve key data contained in the AnimTrack.
get name(): string
Gets the name of the AnimTrack.
get outputs(): AnimData[]
Gets the list of curve values contained in the AnimTrack.
Class · category: Animation
AnimTransitions represent connections in the controllers state graph between AnimStates. During each frame, the controller tests to see if any of the AnimTransitions have the current AnimState as their source (from) state. If so and the AnimTransitions parameter based conditions are met, the controller will transition to the destination state.
Each condition compares a parameter with a value using one of the predicates such as
ANIM_GREATER_THAN or ANIM_EQUAL_TO. time is the blend duration,
exitTime restricts the transition to a point in the source state's playback,
priority orders transitions whose conditions pass together, and
interruptionSource says which other transitions may cut this one short. A transition
may also start from the ANIM_STATE_ANY state so that it applies from every state.
new AnimTransition(options: object)
Create a new AnimTransition.
Parameters
options (object): Options.
options.conditions (any[], optional, default []): A list of conditions which must pass for this
transition to be used. Defaults to [].options.exitTime (number, optional, default null): If provided, this transition will only be active for
the exact frame during which the source states progress passes the time specified. Given as
a normalized value of the source states duration. Values less than 1 will be checked every
animation loop. Defaults to null.options.from (string): The state that this transition will exit from.options.interruptionSource (string, optional, default ANIM_INTERRUPTION_NONE): Defines whether another transition can
interrupt this one and which of the current or previous states transitions can do so. One of
ANIM_INTERRUPTION_*. Defaults to ANIM_INTERRUPTION_NONE.options.priority (number, optional, default 0): Used to sort all matching transitions in ascending
order. The first transition in the list will be selected. Defaults to 0.options.time (number, optional, default 0): The duration of the transition in seconds. Defaults to 0.options.to (string): The state that this transition will transition to.options.transitionOffset (number, optional, default null): If provided, the destination state will begin
playing its animation at this time. Given in normalized time, based on the state's duration
and must be between 0 and 1. Defaults to null.Class · category: Animation (Legacy)
An Animation contains the data that defines how a Skeleton animates over time. The Animation contains an array of AnimationNodes, where each AnimationNode targets a specific GraphNode referenced by a Skeleton.
An Animation can be played back by an AnimationComponent.
new Animation()
Create a new Animation instance.
duration: number = 0
Duration of the animation in seconds.
name: string = ''
Human-readable name of the animation.
get nodes(): AnimationNode[]
A read-only property to get array of animation nodes.
addNode(node: AnimationNode): void
Adds a node to the internal nodes array.
Parameters
node (AnimationNode): The node to add.getNode(name: string): AnimationNode
Gets a AnimationNode by name.
Parameters
name (string): The name of the AnimationNode.Returns AnimationNode: The AnimationNode with the specified name.
Class · extends Component · category: Animation (Legacy)
The AnimationComponent enables an Entity to play back skeletal animations on a model. It is a legacy component that has largely been superseded by AnimComponent, which supports more advanced features such as animation state graphs and blending.
You should never need to use the AnimationComponent constructor directly. To add an AnimationComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('animation', {
assets: [animationAsset.id],
speed: 1
});
Once the AnimationComponent is added to the entity, you can access it via the Entity#animation property:
entity.animation.speed = 2; // Play the animation at double speed
console.log(entity.animation.speed); // Get the playback speed and print it
activate: boolean = true
If true, the first animation asset will begin playing when the scene is loaded.
skeleton: Skeleton | null = null
Get the skeleton for the current model. If the model is loaded from glTF/glb, then the skeleton is null.
speed: number = 1
Speed multiplier for animation play back. 1 is playback at normal speed and 0 pauses the animation.
get animations(): {}
set animations(value: {})
Gets the dictionary of animations by name.
get assets(): (number | Asset<string>)[]
set assets(value: (number | Asset<string>)[])
Gets the array of animation assets or asset ids.
get currentTime(): number
set currentTime(currentTime: number)
Gets the current time position (in seconds) of the animation.
get duration(): number
Gets the duration in seconds of the current animation. Returns 0 if no animation is playing.
get loop(): boolean
set loop(value: boolean)
Gets whether the animation will restart from the beginning when it reaches the end.
getAnimation(name: string): Animation
Return an animation.
Parameters
name (string): The name of the animation asset.Returns Animation: An Animation.
play(name: string, blendTime?: number): void
Start playing an animation.
Parameters
name (string): The name of the animation asset to begin playing.blendTime (number, optional, default 0): The time in seconds to blend from the current
animation state to the start of the animation being set. Defaults to 0.entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Animation (Legacy)
Manages the AnimationComponents of an application, the legacy animation system. Reach
it through app.systems.animation; components are created with Entity#addComponent,
never by calling the system directly. New work should use AnimComponent.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Animation (Legacy)
AnimationNode represents an array of keyframes that animate the transform of a GraphNode over time. Typically, an Animation maintains a collection of AnimationNodes, one for each GraphNode in a Skeleton.
new AnimationNode()
Create a new AnimationNode instance.
Class · category: Animation (Legacy)
Represents a skeleton used to play animations.
new Skeleton(graph: GraphNode)
Create a new Skeleton instance.
Parameters
looping: boolean = true
Determines whether skeleton is looping its animation.
get animation(): Animation
set animation(value: Animation)
Gets the animation on the skeleton.
get currentTime(): number
set currentTime(value: number)
Gets the current time of the currently active animation in seconds.
get numNodes(): number
Gets the number of nodes in the skeleton.
addTime(delta: number): void
Progresses the animation assigned to the specified skeleton by the supplied time delta. If the delta takes the animation passed its end point, if the skeleton is set to loop, the animation will continue from the beginning. Otherwise, the animation's current time will remain at its duration (i.e. the end).
Parameters
delta (number): The time in seconds to progress the skeleton's animation.blend(skel1: Skeleton, skel2: Skeleton, alpha: number): void
Blends two skeletons together.
Parameters
skel1 (Skeleton): Skeleton holding the first pose to be blended.skel2 (Skeleton): Skeleton holding the second pose to be blended.alpha (number): The value controlling the interpolation in relation to the two input
skeletons. The value is in the range 0 to 1, 0 generating skel1, 1 generating skel2 and
anything in between generating a spherical interpolation between the two.setGraph(graph: GraphNode): void
Links a skeleton to a node hierarchy. The nodes animated skeleton are then subsequently used to drive the local transformation matrices of the node hierarchy.
Parameters
graph (GraphNode): The root node of the graph that the skeleton is to drive.updateGraph(): void
Synchronizes the currently linked node hierarchy with the current state of the skeleton. Internally, this function converts the interpolated keyframe at each node in the skeleton into the local transformation matrix at each corresponding node in the linked node hierarchy.
Class · extends ResourceHandler · category: Asset
Resource handler for the animation asset type. Loads an AnimTrack from a GLB file, or
a legacy Animation from a PlayCanvas JSON animation file.
protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidopen(url: string, data: any, asset?: Asset<string>): anypatch(asset: Asset<string>, assets: AssetRegistry): voidremoveParser(parser: ResourceParser): voidClass · extends EventHandler · category: Asset
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.
Example
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;
});
template
new Asset<K extends string & {} | AssetType>(name: string, type: K, file?: object, data?: any, options?: object)
Create a new Asset record. Add it to the AssetRegistry with AssetRegistry#add so the application can find and load it.
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:
ArrayBufferstringstringstringstringTypes 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.
file (object, optional): 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.
file.contents (ArrayBuffer, optional): Optional file contents. This is faster than wrapping
the data in a (base64 encoded) blob. Currently only used by container assets.file.filename (string, optional): The filename of the resource file or null if no filename
was set (e.g from using AssetRegistry#loadFromUrl).file.hash (string, optional): 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).file.size (number, optional): The size of the resource file or null if no size was set
(e.g. from using AssetRegistry#loadFromUrl).file.url (string, optional): The URL of the resource file that contains the asset data.data (any, optional, default {}): 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).
options (object, optional, default {}): The asset handler options. For container options see
ContainerHandler.
options.crossOrigin ("anonymous" | "use-credentials" | null, optional): For use with texture assets
that are loaded using the browser. This setting overrides the default crossOrigin specifier.
For more details on crossOrigin and its use, see
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin.Example
// 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
set data(value: any)
Gets optional asset JSON data.
get file(): any
set file(value: any)
Gets the file details or null if no file.
get name(): string
set name(value: string)
Gets the asset name.
get preload(): boolean
set preload(value: boolean)
Gets whether to preload an asset.
get resource(): AssetResource<K> | undefined
set resource(value: AssetResource<K>)
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.
get resources(): AssetResource<K>[]
set resources(value: AssetResource<K>[])
Gets the asset resources. For a cube map asset, the first entry is the cube map and the
remaining entries are its prefiltered levels, some of which may be null.
getFileUrl(): string | null
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.
Example
const asset = app.assets.find("My Image", "texture");
const img = "<img src='" + asset.getFileUrl() + "'>";
ready(callback: AssetReadyCallback<K>, scope?: any): void
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.scope (any, optional): Scope object to use when calling the callback.Example
const asset = app.assets.find("My Asset");
asset.ready((asset) => {
// asset loaded
});
app.assets.load(asset);
unload(): void
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.
Example
const asset = app.assets.find("My Asset");
asset.unload();
// asset.resource is null
static EVENT_ADDLOCALIZED: string = 'add:localized'
Fired when we add a new localized asset id to the asset.
Example
asset.on('add:localized', (locale, assetId) => {
console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`);
});
static EVENT_CHANGE: string = 'change'
Fired when one of the asset properties file, data, resource or resources is changed.
Example
asset.on('change', (asset, property, newValue, oldValue) => {
console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`);
});
static EVENT_ERROR: string = 'error'
Fired if the asset encounters an error while loading.
Example
asset.on('error', (err, asset) => {
console.error(`Error loading asset ${asset.name}: ${err}`);
});
static EVENT_LOAD: string = 'load'
Fired when the asset has completed loading.
Example
asset.on('load', (asset) => {
console.log(`Asset loaded: ${asset.name}`);
});
static 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:
asset.file.contents is supplied, so no progress is reportedExample
asset.on('progress', (receivedBytes, totalBytes) => {
console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`);
});
static EVENT_REMOVE: string = 'remove'
Fired when the asset is removed from the asset registry.
Example
asset.on('remove', (asset) => {
console.log(`Asset removed: ${asset.name}`);
});
static EVENT_REMOVELOCALIZED: string = 'remove:localized'
Fired when we remove a localized asset id from the asset.
Example
asset.on('remove:localized', (locale, assetId) => {
console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`);
});
static 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.
Example
asset.on('unload', (asset) => {
console.log(`Asset about to unload: ${asset.name}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Asset
An AssetListLoader loads a group of assets together and reports once when every one of them has loaded or failed. Pass it Asset instances or asset ids. Assets not yet in the AssetRegistry are added, and ids that the registry does not know yet are waited for until a matching asset is registered. Call load to start loading and ready to be told when the list is complete without starting anything.
Example
const assets = [
new Asset('model', 'container', { url: 'http://example.com/asset.glb' }),
new Asset('styling', 'css', { url: 'http://example.com/asset.css' })
];
const assetListLoader = new AssetListLoader(assets, app.assets);
assetListLoader.load((err, failed) => {
if (err) {
console.error(`${failed.length} assets failed to load`);
} else {
console.log(`${assets.length} assets loaded`);
}
});
new AssetListLoader(assetList: number[] | Asset<string>[], assetRegistry: AssetRegistry)
Create a new AssetListLoader using a list of assets to load and the asset registry used to load and manage them.
Parameters
assetList (number[] | Asset<string>[]): An array of Asset objects to load or an array
of Asset IDs to load.assetRegistry (AssetRegistry): The application's asset registry.Example
const assetListLoader = new AssetListLoader([
new Asset("texture1", "texture", { url: 'http://example.com/my/assets/here/texture1.png' }),
new Asset("texture2", "texture", { url: 'http://example.com/my/assets/here/texture2.png' })
], app.assets);
destroy(): void
Removes all references to this asset list loader.
load(done: Function, scope?: any): void
Start loading asset list and call done() when all assets have loaded or failed to load.
Parameters
done (Function): Callback called when all assets in the list are loaded. Passed
(err, failed) where err is undefined if no errors are encountered and failed contains
an array of assets that failed to load.scope (any, optional): Scope to use when calling callback.ready(done: Function, scope?: any): void
Sets a callback which will be called when all assets in the list have been loaded.
Parameters
done (Function): Callback called when all assets in the list are loaded.scope (any, optional): Scope to use when calling callback.fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Asset
An AssetReference follows a single asset slot on behalf of its owner, such as the texture
property of a component, and calls back when that asset is added to the registry, loads or is
removed. Point it at an asset by setting id or url. The asset does not need to
exist yet: the add callback fires when an asset with that id or URL is later registered. The
unload callback is delivered only for a reference by id.
Example
const reference = new AssetReference('textureAsset', this, this.app.assets, {
load: this.onTextureAssetLoad,
remove: this.onTextureAssetRemove
}, this);
reference.id = this.textureAsset.id;
new AssetReference(propertyName: string, parent: any, registry: AssetRegistry, callbacks: object, scope?: any)
Create a new AssetReference instance.
Parameters
propertyName (string): The name of the property that the asset is stored under,
passed into callbacks to enable updating.parent (any): The parent object that contains the asset reference, passed
into callbacks to enable updating. Currently an asset, but could be component or other.registry (AssetRegistry): The asset registry that stores all assets.callbacks (object): A set of functions called when the asset state changes: load,
add, remove.
callbacks.add (any, optional): The function called when the asset is added to the
registry add(propertyName, parent, asset).callbacks.load (any, optional): The function called when the asset loads
load(propertyName, parent, asset).callbacks.remove (any, optional): The function called when the asset is remove from the
registry remove(propertyName, parent, asset).callbacks.unload (any, optional): The function called when the asset is unloaded
unload(propertyName, parent, asset).scope (any, optional): The scope to call the callbacks in.Example
const reference = new AssetReference('textureAsset', this, this.app.assets, {
load: this.onTextureAssetLoad,
add: this.onTextureAssetAdd,
remove: this.onTextureAssetRemove
}, this);
reference.id = this.textureAsset.id;
get id(): number | null
set id(value: number | null)
Gets the asset id which this references.
get url(): string | null
set url(value: string | null)
Gets the asset url which this references.
Class · extends EventHandler · category: Asset
The AssetRegistry holds every Asset an application knows about and drives their loading through the ResourceLoader. Each application has one at AppBase#assets.
Look assets up by id with get, by name and type with find and findAll, by URL with getByUrl, or by tag with findByTag. Register an asset with add, or create and load one in a single call with loadFromUrl, which reuses any asset already registered for that URL.
Adding an asset does not fetch it unless Asset#preload is true. Call load to
fetch it, then wait with Asset#ready or listen for the registry's load, error, add
and remove events. Each also fires per asset as load:[id] and, except for error, per URL as
load:url:[url].
Example
const asset = app.assets.find('brick', 'texture');
app.assets.load(asset);
asset.ready((asset) => {
material.diffuseMap = asset.resource;
});
Example
app.assets.loadFromUrl('models/robot.glb', 'container', (err, asset) => {
app.root.addChild(asset.resource.instantiateRenderEntity());
});
new AssetRegistry(loader: ResourceLoader)
Create an instance of an AssetRegistry.
Parameters
loader (ResourceLoader): The ResourceLoader used to load the asset files.bundles: BundleRegistry | null = null
The bundle registry that tracks which assets are packed into bundle assets and serves their files from loaded bundles. Assigned when the application creates its bundle registry; null until then.
prefix: string | null = null
A URL prefix that will be added to all asset loading requests.
add(asset: Asset<string>): void
Add an asset to the registry. If Asset#preload is true, it will also get loaded.
Parameters
asset (Asset<string>): The asset to add.Example
const asset = new Asset("My Asset", "texture", {
url: "../path/to/image.jpg"
});
app.assets.add(asset);
filter(callback: FilterAssetCallback): Asset<string>[]
Return all Assets that satisfy a filter callback.
Parameters
callback (FilterAssetCallback): The callback function that is used to filter assets.
Return true to include an asset in the returned array.Returns Asset<string>[]: A list of all Assets found.
Example
const assets = app.assets.filter(asset => asset.name.includes('monster'));
console.log(`Found ${assets.length} assets with a name containing 'monster'`);
find<K extends string & {} | AssetType>(name: string, type: K): Asset<K> | null
Return the first Asset with the specified name and type found in the registry.
The type also types the result: find('brick', 'texture') returns
Asset<'texture'> | null, whose resource is a Texture. See AssetMap.
Parameters
name (string): The name of the Asset to find.type (K): The type of the Asset to find (an AssetType).Returns Asset<K> | null: A single Asset or null if no Asset is found.
Example
const asset = app.assets.find("myTextureAsset", "texture");
if (asset) {
const texture = asset.resource; // a Texture
}
find(name: string, type?: string): Asset<string> | null
Return the first Asset with the specified name found in the registry, of any type or of a
type only known as a string. The result is a plain Asset, whose resource is unknown.
Parameters
name (string): The name of the Asset to find.type (string, optional): The type of the Asset to find.Returns Asset<string> | null: A single Asset or null if no Asset is found.
Example
const asset = app.assets.find("myAsset");
findAll<K extends string & {} | AssetType>(name: string, type: K): Asset<K>[]
Return all Assets with the specified name and type found in the registry.
The type also types the result, as for AssetRegistry#find:
findAll('brick', 'texture') returns Asset<'texture'>[].
Parameters
name (string): The name of the Assets to find.type (K): The type of the Assets to find (an AssetType).Returns Asset<K>[]: A list of all Assets found.
Example
const assets = app.assets.findAll('brick', 'texture');
console.log(`Found ${assets.length} texture assets named 'brick'`);
const textures = assets.map(asset => asset.resource); // Texture[]
findAll(name: string, type?: string): Asset<string>[]
Return all Assets with the specified name found in the registry, of any type or of a type
only known as a string.
Parameters
name (string): The name of the Assets to find.type (string, optional): The type of the Assets to find.Returns Asset<string>[]: A list of all Assets found.
Example
const assets = app.assets.findAll('brick');
findByTag(...query: any[]): Asset<string>[]
Return all Assets that satisfy the search query. Query can be simply a string, or comma separated strings, to have inclusive results of assets that match at least one query. A query that consists of an array of tags can be used to match assets that have each tag of array.
Parameters
query (any[]): Name of a tag or array of tags.Returns Asset<string>[]: A list of all Assets matched query.
Example
const assets = app.assets.findByTag("level-1");
// returns all assets that tagged by `level-1`
Example
const assets = app.assets.findByTag("level-1", "level-2");
// returns all assets that tagged by `level-1` OR `level-2`
Example
const assets = app.assets.findByTag(["level-1", "monster"]);
// returns all assets that tagged by `level-1` AND `monster`
Example
const assets = app.assets.findByTag(["level-1", "monster"], ["level-2", "monster"]);
// returns all assets that tagged by (`level-1` AND `monster`) OR (`level-2` AND `monster`)
get(id: number): Asset<string> | undefined
Retrieve an asset from the registry by its id field.
Parameters
id (number): The id of the asset to get.Returns Asset<string> | undefined: The asset.
Example
const asset = app.assets.get(100);
getByUrl(url: string): Asset<string> | undefined
Retrieve an asset from the registry by its file's URL field.
Parameters
url (string): The url of the asset to get.Returns Asset<string> | undefined: The asset.
Example
const asset = app.assets.getByUrl("../path/to/image.jpg");
list(filters?: object): Asset<string>[]
Create a filtered list of assets from the registry.
Parameters
filters (object, optional, default {}): Filter options.
filters.preload (boolean, optional): Filter by preload setting.Returns Asset<string>[]: The filtered list of assets.
load(asset: Asset<string>, options?: object): void
Load the asset's file from a remote source. Listen for load events on the asset to find
out when it is loaded.
Container-backed render assets wait for the container referenced by data.containerAsset
to be registered and loaded before firing load. The container can be registered later,
but if it is never registered, the render asset remains loading indefinitely. If that
render asset is marked for preload, it also prevents AppBase#preload from completing.
Parameters
asset (Asset<string>): The asset to load.options (object, optional): Options for asset loading.
options.bundlesFilter (BundlesFilterCallback, optional): A callback that will be called
when loading an asset that is contained in any of the bundles. It provides an array of
bundles and will ensure asset is loaded from bundle returned from a callback. By default,
the smallest filesize bundle is chosen.options.bundlesIgnore (boolean, optional): If set to true, then asset will not try to load
from a bundle. Defaults to false.options.force (boolean, optional): If set to true, then the check of asset being loaded or
is already loaded is bypassed, which forces loading of asset regardless.Example
// load some assets
const assetsToLoad = [
app.assets.find("My Asset"),
app.assets.find("Another Asset")
];
let count = 0;
assetsToLoad.forEach((assetToLoad) => {
assetToLoad.ready((asset) => {
count++;
if (count === assetsToLoad.length) {
// done
}
});
app.assets.load(assetToLoad);
});
loadFromUrl<K extends string & {} | AssetType>(url: string, type: K, callback: LoadAssetCallback<K>): void
Use this to load and create an asset if you don't have assets created. Usually you would only use this if you are not integrated with the PlayCanvas Editor.
The type also types the loaded asset: loadFromUrl(url, 'texture', callback) passes an
Asset<'texture'> to callback, whose resource is a Texture. See AssetMap.
An asset already registered for the URL is reused, whatever its type, so load a URL as one
type only; otherwise the callback can receive an asset of another type than requested.
Parameters
url (string): The url to load.type (K): The type of asset to load (an AssetType).callback (LoadAssetCallback<K>): Function called when asset is loaded, passed (err,
asset), where err is null if no errors were encountered.Example
app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) {
const texture = asset.resource; // a Texture
});
loadFromUrlAndFilename<K extends string & {} | AssetType>(url: string, filename: string, type: K, callback: LoadAssetCallback<K>): void
Use this to load and create an asset when both the URL and filename are required. For example, use this function when loading BLOB assets, where the URL does not adequately identify the file.
Parameters
url (string): The url to load.filename (string): The filename of the asset to load.type (K): The type of asset to load (an AssetType).callback (LoadAssetCallback<K>): Function called when asset is loaded, passed (err,
asset), where err is null if no errors were encountered.Example
const file = magicallyObtainAFile();
app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) {
const texture = asset.resource; // a Texture
});
remove(asset: Asset<string>): boolean
Remove an asset from the registry.
Parameters
asset (Asset<string>): The asset to remove.Returns boolean: True if the asset was successfully removed and false otherwise.
Example
const asset = app.assets.get(100);
app.assets.remove(asset);
static EVENT_ADD: string = 'add'
Fired when an asset is added to the registry. This event is available in three forms. They are as follows:
add - Fired when any asset is added to the registry.add:[id] - Fired when an asset is added to the registry, where [id] is the unique id
of the asset.add:url:[url] - Fired when an asset is added to the registry and matches the URL
[url], where [url] is the URL of the asset.Example
app.assets.on('add', (asset) => {
console.log(`Asset added: ${asset.name}`);
});
Example
const id = 123456;
app.assets.on('add:' + id, (asset) => {
console.log(`Asset added: ${asset.name}`);
});
Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('add:url:' + asset.file.url, (asset) => {
console.log(`Asset added: ${asset.name}`);
});
static EVENT_ERROR: string = 'error'
Fired when an error occurs during asset loading. This event is available in two forms. They are as follows:
error - Fired when any asset reports an error in loading.error:[id] - Fired when an asset reports an error in loading, where [id] is the
unique id of the asset.Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error', (err, asset) => {
console.error(err);
});
app.assets.load(asset);
Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error:' + id, (err, asset) => {
console.error(err);
});
app.assets.load(asset);
static EVENT_LOAD: string = 'load'
Fired when an asset completes loading. This event is available in three forms. They are as follows:
load - Fired when any asset finishes loading.load:[id] - Fired when a specific asset has finished loading, where [id] is the
unique id of the asset.load:url:[url] - Fired when an asset finishes loading whose URL matches [url], where
[url] is the URL of the asset.Example
app.assets.on('load', (asset) => {
console.log(`Asset loaded: ${asset.name}`);
});
Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:' + id, (asset) => {
console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);
Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:url:' + asset.file.url, (asset) => {
console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);
static EVENT_REMOVE: string = 'remove'
Fired when an asset is removed from the registry. This event is available in three forms. They are as follows:
remove - Fired when any asset is removed from the registry.remove:[id] - Fired when an asset is removed from the registry, where [id] is the
unique id of the asset.remove:url:[url] - Fired when an asset is removed from the registry and matches the
URL [url], where [url] is the URL of the asset.Example
app.assets.on('remove', (asset) => {
console.log(`Asset removed: ${asset.name}`);
});
Example
const id = 123456;
app.assets.on('remove:' + id, (asset) => {
console.log(`Asset removed: ${asset.name}`);
});
Example
const id = 123456;
const asset = app.assets.get(id);
app.assets.on('remove:url:' + asset.file.url, (asset) => {
console.log(`Asset removed: ${asset.name}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ResourceHandler · category: Asset
Resource handler for the audio asset type. Decodes any audio format the browser supports, such
as MP3, OGG and WAV, into a Sound through the application's SoundManager.
protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidopen(url: string, data: any, asset?: Asset<string>): anypatch(asset: Asset<string>, assets: AssetRegistry): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the container asset type. Loads glTF and GLB files, whose meshes,
materials, textures, animations and Gaussian splats become one ContainerResource.
For glTF files, the asset options object can be used to pass load time callbacks for handling the various resources at different stages of loading. The table below lists the resource types and the corresponding supported process functions.
| resource | preprocess | process | processAsync | postprocess |
|---|---|---|---|---|
| global | √ | √ | ||
| node | √ | √ | √ | |
| light | √ | √ | √ | |
| camera | √ | √ | √ | |
| animation | √ | √ | ||
| material | √ | √ | √ | |
| image | √ | √ | √ | |
| texture | √ | √ | √ | |
| buffer | √ | √ | √ | |
| bufferView | √ | √ | √ |
Additional options that can be passed for glTF files: [options.morphPreserveData] - When true, the morph target keeps its data passed using the options, allowing the clone operation. [options.morphPreferHighPrecision] - When true, high precision storage for morph targets should be preferred. This is faster to create and allows higher precision, but takes more memory and might be slower to render. Defaults to false. [options.skipMeshes] - When true, the meshes and gaussian splats from the container are not created. This can be useful if you only need access to textures or animations and similar.
For example, to receive a texture preprocess callback:
const containerAsset = new Asset(filename, 'container', { url: url, filename: filename }, null, {
texture: {
preprocess: (gltfTexture) => {
console.log("texture preprocess");
}
}
});
protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidopen(url: string, data: any, asset?: Asset<string>): anypatch(asset: Asset<string>, assets: AssetRegistry): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the cubemap asset type. Assembles a cube map Texture from six
face texture assets, from a prefiltered environment file, or both, and stores the results in
Asset#resources.
load(url: any, callback: any, asset: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.asset (any): Optional asset that is passed by ResourceLoader.open(url: any, data: any, asset: any): any
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.asset (any): Optional asset that is passed by ResourceLoader.Returns any: The parsed resource data.
patch(asset: any, registry: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.registry (any)protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the font asset type. Loads a Font from a JSON glyph description
and the texture pages that accompany it. Bitmap fonts and multi-channel signed distance field
fonts are both supported.
load(url: any, callback: any, asset: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.asset (any): Optional asset that is passed by ResourceLoader.open(url: any, data: any, asset: any): Font
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.asset (any): Optional asset that is passed by ResourceLoader.Returns Font: The parsed resource data.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the material asset type. Loads material JSON into a
StandardMaterial and binds the texture assets it references. A custom parser may
produce another kind of Material.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidopen(url: string, data: any, asset?: Asset<string>): anyremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the model asset type. Loads legacy PlayCanvas JSON models and GLB files
into a Model. OBJ files are supported once the ObjModelParser shipped in
playcanvas/scripts/esm/parsers/obj-model.mjs is registered with
ResourceHandler#addParser.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidopen(url: string, data: any, asset?: Asset<string>): anyremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the render asset type. A render asset has no file of its own: it takes
the meshes of one glTF mesh from the container asset named in its data and exposes them as a
Render.
load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): void
Waits for a render asset's container to supply its meshes. Without an asset, completes with no render data.
Parameters
url (string | { load: string; original: string }): The resource URL. Not used for
container-backed render assets.callback (ResourceHandlerCallback): Called with the container's render data or an error.asset (Asset<string>, optional): The render asset whose container dependency should be loaded.open(url: any, data: any): Render
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.Returns Render: The parsed resource data.
patch(asset: any, registry: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.registry (any)protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · category: Asset
A ResourceHandler loads and opens resources of one asset type on behalf of the ResourceLoader. The engine ships a handler for every built-in AssetType, and an application registers the ones listed in AppOptions#resourceHandlers, so a hand-configured AppBase may support only some types. Register your own with ResourceLoader#addHandler to add a new type.
A handler works in two steps. load fetches the raw data for a URL and open turns that data into the resource stored on Asset#resource. A handler may also implement patch to resolve references to other assets once the resource exists. Rather than overriding those methods, a handler can register one ResourceParser per file format with addParser and let the base class pick the parser that claims the file.
Example
class CsvHandler extends ResourceHandler {
constructor(app) {
super(app, 'csv');
}
load(url, callback) {
this.fetch(url, 'text', callback);
}
open(url, data) {
return data.split('\n').map(line => line.split(','));
}
}
app.loader.addHandler('csv', new CsvHandler(app));
new ResourceHandler(app: AppBase, handlerType: string)
Parameters
app (AppBase): The running AppBase.handlerType (string): The type of the resource the handler handles.protected _app: AppBase
The running app instance.
handlerType: string = ''
Type of the resource the handler handles.
get app(): AppBase
Gets the running AppBase instance.
get maxRetries(): number
set maxRetries(value: number)
Gets the number of times to retry a failed request for the resource.
get parsers(): ResourceParser[]
Gets a read-only copy of the registered parsers.
addParser(parser: ResourceParser, decider?: any): void
Registers a ResourceParser for this handler. Parsers are consulted newest-first: the most recently added parser whose ResourceParser#canParse returns true is selected. This lets a later registration override a built-in parser for the same format.
Register parsers before starting loads for this handler's type - selection runs for both the load and open phases, so changing the registry while loads are in flight can route them inconsistently. Note that handlers that implement their own loading without consulting registered parsers (for example cubemap or font) ignore registered parsers.
Parameters
parser (ResourceParser): The parser to register. Must implement canParse(context).decider (any, optional): Removed. Previously a (url, data) => boolean selector; implement
canParse(context) on the parser instead. If passed, it is ignored and logs a warning.Example
app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice));
fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): void
Fetches a resource's raw data using this handler's retry settings, reusing pre-fetched
asset.file.contents when available. A convenience for a ResourceParser's load method,
so parsers don't reimplement the fetch boilerplate.
Parameters
url (string | { load: string; original: string }): The resource URL, or a load/original
structure.responseType (string): The Http response type to fetch as (for example
Http.ResponseType.ARRAY_BUFFER for a binary format, or Http.ResponseType.TEXT).callback (ResourceHandlerCallback): Called with (err, data) when the fetch completes.asset (Asset<string>, optional): The asset being loaded, used to reuse already-fetched contents.load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (string | { load: string; original: string }): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (ResourceHandlerCallback): The callback used when the resource is loaded or
an error occurs.asset (Asset<string>, optional): Optional asset that is passed by ResourceLoader.open(url: string, data: any, asset?: Asset<string>): any
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (string): The URL of the resource to open.data (any): The raw resource data passed by callback from load.asset (Asset<string>, optional): Optional asset that is passed by ResourceLoader.Returns any: The parsed resource data.
patch(asset: Asset<string>, assets: AssetRegistry): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (Asset<string>): The asset to patch.assets (AssetRegistry): The asset registry.removeParser(parser: ResourceParser): void
Removes a previously registered ResourceParser.
Parameters
parser (ResourceParser): The parser to remove.Class · category: Asset
The ResourceLoader turns a URL and an asset type into a loaded resource. It owns one ResourceHandler per type, dispatches each request to the matching handler, and caches the result by URL and type so the same request is fetched once. Each application has one at AppBase#loader.
Most code never calls the loader directly: the AssetRegistry does so on its behalf when an Asset loads. Use the loader to add support for a new asset type with addHandler, to reach an existing handler with getHandler, or to tune requests with maxConcurrentRequests, withCredentials and enableRetry.
Parsers for formats the engine does not load by default ship in the package and are registered on
an existing handler rather than added as one: playcanvas/scripts/esm/parsers/obj-model.mjs adds
.obj model loading and playcanvas/scripts/esm/parsers/spz-parser.mjs adds .spz
Gaussian-splat loading.
Example
app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice));
Example
app.loader.getHandler('gsplat').addParser(new SpzParser(app));
new ResourceLoader(app: AppBase)
Create a new ResourceLoader instance.
Parameters
app (AppBase): The application.get maxConcurrentRequests(): number
set maxConcurrentRequests(value: number)
Gets the maximum number of asset requests that can be in flight at the same time.
get withCredentials(): boolean
set withCredentials(value: boolean)
Gets whether asset requests are sent with credentials.
addHandler(type: string & {} | AssetType, handler: ResourceHandler): void
Add a ResourceHandler for a resource type. Handler should support at least load()
and open(). Handlers can optionally support patch(asset, assets) to handle dependencies on
other assets.
Parameters
type (string & {} | AssetType): The name of the resource type that the handler will
be registered with: one of the built-in AssetType names, such as 'texture', 'model'
or 'container', or a new name for an application-defined handler. See AssetMap for
typing the resource of a new name.handler (ResourceHandler): An instance of a resource handler
supporting at least load() and open().Example
// register a handler for a new 'csv' asset type (see ResourceHandler for the class)
app.loader.addHandler('csv', new CsvHandler(app));
clearCache(url: string, type: string): void
Remove resource from cache.
Parameters
url (string): The URL of the resource.type (string): The type of resource.destroy(): void
Destroys the resource loader.
disableRetry(): void
Disables retrying of failed requests when loading assets.
enableRetry(maxRetries?: number): void
Enables retrying of failed requests when loading assets. Retries use exponential backoff and are also enabled by default for new applications.
Parameters
maxRetries (number, optional, default 5): The maximum number of times to retry loading an asset.
Defaults to 5.getFromCache(url: string, type: string): any
Check cache for resource from a URL. If present, return the cached value.
Parameters
url (string): The URL of the resource to get from the cache.type (string): The type of the resource.Returns any: The resource loaded from the cache.
getHandler(type: string & {} | AssetType): ResourceHandler | undefined
Get a ResourceHandler for a resource type.
Parameters
type (string & {} | AssetType): The name of the resource type that the handler is
registered with.Returns ResourceHandler | undefined: The registered handler, or
undefined if the requested handler is not registered.
load(url: string, type: string, callback: ResourceLoaderCallback, asset?: Asset<string>, options?: object): void
Make a request for a resource from a remote URL. Parse the returned data using the handler for the specified type. When loaded and parsed, use the callback to return an instance of the resource.
Parameters
url (string): The URL of the resource to load.type (string): The type of resource expected.callback (ResourceLoaderCallback): The callback used when the resource is loaded or
an error occurs. Passed (err, resource) where err is null if there are no errors.asset (Asset<string>, optional): Optional asset that is passed into
handler.options (object, optional): Additional options for loading.
options.bundlesFilter (BundlesFilterCallback, optional): A callback that will be called
when loading an asset that is contained in any of the bundles. It provides an array of
bundles and will ensure asset is loaded from bundle returned from a callback. By default,
the smallest filesize bundle is chosen.options.bundlesIgnore (boolean, optional): If set to true, then asset will not try to load
from a bundle. Defaults to false.Example
app.loader.load("../path/to/texture.png", "texture", function (err, texture) {
// use texture here
});
open(type: string, data: any): any
Convert raw resource data into a resource instance. E.g. Take 3D model format JSON and return a Model.
Parameters
type (string): The type of resource.data (any): The raw resource data.Returns any: The parsed resource data.
patch(asset: Asset<string>, assets: AssetRegistry): void
Perform any operations on a resource, that requires a dependency on its asset data or any other asset data.
Parameters
asset (Asset<string>): The asset to patch.assets (AssetRegistry): The asset registry.removeHandler(type: string & {} | AssetType): void
Remove a ResourceHandler for a resource type.
Parameters
type (string & {} | AssetType): The name of the type that the handler will be removed.Class · extends ResourceHandler · category: Asset
Resource handler for the scene asset type. Loads a PlayCanvas scene JSON file, instantiates
its entity hierarchy as the root of AppBase#scene and applies the scene's settings.
load(url: any, callback: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.open(url: any, data: any): Scene
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.Returns Scene: The parsed resource data.
protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidpatch(asset: Asset<string>, assets: AssetRegistry): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for loading JavaScript files dynamically. Two types of JavaScript files can be loaded, PlayCanvas scripts which contain calls to createScript, or regular JavaScript files, such as third-party libraries.
load(url: any, callback: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.open(url: any, data: any): any
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.Returns any: The parsed resource data.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the sprite asset type. Builds a Sprite from sprite JSON, loaded
from a file or supplied as asset data, and binds the TextureAtlas asset it references.
load(url: any, callback: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.open(url: any, data: any): Sprite
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.Returns Sprite: The parsed resource data.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the textureatlas asset type. Loads a texture and its frame definitions
into a TextureAtlas. The frames come from the asset data, or from a JSON file with a
texture of the same name beside it.
load(url: any, callback: any): void
Load a resource from a remote URL. When parsers are registered, the matching parser's load is
used; otherwise the base implementation does nothing (subclasses may override).
Parameters
url (any): Either the URL of the resource to
load or a structure containing the load URL (used for loading the resource) and the original
URL (used for identifying the resource format; necessary when loading, for example, from
a blob URL).callback (any): The callback used when the resource is loaded or
an error occurs.open(url: any, data: any, asset: any): TextureAtlas | null
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.asset (any): Optional asset that is passed by ResourceLoader.Returns TextureAtlas | null: The parsed resource data.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · extends ResourceHandler · category: Asset
Resource handler for the texture asset type. Loads 2D and 3D Texture resources from
any image format the browser decodes, such as PNG, JPEG, WebP and AVIF, and from DDS, KTX,
KTX2, Basis and HDR files.
open(url: any, data: any, asset: any): any
The open function is passed the raw resource data. The handler can then process the data
into a format that can be used at runtime. When parsers are registered, the matching parser's
open is used (if it implements one); otherwise the base implementation simply returns the data.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from load.asset (any): Optional asset that is passed by ResourceLoader.Returns any: The parsed resource data.
patch(asset: any, assets: any): void
The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.
Parameters
asset (any): The asset to patch.assets (any): The asset registry.protected _app: AppBasehandlerType: string = ''get app(): AppBaseget maxRetries(): number · set maxRetries(value: number)get parsers(): ResourceParser[]addParser(parser: ResourceParser, decider?: any): voidfetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): voidload(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): voidremoveParser(parser: ResourceParser): voidClass · category: Debug
MiniStats is a small graphical overlay that displays realtime performance metrics. By default, it shows CPU and GPU durations, frame intervals, draw call count and estimated GPU resource memory. It can also display additional counters from AppBase#stats.
The default CPU timings, including render time, draw call count and memory estimates are available in all builds. GPU timing requires device support and is enabled when MiniStats creates its GPU timer. Some additional counters, such as AppStats#primitiveCount, require a debug or profiler build. See AppStats for measurement scope and availability. In the detailed views, click a category heading to collapse or expand its sub-counters. Click elsewhere in the overlay to change size. Collapsing a category preserves its sampling and graph history. Resources is enabled and collapsed by default, and displays current counts of existing tracked resources, including internal resources, in detailed views. Resource counts refresh at textRefreshRate while visible, including their sum in the collapsed heading; they have no average or peak. In graph views, resource histories use the latest sampled counts and scale to accommodate the highest count seen.
new MiniStats(app: AppBase, options?: MiniStatsOptions)
Create a new MiniStats instance.
Parameters
app (AppBase): The application.options (MiniStatsOptions, optional): Options for the MiniStats instance.Example
const miniStats = new MiniStats(app);
get cpuCollapsed(): boolean
set cpuCollapsed(value: boolean)
get enabled(): boolean
set enabled(value: boolean)
get engineCollapsed(): boolean
set engineCollapsed(value: boolean)
get gpuCollapsed(): boolean
set gpuCollapsed(value: boolean)
get resourcesCollapsed(): boolean
set resourcesCollapsed(value: boolean)
get resourcesEnabled(): boolean
set resourcesEnabled(value: boolean)
get userCollapsed(): boolean
set userCollapsed(value: boolean)
get vramCollapsed(): boolean
set vramCollapsed(value: boolean)
destroy(): void
Destroy the MiniStats instance and release its event listeners, textures and mesh.
Example
miniStats.destroy();
static getDefaultOptions(extraStats?: string[]): MiniStatsOptions
Returns options for three sizes: compact core counters, grouped averages, and grouped averages and peaks with graph history. Engine counters appear first, starting with draw calls and frame time, followed by User, CPU, GPU and VRAM. In the detailed views, Engine and User have collapsible headings, omitted when empty.
Parameters
extraStats (string[], optional, default []): Presets to include: 'gsplats' or 'gsplatsCopy'.Returns MiniStatsOptions: The default options for MiniStats.
Example
const options = MiniStats.getDefaultOptions(['gsplats']);
options.sizes[2].width = 280;
const miniStats = new MiniStats(app, options);
Class · category: Debug
Log tracing functionality, allowing for tracing of the internal functionality of the engine. Note that the trace logging only takes place in the debug build of the engine and is stripped out in other builds.
The debug build ships in the npm package: import from 'playcanvas/debug' instead of
'playcanvas' to enable trace channels, assertions and validation warnings. A
'playcanvas/profiler' build is also available for per-frame timings.
static stack: boolean = false
Enable call stack logging for trace calls. Defaults to false.
static get(channel: string): boolean
Test if the trace channel is enabled.
Parameters
channel (string): Name of the trace channel.Returns boolean: - True if the trace channel is enabled.
static set(channel: string, enabled?: boolean): void
Enable or disable a trace channel.
Parameters
channel (string): Name of the trace channel. Can be:
enabled (boolean, optional, default true): New enabled state for the channel.
Class · category: Exporter
Implementation of the GLTF 2.0 format exporter.
build(entity: Entity, options?: object): Promise<ArrayBuffer>
Converts a hierarchy of entities to GLB format.
Parameters
entity (Entity): The root of the entity hierarchy to convert.options (object, optional, default {}): Object for passing optional arguments.
options.maxTextureSize (number, optional): Maximum texture size. Texture is resized if over the size.
options.stripUnusedAttributes (boolean, optional): If true, removes unused vertex attributes:
Defaults to false.
Returns Promise<ArrayBuffer>: - The GLB file content.
new GltfExporter()Class · category: Exporter
Implementation of the USDZ format exporter. Note that ASCII version of the format (USDA) is used.
build(entity: Entity, options?: object): Promise<ArrayBuffer>
Converts a hierarchy of entities to USDZ format. Skinned meshes are exported in their current pose.
Parameters
entity (Entity): The root of the entity hierarchy to convert.options (object, optional, default {}): Object for passing optional arguments.
options.maxTextureSize (number, optional): Maximum texture size. Texture is resized if over
the size.Returns Promise<ArrayBuffer>: - The USDZ file content.
new UsdzExporter()Class · extends EventHandler · category: Framework
AppBase represents the base functionality for all PlayCanvas applications. It is responsible for initializing and managing the application lifecycle. It coordinates core engine systems such as:
Using AppBase directly requires you to register ComponentSystems and ResourceHandlers yourself. This facilitates tree-shaking when bundling your application.
It is the preferred entry point for new code - Application is a convenience subclass that registers everything for you, and is expected to be deprecated in a future release.
new AppBase(canvas) only constructs the instance and its root entity. You must then call
AppBase#init with an AppOptions supplying at minimum graphicsDevice,
componentSystems and resourceHandlers before adding components or calling
AppBase#start. Create the graphicsDevice with createGraphicsDevice.
new AppBase(canvas: OffscreenCanvas | HTMLCanvasElement)
Create a new AppBase instance.
Parameters
canvas (OffscreenCanvas | HTMLCanvasElement): The canvas element.Example
const app = new AppBase(canvas);
const options = new AppOptions();
app.init(options);
// Start the application's main loop
app.start();
assets: AssetRegistry
The asset registry managed by the application.
Example
// Search the asset registry for all assets with the tag 'vehicle'
const vehicleAssets = this.app.assets.findByTag('vehicle');
autoRender: boolean = true
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.
Example
// Disable rendering every frame and only render on a keydown event
this.app.autoRender = false;
this.app.keyboard.on('keydown', (event) => {
this.app.renderNextFrame = true;
});
elementInput: ElementInput | null = null
Used to handle input for ElementComponents.
gamepads: GamePads | null = null
Used to access GamePad input.
graphicsDevice: GraphicsDevice
The graphics device used by the application.
i18n: I18n
Handles localization.
keyboard: Keyboard | null = null
The keyboard device.
lightmapper: Lightmapper | null = null
The run-time lightmapper.
loader: ResourceLoader
The resource loader.
maxDeltaTime: number = 0.1
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).
Example
// Don't clamp inter-frame times of 200ms or less
this.app.maxDeltaTime = 0.2;
mouse: Mouse | null = null
The mouse device.
renderNextFrame: boolean
Set to true to render the scene on the next iteration of the main loop. This only has an effect if autoRender is set to false. The value of renderNextFrame is set back to false again as soon as the scene has been rendered.
Example
// Render the scene only while space key is pressed
if (this.app.keyboard.isPressed(KEY_SPACE)) {
this.app.renderNextFrame = true;
}
root: Entity
The root entity of the application.
Example
// Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
const camera = this.app.root.findByName('Camera');
scene: Scene
The scene managed by the application.
Example
// Set the fog type property of the application's scene
this.app.scene.fog.type = FOG_LINEAR;
scenes: SceneRegistry
The scene registry managed by the application.
Example
// 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);
scripts: ScriptRegistry
The application's script registry.
scriptsOrder: string[] = []
Scripts in order of loading first.
systems: ComponentSystemRegistry
The application's component system registry.
Example
// Set global gravity to zero
this.app.systems.rigidbody.gravity.set(0, 0, 0);
Example
// Set the global sound volume to 50%
this.app.systems.sound.volume = 0.5;
timeScale: number = 1
Scales the global time delta. Defaults to 1. Scripts, animation and physics all receive the scaled delta, so 0 stops them together. To pause or slow down physics alone while the rest of the application keeps running, use RigidBodyComponentSystem#timeScale.
Example
// Set the app to run at half speed
this.app.timeScale = 0.5;
touch: TouchDevice | null = null
Used to get touch events input.
xr: XrManager | null = null
The XR Manager that provides ability to start VR/AR sessions.
Example
// check if VR is available
if (app.xr.isAvailable(XRTYPE_VR)) {
// VR is available
}
get batcher(): BatchManager
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.
get fillMode(): string
The current fill mode of the canvas. Can be:
get resolutionMode(): string
The current resolution mode of the canvas, Can be:
get stats(): AppStats
The application's performance statistics. Returns the same AppStats instance on every access. Engine measurements are read-only; AppStats#user holds writable application-defined counters. See AppStats for units, sampling and GPU profiling setup.
applySceneSettings(settings: object): void
Apply scene settings to the current scene. Useful when your scene settings are parsed or generated from a non-URL source.
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.ambientBake (boolean, optional): Enable baking ambient light into lightmaps. Defaults to false.
settings.render.ambientBakeNumSamples (number, optional): Number of samples to use when baking ambient light. Defaults to 1.
settings.render.ambientBakeOcclusionBrightness (number, optional): Brightness of the baked ambient occlusion. Defaults to 0.
settings.render.ambientBakeOcclusionContrast (number, optional): Contrast of the baked ambient occlusion. Defaults to 0.
settings.render.ambientBakeSpherePart (number, optional): How much of the sphere to include when baking ambient light. Defaults to 0.4.
settings.render.ambientLuminance (number): Lux (lm/m^2) value for ambient light intensity.
settings.render.clusteredLightingEnabled (boolean, optional): Enable clustered lighting. Defaults to false.
settings.render.exposure (number): The exposure value tweaks the overall brightness
of the scene.
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_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.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.gamma_correction (number): The gamma correction to apply when
rendering the scene. Can be:
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.gsplatAlphaClip (number, optional): Alpha threshold for gsplat shadow, pick, and prepass rendering. Defaults to 0.3.
settings.render.gsplatAlphaClipForward (number, optional): Alpha threshold for the forward gsplat rendering pass. Defaults to 1 / 255.
settings.render.gsplatAntiAlias (boolean, optional): Enables anti-aliasing compensation for Gaussian splats. Defaults to false.
settings.render.gsplatColorUpdateAngle (number, optional): Viewing angle threshold in degrees for triggering gsplat spherical harmonics color updates. Defaults to 10.
settings.render.gsplatCooldownTicks (number, optional): Number of update ticks before unloading unused streamed gsplat resources. Defaults to 100.
settings.render.gsplatDataFormat (string, optional): Work buffer data format for gsplat rendering. One of the GSPLATDATA_* constants. Defaults to GSPLATDATA_COMPACT.
settings.render.gsplatEnableIds (boolean, optional): Enables per-component ID storage in the gsplat work buffer. Defaults to false.
settings.render.gsplatFoveationCenter (number, optional): Protected centre radius for foveated contribution culling. Defaults to 0.3.
settings.render.gsplatFoveationStrength (number, optional): Foveated contribution culling strength. Defaults to 0.
settings.render.gsplatLodBehindPenalty (number, optional): Multiplier applied to effective distance for gsplat nodes behind the camera. Defaults to 1.5.
settings.render.gsplatLodUnderfillLimit (number, optional): Maximum number of gsplat LOD levels allowed below the optimal level when optimal data is not resident. Defaults to 0.
settings.render.gsplatLodUpdateAngle (number, optional): Angle threshold in degrees to trigger gsplat LOD updates based on camera rotation. Defaults to 90.
settings.render.gsplatLodUpdateDistance (number, optional): Distance threshold in world units to trigger gsplat LOD updates. Defaults to 1.
settings.render.gsplatMinContribution (number, optional): Minimum visual contribution threshold for the compute gsplat renderer. Defaults to 3.
settings.render.gsplatMinPixelSize (number, optional): Minimum screen-space pixel size below which splats are discarded. Defaults to 2.
settings.render.gsplatRadialSorting (boolean, optional): Enables radial sorting of Gaussian splats. Defaults to false.
settings.render.gsplatSplatBudget (number, optional): Number of splats across all GSplats in the scene, used as set by gsplatSplatBudgetMode. 0 means no budget. Defaults to 1000000.
settings.render.gsplatSplatBudgetMode (string, optional): How the splat budget is used for streamed GSplats: 'target' (default) raises detail until the budget is used up; 'limit' lets the LOD distances of each GSplat decide the detail and only lowers it when they would exceed the budget.
settings.render.gsplatUseFog (boolean, optional): Whether to apply scene fog to Gaussian splats. Defaults to true.
settings.render.gsplatUseTonemap (boolean, optional): Whether to apply the camera's tonemapping and the
scene exposure to Gaussian splats. Defaults to true.
settings.render.lightingAreaLightsEnabled (boolean, optional): If set to true, the clustered lighting will support area lights. Defaults to false.
settings.render.lightingCells (number[], optional): Number of cells along each world space axis the space containing lights
is subdivided into. Defaults to [10, 3, 10].
Only lights with bakeDir=true will be used for generating the dominant light direction.
settings.render.lightingCookieAtlasResolution (number, optional): Resolution of the atlas texture storing all non-directional cookie textures. Defaults to 2048.
settings.render.lightingCookiesEnabled (boolean, optional): If set to true, the clustered lighting will support cookie textures. Defaults to false.
settings.render.lightingMaxLights (number, optional): Maximum number of lights the clustered lighting can use in a single
frame. Keep this as low as the scene allows, as a larger value has a per-frame cost. The value is limited by the maximum
texture size supported by the device. Defaults to 255.
settings.render.lightingMaxLightsPerCell (number, optional): Maximum number of lights a cell can store. Defaults to 255.
settings.render.lightingShadowAtlasResolution (number, optional): Resolution of the atlas texture storing all non-directional shadow textures. Defaults to 2048.
settings.render.lightingShadowsEnabled (boolean, optional): If set to true, the clustered lighting will support shadows. Defaults to true.
settings.render.lightingShadowType (number, optional): The type of shadow filtering used by all shadows. Can be:
Defaults to SHADOW_PCF3_32F.
settings.render.lightmapFilterEnabled (boolean, optional): Enables bilateral filter on runtime baked color lightmaps. Defaults to false.
settings.render.lightmapFilterRange (number, optional): Sets the range parameter of the bilateral filter. Defaults to 10.
settings.render.lightmapFilterSmoothness (number, optional): Sets the spatial parameter of the bilateral filter. Defaults to 0.2.
settings.render.lightmapMaxResolution (number): The maximum lightmap resolution.
settings.render.lightmapMode (number): The lightmap baking mode. Can be:
settings.render.lightmapSizeMultiplier (number): The lightmap resolution multiplier.
settings.render.skybox (number | null, optional): The asset ID of the cube map texture to be
used as the scene's skybox. Defaults to null.
settings.render.skyboxIntensity (number, optional): Multiplier for skybox intensity. Defaults to 1.
settings.render.skyboxLuminance (number, optional): Lux (lm/m^2) value for skybox intensity when physical light units are enabled. Defaults to 20000.
settings.render.skyboxMip (number, optional): The mip level of the skybox to be displayed. Defaults to 0.
Only valid for prefiltered cubemap skyboxes.
settings.render.skyboxRotation (number[], optional): Rotation of skybox. Defaults to [0, 0, 0].
settings.render.skyCenter (number[], optional): The center of the sky. Ignored for SKYTYPE_INFINITE. Defaults to [0, 1, 0].
settings.render.skyMeshPosition (number[], optional): The position of sky mesh. Ignored for SKYTYPE_INFINITE. Defaults to [0, 0, 0].
settings.render.skyMeshRotation (number[], optional): The rotation of sky mesh. Ignored for SKYTYPE_INFINITE. Defaults to [0, 0, 0].
settings.render.skyMeshScale (number[], optional): The scale of sky mesh. Ignored for SKYTYPE_INFINITE. Defaults to [1, 1, 1].
settings.render.skyType (string, optional): The type of the sky. One of the SKYTYPE_* constants. Defaults to SKYTYPE_INFINITE.
settings.render.tonemapping (number): The tonemapping transform to apply when
writing fragments to the frame buffer. Can be:
Example
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);
configure(url: string, callback: ConfigureAppCallback): void
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(): void
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.
Example
app.destroy();
drawLine(start: Vec3, end: Vec3, color?: Color, depthTest?: boolean, layer?: Layer): void
Draws a single line. Line start and end coordinates are specified in world space. The line will be flat-shaded with the specified color.
Parameters
start (Vec3): The start world space coordinate of the line.end (Vec3): The end world space coordinate of the line.color (Color, optional): The color of the line, specified in sRGB color space. It defaults
to white if not specified.depthTest (boolean, optional): Specifies if the line is depth tested against the depth
buffer. Defaults to true.layer (Layer, optional): The layer to render the line into. Defaults to LAYERID_IMMEDIATE.Example
// Render a 1-unit long white line
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLine(start, end);
Example
// Render a 1-unit long red line which is not depth tested and renders on top of other geometry
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLine(start, end, Color.RED, false);
Example
// Render a 1-unit long white line into the world layer
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
const worldLayer = app.scene.layers.getLayerById(LAYERID_WORLD);
app.drawLine(start, end, Color.WHITE, true, worldLayer);
drawLineArrays(positions: number[], colors: number[] | Color, depthTest?: boolean, layer?: Layer): void
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.
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[] | Color): A single color for all lines, or an array of colors to color
the lines. If an array is specified, the number of colors it stores must match the number
of positions provided.depthTest (boolean, optional, default true): Specifies if the lines are depth tested against the depth
buffer. Defaults to true.layer (Layer, optional): The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.Example
// 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);
drawLines(positions: Vec3[], colors: Color | Color[], depthTest?: boolean, layer?: Layer): void
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.
Parameters
positions (Vec3[]): An array of points to draw lines between. The length of the
array must be a multiple of 2.colors (Color | Color[]): An array of colors or a single color. If an array is
specified, this must be the same length as the position array. The length of the array
must also be a multiple of 2.depthTest (boolean, optional, default true): Specifies if the lines are depth tested against the depth
buffer. Defaults to true.layer (Layer, optional): The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.Example
// Render a single line, with unique colors for each point
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLines([start, end], [Color.RED, Color.WHITE]);
Example
// Render 2 discrete line segments
const points = [
// Line 1
new Vec3(0, 0, 0),
new Vec3(1, 0, 0),
// Line 2
new Vec3(1, 1, 0),
new Vec3(1, 1, 1)
];
const colors = [
// Line 1
Color.RED,
Color.YELLOW,
// Line 2
Color.CYAN,
Color.BLUE
];
app.drawLines(points, colors);
init(appOptions: AppOptions): void
Initialize the app.
Parameters
appOptions (AppOptions): Options specifying the init parameters for the app.isHidden(): boolean
Queries the visibility of the window or tab in which the application is running.
Returns boolean: True if the application is not visible and false otherwise.
preload(callback: PreloadAppCallback): void
Load all assets in the asset registry that are marked as 'preload'.
Container-backed render assets wait for their referenced containers to be registered and
loaded. If a preloaded render asset's data.containerAsset refers to a container that is
never registered, this method never calls its callback or fires preload:end. Debug builds
warn when a render asset starts waiting for an unregistered container.
Parameters
callback (PreloadAppCallback): Function called when all assets are loaded.resizeCanvas(width?: number, height?: number): { height: number; width: number } | undefined
Resize the application's canvas element in line with the current fill mode.
Parameters
width (number, optional): The width of the canvas. Only used if current fill mode is FILLMODE_NONE.height (number, optional): The height of the canvas. Only used if current fill mode is FILLMODE_NONE.Returns { height: number; width: number } | undefined: An object containing the values
calculated to use as width and height, or undefined if resizing is not allowed or an XR
session is active.
setAreaLightLuts(ltcMat1: number[], ltcMat2: number[]): void
Sets the area light LUT tables for this app.
Parameters
ltcMat1 (number[]): LUT table of type array to be set.ltcMat2 (number[]): LUT table of type array to be set.setCanvasFillMode(mode: string, width?: number, height?: number): void
Controls how the canvas fills the window. The canvas is sized when this is called and on
every AppBase#resizeCanvas; the engine installs no window resize listener of its
own, so call resizeCanvas from your own handler to keep the window-relative modes tracking
the window.
Parameters
mode (string): The mode to use when setting the size of the canvas. Can be:
width (number, optional): The width of the canvas (only used when mode is FILLMODE_NONE).
height (number, optional): The height of the canvas (only used when mode is FILLMODE_NONE).
setCanvasResolution(mode: string, width?: number, height?: number): void
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, optional): The horizontal resolution, optional in AUTO mode, if not provided
canvas clientWidth is used.
height (number, optional): The vertical resolution, optional in AUTO mode, if not provided
canvas clientHeight is used.
setSkybox(asset: Asset<string>): void
Sets the skybox asset to current scene, and subscribes to asset load/change events.
Parameters
asset (Asset<string>): Asset of type skybox to be set to, or null to remove skybox.start(): void
Start the application. This function does the following:
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.
The main loop is driven by requestAnimationFrame. Where that is unavailable, such as in
Node.js, no loop runs, so call update yourself at the rate you need.
Example
app.start();
update(dt: number): void
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, except where there is no main loop, such as in Node.js.
Parameters
dt (number): The time delta in seconds since the last frame.Example
// run a Node.js server at 20 updates per second
setInterval(() => app.update(1 / 20), 50);
updateCanvasSize(): void
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.
static getApplication(id?: string): AppBase | undefined
Get the current application. In the case where there are multiple running applications, the function can get an application based on a supplied canvas id. This function is particularly useful when the current Application is not readily available. For example, in the JavaScript console of the browser's developer tools.
Parameters
id (string, optional): If defined, the returned application should use the canvas which has
this id. Otherwise current application will be returned.Returns AppBase | undefined: The running application, if any.
Example
const app = AppBase.getApplication();
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends AppBase · category: Framework
Application is a subclass of AppBase, which represents the base functionality for all PlayCanvas applications. It acts as a convenience class by internally registering all ComponentSystems and ResourceHandlers implemented in the PlayCanvas Engine. This makes app setup simple but results in the full engine being included when bundling your application.
New code should prefer AppBase, as this class is expected to be deprecated in a future release. Two limitations motivate that:
The equivalent AppBase setup registers only what the app actually uses:
const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] });
const options = new AppOptions();
options.graphicsDevice = device;
options.componentSystems = [RenderComponentSystem, CameraComponentSystem, LightComponentSystem];
options.resourceHandlers = [TextureHandler, ContainerHandler];
const app = new AppBase(canvas);
app.init(options);
The component systems this class registers are listed on the constructor below. That list doubles as a migration checklist, as it maps each component name to the system you would need to register yourself.
AppBase#keyboard, AppBase#mouse, AppBase#touch,
AppBase#gamepads and AppBase#elementInput stay null unless the matching device
is passed to this constructor, so a game that reads input must construct with, for example,
{ keyboard: new Keyboard(window), mouse: new Mouse(canvas), touch: new TouchDevice(canvas) }.
new Application(canvas: OffscreenCanvas | HTMLCanvasElement, options?: object)
Create a new Application instance.
Automatically registers these component systems with the application's component system registry:
Parameters
canvas (OffscreenCanvas | HTMLCanvasElement): The canvas element.options (object, optional, default {}): The options object to configure the Application.
options.assetPrefix (string, optional): Prefix to apply to asset urls before loading.options.devtools (boolean, optional): Whether the app announces itself to developer tools,
such as the PlayCanvas Inspector browser extension. Defaults to true. See
AppOptions#devtools.options.elementInput (ElementInput, optional): Input handler for ElementComponents.options.gamepads (GamePads, optional): Gamepad handler for input.options.graphicsDevice (GraphicsDevice, optional): The graphics device used by the
application. If not provided, a WebGl graphics device will be created.options.graphicsDeviceOptions (any, optional): Options object that is passed into the
GraphicsDevice constructor.options.keyboard (Keyboard, optional): Keyboard handler for input.options.mouse (Mouse, optional): Mouse handler for input.options.physicsWorld (PhysicsWorld, optional): The physics backend used to simulate rigid
bodies, collisions and joints. When omitted, the Ammo.js backend is created automatically if
the Ammo library is loaded. See AppOptions#physicsWorld.options.scriptPrefix (string, optional): Prefix to apply to script urls before loading.options.scriptsOrder (string[], optional): Scripts in order of loading first.options.touch (TouchDevice, optional): TouchDevice handler for input.Example
// Engine-only example: create the application manually
const app = new Application(canvas, options);
// Start the application's main loop
app.start();
assets: AssetRegistryautoRender: boolean = trueelementInput: ElementInput | null = nullgamepads: GamePads | null = nullgraphicsDevice: GraphicsDevicei18n: I18nkeyboard: Keyboard | null = nulllightmapper: Lightmapper | null = nullloader: ResourceLoadermaxDeltaTime: number = 0.1mouse: Mouse | null = nullrenderNextFrame: booleanroot: Entityscene: Scenescenes: SceneRegistryscripts: ScriptRegistryscriptsOrder: string[] = []systems: ComponentSystemRegistrytimeScale: number = 1touch: TouchDevice | null = nullxr: XrManager | null = nullget batcher(): BatchManagerget fillMode(): stringget resolutionMode(): stringget stats(): AppStatsapplySceneSettings(settings: object): voidconfigure(url: string, callback: ConfigureAppCallback): voiddestroy(): voiddrawLine(start: Vec3, end: Vec3, color?: Color, depthTest?: boolean, layer?: Layer): voiddrawLineArrays(positions: number[], colors: number[] | Color, depthTest?: boolean, layer?: Layer): voiddrawLines(positions: Vec3[], colors: Color | Color[], depthTest?: boolean, layer?: Layer): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleaninit(appOptions: AppOptions): voidisHidden(): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlepreload(callback: PreloadAppCallback): voidresizeCanvas(width?: number, height?: number): { height: number; width: number } | undefinedsetAreaLightLuts(ltcMat1: number[], ltcMat2: number[]): voidsetCanvasFillMode(mode: string, width?: number, height?: number): voidsetCanvasResolution(mode: string, width?: number, height?: number): voidsetSkybox(asset: Asset<string>): voidstart(): voidupdate(dt: number): voidupdateCanvasSize(): voidstatic getApplication(id?: string): AppBase | undefinedClass · category: Framework
AppOptions holds configuration settings utilized in the creation of an AppBase instance. It allows functionality to be included or excluded from the AppBase instance.
assetPrefix: string
Prefix to apply to asset urls before loading.
batchManager: typeof BatchManager
The BatchManager.
componentSystems: typeof ComponentSystem[] = []
The component systems the app requires.
devtools: boolean = true
Whether the app announces itself to developer tools, such as the PlayCanvas Inspector browser extension, so they can find and inspect it. Set to false to keep a production build from announcing itself. This is an opt-out, not a protection: code running on the page can still reach the app by other means. Defaults to true.
elementInput: ElementInput
Input handler for ElementComponents.
gamepads: GamePads
Gamepad handler for input.
graphicsDevice: GraphicsDevice
The graphics device.
keyboard: Keyboard
Keyboard handler for input.
lightmapper: typeof Lightmapper
The lightmapper.
mouse: Mouse
Mouse handler for input.
physicsWorld: PhysicsWorld
The physics backend used to simulate rigid bodies, collisions and joints, such as AmmoPhysicsWorld or NullPhysicsWorld. When set, the application installs it into the RigidBodyComponentSystem during AppBase#init, so AppOptions#componentSystems must include RigidBodyComponentSystem. A useful simulation also requires CollisionComponentSystem - rigid bodies and triggers obtain their shapes from collision components - and JointComponentSystem if joints are used. The rigid body system registers its contact listener with the world. When omitted, an AmmoPhysicsWorld is created automatically once application libraries have loaded, if the Ammo.js WasmModule is present. The application takes ownership of the world and destroys it with the application.
resourceHandlers: typeof ResourceHandler[] = []
The resource handlers the app requires.
scriptPrefix: string
Prefix to apply to script urls before loading.
scriptsOrder: string[]
Scripts in order of loading first.
soundManager: SoundManager
The sound manager
touch: TouchDevice
TouchDevice handler for input.
xr: typeof XrManager
The XrManager.
Class · category: Framework
Performance statistics for an application, accessed through AppBase#stats. Engine measurements are read-only; user holds writable application-defined counters. Includes frame cadence, CPU phase timings, overall GPU frame timing, and estimated GPU resource memory usage. CPU timings, GPU timings and memory statistics are available in all builds, subject to graphics capabilities. Primitive counting requires a debug or profiler build; see each getter for its availability.
Durations are in milliseconds and memory sizes are in bytes. Values are the latest available measurements, not averages, except for fps, which refreshes approximately once per second. Frame counters are published at the start of the next application tick; CPU timings are updated when their respective phases finish. CPU phases overlap and must not all be added together. CPU timings and counters are initially zero. GPU results arrive asynchronously and can describe an older frame than the CPU measurements.
GPU profiling is disabled by default. Enable it with
app.graphicsDevice.gpuProfiler.enabled = true when a profiler exists (see the example below).
WebGL requires the disjoint timer query extension; WebGPU requires the timestamp-query feature.
Enabling profiling on an unsupported device produces no timings. gpuFrameTime returns
undefined when profiling is disabled, unsupported, or no valid result has arrived. Reading stats
does not enable profiling. MiniStats also enables GPU profiling when it creates its GPU timer.
Memory statistics estimate resources tracked by the application's graphics device, which may be shared by applications. They do not represent total physical GPU memory usage or capacity, and exclude untracked driver overhead and JavaScript memory.
Example
const profiler = app.graphicsDevice.gpuProfiler;
if (profiler) {
profiler.enabled = true;
}
app.on('frameend', () => {
const stats = app.stats;
console.log(stats.cpuUpdateTime, stats.cpuRenderTime, stats.gpuFrameTime);
});
See AppBase#stats
get cpuAnimationTime(): number
CPU duration of the latest dedicated animation-update phase in milliseconds, used by AnimComponentSystem. Excludes the legacy AnimationComponentSystem, which runs in the system update phase. Part of cpuUpdateTime. Available in all builds.
get cpuPhysicsTime(): number
CPU duration of the most recent physics step in milliseconds, including synchronization and contact handling. Normally part of cpuSystemUpdateTime. Multiple manual steps are not accumulated. Zero before any step or when physics is paused through its timeScale property. Available in all builds.
get cpuRenderTime(): number
CPU duration of the latest scene render in milliseconds, including prerender and postrender event listeners, hierarchy synchronization, batching and render command submission. Excludes graphics device frameStart/frameEnd work and does not measure GPU execution. Retains the latest measurement when rendering is skipped. Available in all builds.
get cpuSystemPostUpdateTime(): number
CPU duration of the latest component systems post-update phase in milliseconds, including script postUpdate callbacks. Part of cpuUpdateTime. Available in all builds.
get cpuSystemUpdateTime(): number
CPU duration of the latest component systems update phase in milliseconds. Includes script updates, physics and other systems subscribed to the update event. Part of cpuUpdateTime. Available in all builds.
get cpuUpdateTime(): number
CPU duration of the latest application update in milliseconds, including component systems, application update event listeners and input updates. Excludes graphics device updates. Includes the other CPU update phase timings. Available in all builds.
get drawCallCount(): number
Total draw calls submitted during the previous frame, published at the start of the next application tick. Available in all builds.
get fps(): number
Frame count over the latest approximately one-second reporting interval. Initially zero until an interval completes. Available in all builds.
get frameTime(): number
Interval between application ticks in milliseconds, including time outside the engine. Unaffected by time scaling or delta-time clamping. Available in all builds.
get gpuFrameTime(): number | undefined
Overall duration of the most recently resolved GPU frame in milliseconds. Available in all builds when GPU profiling is supported and enabled. Returns undefined until a valid timing arrives, when profiling is disabled, or after timing invalidation such as context loss. Results arrive asynchronously and may be several frames old.
WebGL measures a whole-frame timer query. WebGPU measures the span from the first profiled pass beginning to the last pass ending, including gaps between passes. This is elapsed GPU time, not GPU utilization, and is not the sum of potentially overlapping pass durations.
get primitiveCount(): number | undefined
Total primitives submitted during the previous frame, published at the start of the next application tick. Counts triangles, lines and points across all passes, including instances and CPU-authored multi-draw commands. Counts are calculated before GPU clipping and culling.
Available only in debug and profiler builds. Returns undefined in release and minified builds. This is an estimate from draw parameters: GPU-generated indirect draws are excluded, and primitive-restart indices in indexed strips are not inspected. No GPU readback is performed.
get user(): Map<string, number>
Application-defined numeric counters. Returns the same map on every access. Entries can be added, updated, deleted or cleared by the application; the engine never resets them. Available in all builds. Values and their units are defined by the application.
To display a counter in MiniStats, configure a graph with a path such as user.ai.
Counter names used in MiniStats must not contain dots, which separate path segments.
Initialize counters before accumulating values and reset per-frame totals on frameupdate.
Example
app.stats.user.set('ai', 0);
app.on('frameupdate', () => app.stats.user.set('ai', 0));
// Accumulate time spent in application code during this frame.
const start = performance.now();
// ... run AI logic ...
app.stats.user.set('ai', app.stats.user.get('ai') + performance.now() - start);
get vramIndexBufferBytes(): number
Estimated GPU index buffer memory in bytes. Available in all builds.
get vramStorageBufferBytes(): number
Estimated GPU storage buffer memory in bytes. Available in all builds. Zero on backends without storage buffers or when none have been allocated.
get vramTextureBytes(): number
Estimated GPU texture memory in bytes. Available in all builds.
get vramTotalBytes(): number
Total estimated GPU resource memory in bytes: textures, vertex buffers, index buffers, uniform buffers and storage buffers. Available in all builds.
get vramUniformBufferBytes(): number
Estimated GPU uniform buffer memory in bytes. Available in all builds. Zero when no tracked uniform buffers have been allocated.
get vramVertexBufferBytes(): number
Estimated GPU vertex buffer memory in bytes. Available in all builds.
Class · extends EventHandler · category: Framework
Components are used to attach functionality on a Entity. Components can receive update events each frame, and expose properties to the PlayCanvas Editor.
entity: Entity
The Entity that this Component is attached to.
system: ComponentSystem
The ComponentSystem used to create this Component.
get enabled(): boolean
set enabled(value: boolean)
Gets the enabled state of the component.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Framework
Component Systems contain the logic and functionality to update all Components of a particular type.
new ComponentSystem(app: AppBase)
Create a new ComponentSystem instance.
Parameters
app (AppBase): The application managing this system.readonly id: string
The id type of the ComponentSystem.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Framework
The ComponentSystemRegistry manages the instances of an application's ComponentSystems. AppBase maintains a single instance of this class which can be accessed via AppBase#systems.
// Set the gravity to zero
app.systems.rigidbody.gravity = new Vec3(0, 0, 0);
// Set the volume to 50%
app.systems.sound.volume = 0.5;
new ComponentSystemRegistry()
Create a new ComponentSystemRegistry instance.
readonly anim: AnimComponentSystem | undefined
Gets the AnimComponentSystem from the registry.
readonly animation: AnimationComponentSystem | undefined
Gets the AnimationComponentSystem from the registry.
readonly audiolistener: AudioListenerComponentSystem | undefined
Gets the AudioListenerComponentSystem from the registry.
readonly button: ButtonComponentSystem | undefined
Gets the ButtonComponentSystem from the registry.
readonly camera: CameraComponentSystem | undefined
Gets the CameraComponentSystem from the registry.
readonly collision: CollisionComponentSystem | undefined
Gets the CollisionComponentSystem from the registry.
readonly element: ElementComponentSystem | undefined
Gets the ElementComponentSystem from the registry.
readonly gsplat: GSplatComponentSystem | undefined
Gets the GSplatComponentSystem from the registry.
readonly joint: JointComponentSystem | undefined
Gets the JointComponentSystem from the registry.
readonly layoutchild: LayoutChildComponentSystem | undefined
Gets the LayoutChildComponentSystem from the registry.
readonly layoutgroup: LayoutGroupComponentSystem | undefined
Gets the LayoutGroupComponentSystem from the registry.
readonly light: LightComponentSystem | undefined
Gets the LightComponentSystem from the registry.
readonly model: ModelComponentSystem | undefined
Gets the ModelComponentSystem from the registry.
readonly particlesystem: ParticleSystemComponentSystem | undefined
Gets the ParticleSystemComponentSystem from the registry.
readonly render: RenderComponentSystem | undefined
Gets the RenderComponentSystem from the registry.
readonly rigidbody: RigidBodyComponentSystem | undefined
Gets the RigidBodyComponentSystem from the registry.
readonly screen: ScreenComponentSystem | undefined
Gets the ScreenComponentSystem from the registry.
readonly script: ScriptComponentSystem | undefined
Gets the ScriptComponentSystem from the registry.
readonly scrollbar: ScrollbarComponentSystem | undefined
Gets the ScrollbarComponentSystem from the registry.
readonly scrollview: ScrollViewComponentSystem | undefined
Gets the ScrollViewComponentSystem from the registry.
readonly sound: SoundComponentSystem | undefined
Gets the SoundComponentSystem from the registry.
readonly sprite: SpriteComponentSystem | undefined
Gets the SpriteComponentSystem from the registry.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends GraphNode · category: Framework
An Entity is the core primitive of a PlayCanvas application. Every object in a scene (a camera, a light, a 3D model, a sound source, a piece of UI, or your own gameplay object) is represented by an Entity. On its own, an Entity is simply a named node in the scene graph; it gains behavior from the Components attached to it.
An Entity therefore brings together two things:
Add a capability with Entity#addComponent, access it later through the matching property (such as Entity#camera or Entity#render), and remove it with Entity#removeComponent. An entity, together with all of its descendants and their components, can be enabled or disabled as a group via GraphNode#enabled, and removed from the scene with Entity#destroy.
Example
// Create an entity, give it a camera component, position it, and add it to the scene
const camera = new Entity('camera');
camera.addComponent('camera', {
clearColor: new Color(0.1, 0.1, 0.1)
});
camera.setPosition(0, 0, 10);
app.root.addChild(camera);
Example
// Entities form a hierarchy: a child inherits its parent's transform
const parent = new Entity('parent');
const child = new Entity('child');
parent.addChild(child);
parent.setLocalPosition(5, 0, 0); // moves both parent and child
new Entity(name?: string, app?: AppBase)
Create a new Entity.
Parameters
name (string, optional): The non-unique name of the entity, default is "Untitled".app (AppBase, optional): The application the entity belongs to, default is the current
application.Example
const entity = new Entity();
// Add a Component to the Entity
entity.addComponent('camera', {
fov: 45,
nearClip: 1,
farClip: 10000
});
// Add the Entity into the scene graph
app.root.addChild(entity);
// Move the entity
entity.translate(10, 0, 0);
// Or translate it by setting its position directly
const p = entity.getPosition();
entity.setPosition(p.x + 10, p.y, p.z);
// Change the entity's rotation in local space
const e = entity.getLocalEulerAngles();
entity.setLocalEulerAngles(e.x, e.y + 90, e.z);
// Or use rotateLocal
entity.rotateLocal(0, 90, 0);
readonly anim: AnimComponent | undefined
Gets the AnimComponent attached to this entity.
readonly animation: AnimationComponent | undefined
Gets the AnimationComponent attached to this entity.
readonly audiolistener: AudioListenerComponent | undefined
Gets the AudioListenerComponent attached to this entity.
readonly button: ButtonComponent | undefined
Gets the ButtonComponent attached to this entity.
readonly camera: CameraComponent | undefined
Gets the CameraComponent attached to this entity.
readonly collision: CollisionComponent | undefined
Gets the CollisionComponent attached to this entity.
readonly element: ElementComponent | undefined
Gets the ElementComponent attached to this entity.
readonly gsplat: GSplatComponent | undefined
Gets the GSplatComponent attached to this entity.
readonly joint: JointComponent | undefined
Gets the JointComponent attached to this entity.
readonly layoutchild: LayoutChildComponent | undefined
Gets the LayoutChildComponent attached to this entity.
readonly layoutgroup: LayoutGroupComponent | undefined
Gets the LayoutGroupComponent attached to this entity.
readonly light: LightComponent | undefined
Gets the LightComponent attached to this entity.
readonly model: ModelComponent | undefined
Gets the ModelComponent attached to this entity.
readonly particlesystem: ParticleSystemComponent | undefined
Gets the ParticleSystemComponent attached to this entity.
readonly render: RenderComponent | undefined
Gets the RenderComponent attached to this entity.
readonly rigidbody: RigidBodyComponent | undefined
Gets the RigidBodyComponent attached to this entity.
readonly screen: ScreenComponent | undefined
Gets the ScreenComponent attached to this entity.
readonly script: ScriptComponent | undefined
Gets the ScriptComponent attached to this entity.
readonly scrollbar: ScrollbarComponent | undefined
Gets the ScrollbarComponent attached to this entity.
readonly scrollview: ScrollViewComponent | undefined
Gets the ScrollViewComponent attached to this entity.
readonly sound: SoundComponent | undefined
Gets the SoundComponent attached to this entity.
readonly sprite: SpriteComponent | undefined
Gets the SpriteComponent attached to this entity.
get guid(): string
Gets the GUID for this Entity.
protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void
Parameters
node (GraphNode): The node to update.enabled (boolean): Enable or disable the node.protected _onHierarchyStateChanged(enabled: boolean): void
Parameters
enabled (boolean): Enable or disable the node.addComponent<K extends string & {} | ComponentName>(type: K, data?: K extends ComponentName ? ComponentOptions<K> : any): (K extends ComponentName ? ComponentMap[K] : Component) | null
Create a new component and add it to the entity. Use this to add functionality to the entity like rendering a model, playing sounds and so on.
For the built-in components the type also types the options and the result:
entity.addComponent('camera', { fov: 45 }) accepts any settable property of
CameraComponent and returns CameraComponent | null. See ComponentOptions for
the rule and ComponentMap for extending this to application-defined components.
Parameters
type (K): The name of the component to add (a ComponentName). Valid strings are:
data (K extends ComponentName ? ComponentOptions<K> : any, optional): The
initialization data for the specific component type: the settable properties of the component
class plus the extras its system understands (see ComponentOptions). Any object is
accepted for a component name that is not in ComponentMap.
Returns (K extends ComponentName ? ComponentMap[K] : Component) | null: The new
Component that was attached to the entity or null if there was an error.
Example
const entity = new Entity();
// Add a light component with default properties
entity.addComponent("light");
// Add a camera component with some specified properties
entity.addComponent("camera", {
fov: 45,
clearColor: new Color(1, 0, 0)
});
clone(): Entity
Create a deep copy of the Entity. Duplicate the full Entity hierarchy, with all Components and all descendants. Note, this Entity is not in the hierarchy and must be added manually.
Returns Entity: A new Entity which is a deep copy of the original.
Example
const e = this.entity.clone();
// Add clone as a sibling to the original
this.entity.parent.addChild(e);
destroy(): void
Destroy the entity and all of its descendants. First, all of the entity's components are disabled and then removed. Then, the entity is removed from the hierarchy. This is then repeated recursively for all descendants of the entity.
The last thing the entity does is fire the destroy event.
Example
const firstChild = this.entity.children[0];
firstChild.destroy(); // destroy child and all of its descendants
findByGuid(guid: string): Entity | null
Find a descendant of this entity with the GUID.
Parameters
guid (string): The GUID to search for.Returns Entity | null: The entity with the matching GUID or null if no entity is found.
findComponent<K extends string & {} | ComponentName>(type: K): (K extends ComponentName ? ComponentMap[K] : Component) | null
Search the entity and all of its descendants for the first component of specified type.
Parameters
type (K): The name of the component type to retrieve.Returns (K extends ComponentName ? ComponentMap[K] : Component) | null: A component of
specified type, if the entity or any of its descendants has one. Returns null otherwise.
Example
// Get the first found light component in the hierarchy tree that starts with this entity
const light = entity.findComponent("light");
findComponents<K extends string & {} | ComponentName>(type: K): (K extends ComponentName ? ComponentMap[K] : Component)[]
Search the entity and all of its descendants for all components of specified type.
Parameters
type (K): The name of the component type to retrieve.Returns (K extends ComponentName ? ComponentMap[K] : Component)[]: All components of
specified type in the entity or any of its descendants. Returns empty array if none found.
Example
// Get all light components in the hierarchy tree that starts with this entity
const lights = entity.findComponents("light");
findScript<T extends Script>(type: Object): T | undefined
Search the entity and all of its descendants for the first script instance of the specified class. The result is typed as an instance of that class, so no cast is needed.
Parameters
type (Object): The script class to search for.Returns T | undefined: A script instance of the specified class, if the entity or any of its
descendants has one. Returns undefined otherwise.
Example
// Get the first PlayerController instance in the hierarchy tree that starts with this entity
const controller = entity.findScript(PlayerController); // PlayerController | undefined
findScript(name: string): Script | undefined
Search the entity and all of its descendants for the first script instance with the specified name.
Parameters
name (string): The name of the script to search for.Returns Script | undefined: A script instance with the specified name, if the entity or any
of its descendants has one. Returns undefined otherwise.
Example
// Get the first found "playerController" instance in the hierarchy tree that starts with this entity
const controller = entity.findScript("playerController");
findScripts<T extends Script>(type: Object): T[]
Search the entity and all of its descendants for all script instances of the specified class. The result is typed as an array of that class, so no cast is needed.
Parameters
type (Object): The script class to search for.Returns T[]: All script instances of the specified class in the entity or any of its
descendants. Returns an empty array if none are found.
Example
// Get all PlayerController instances in the hierarchy tree that starts with this entity
const controllers = entity.findScripts(PlayerController); // PlayerController[]
findScripts(name: string): Script[]
Search the entity and all of its descendants for all script instances with the specified name.
Parameters
name (string): The name of the script to search for.Returns Script[]: All script instances with the specified name in the entity or any of its
descendants. Returns an empty array if none are found.
Example
// Get all "playerController" instances in the hierarchy tree that starts with this entity
const controllers = entity.findScripts("playerController");
removeComponent(type: string & {} | ComponentName): void
Remove a component from the Entity.
Parameters
type (string & {} | ComponentName): The name of the Component type.Example
const entity = new Entity();
entity.addComponent("light"); // add new light component
entity.removeComponent("light"); // remove light component
static EVENT_DESTROY: string = 'destroy'
Fired after the entity is destroyed.
Example
entity.on('destroy', (e) => {
console.log(`Entity ${e.name} has been destroyed`);
});
protected _children: GraphNode[] = []name: stringtags: Tagsget children(): readonly GraphNode[]get enabled(): boolean · set enabled(enabled: boolean)get forward(): Readonly<Vec3>get graphDepth(): numberget parent(): GraphNode | nullget path(): stringget right(): Readonly<Vec3>get root(): GraphNodeget up(): Readonly<Vec3>addChild(node: GraphNode): voidfind(attr: string | FindNodeCallback, value?: any): GraphNode[]findByName(name: string): GraphNode | nullfindByPath(path: string | string[]): GraphNode | nullfindByTag(...query: any[]): GraphNode[]findOne(attr: string | FindNodeCallback, value?: any): GraphNode | nullfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerforEach(callback: ForEachNodeCallback, thisArg?: any): voidgetEulerAngles(): Readonly<Vec3>getLocalEulerAngles(): Readonly<Vec3>getLocalPosition(): Readonly<Vec3>getLocalRotation(): Readonly<Quat>getLocalScale(): Readonly<Vec3>getLocalTransform(): Readonly<Mat4>getPosition(): Readonly<Vec3>getRotation(): Readonly<Quat>getWorldTransform(): Readonly<Mat4>hasEvent(name: string): booleaninsertChild(node: GraphNode, index: number): voidisAncestorOf(node: GraphNode): booleanisDescendantOf(node: GraphNode): booleanlookAt(x: number, y: number, z: number, ux?: number, uy?: number, uz?: number): void · lookAt(target: Vec3, up?: Vec3): voidoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleremove(): voidremoveChild(child: GraphNode): voidreparent(parent: GraphNode, index?: number): voidrotate(x: number, y: number, z: number): void · rotate(rotation: Vec3): voidrotateLocal(x: number, y: number, z: number): void · rotateLocal(rotation: Vec3): voidsetEulerAngles(x: number, y: number, z: number): void · setEulerAngles(angles: Vec3): voidsetLocalEulerAngles(x: number, y: number, z: number): void · setLocalEulerAngles(angles: Vec3): voidsetLocalPosition(x: number, y: number, z: number): void · setLocalPosition(position: Vec3): voidsetLocalRotation(x: number, y: number, z: number, w: number): void · setLocalRotation(rotation: Quat): voidsetLocalScale(x: number, y: number, z: number): void · setLocalScale(scale: Vec3): voidsetPosition(x: number, y: number, z: number): void · setPosition(position: Vec3): voidsetPositionAndRotation(position: Vec3, rotation: Quat): voidsetRotation(x: number, y: number, z: number, w: number): void · setRotation(rotation: Quat): voidtranslate(x: number, y: number, z: number): void · translate(translation: Vec3): voidtranslateLocal(x: number, y: number, z: number): void · translateLocal(translation: Vec3): voidClass · category: Framework
Event Handle that is created by EventHandler and can be used for easier event removal and management.
Example
const evt = obj.on('test', (a, b) => {
console.log(a + b);
});
obj.fire('test');
evt.off(); // easy way to remove this event
obj.fire('test'); // this will not trigger an event
Example
// store an array of event handles
let events = [];
events.push(objA.on('testA', () => {}));
events.push(objB.on('testB', () => {}));
// when needed, remove all events
events.forEach((evt) => {
evt.off();
});
events = [];
new EventHandle(handler: EventHandler, name: string, callback: HandleEventCallback, scope: any, once?: boolean)
Parameters
handler (EventHandler): source object of the event.name (string): Name of the event.callback (HandleEventCallback): Function that is called when event is fired.scope (any): Object that is used as this when event is fired.once (boolean, optional, default false): If this is a single event and will be removed after event is fired.off(): void
Remove this event from its handler.
Class · category: Framework
Abstract base class that implements functionality for event handling.
const obj = new EventHandlerSubclass();
// subscribe to an event
obj.on('hello', (str) => {
console.log('event hello is fired', str);
});
// fire event
obj.fire('hello', 'world');
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler
Fire an event, all additional arguments are passed on to the event listener.
Parameters
name (string): Name of event to fire.arg1 (any, optional): First argument that is passed to the event handler.arg2 (any, optional): Second argument that is passed to the event handler.arg3 (any, optional): Third argument that is passed to the event handler.arg4 (any, optional): Fourth argument that is passed to the event handler.arg5 (any, optional): Fifth argument that is passed to the event handler.arg6 (any, optional): Sixth argument that is passed to the event handler.arg7 (any, optional): Seventh argument that is passed to the event handler.arg8 (any, optional): Eighth argument that is passed to the event handler.Returns EventHandler: Self for chaining.
Example
obj.fire('test', 'This is the message');
hasEvent(name: string): boolean
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.
Example
obj.on('test', () => {}); // bind an event to 'test'
obj.hasEvent('test'); // returns true
obj.hasEvent('hello'); // returns false
off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler
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
name (string, optional): Name of the event to unbind.callback (HandleEventCallback, optional): Function to be unbound.scope (any, optional): Scope that was used as the this when the event is fired.Returns EventHandler: Self for chaining.
Example
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
on(name: string, callback: HandleEventCallback, scope?: any): EventHandle
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.scope (any, optional): 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).
Example
obj.on('test', (a, b) => {
console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console
Example
// 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();
once(name: string, callback: HandleEventCallback, scope?: any): EventHandle
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.scope (any, optional): 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).
Example
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
Class · extends EventHandler · category: Framework
A GraphNode is a node in the scene graph: a named object with a position, rotation and scale, and a list of children whose transforms are expressed relative to it. Nodes form a tree, and the world transform of any node is its local transform combined with the world transform of its parent; the root has no parent, so its world transform is its local one. The engine brings every world transform up to date each frame before rendering, so a change to a parent reaches all of its descendants.
GraphNode is the base class of Entity, which adds components, so in practice these methods are called on entities. The conventions are the same on both:
Build the hierarchy with addChild, insertChild, removeChild and reparent, and search it with findByName, findByPath, findByTag and find. Setting enabled to false disables the node and its whole subtree.
Example
// Move a node one unit in its own facing direction, then turn it to face a target
node.translateLocal(0, 0, -1);
node.lookAt(target.getPosition());
Example
// Getters return read-only internal storage: clone before modifying
const start = node.getPosition().clone();
start.y += 1;
node.setPosition(start);
new GraphNode(name?: string)
Create a new GraphNode instance.
Parameters
name (string, optional, default 'Untitled'): The non-unique name of a graph node. Defaults to 'Untitled'.protected _children: GraphNode[] = []
name: string
The non-unique name of a graph node. Defaults to 'Untitled'.
tags: Tags
Interface for tagging graph nodes. Tag based searches can be performed using the findByTag function.
get children(): readonly GraphNode[]
Gets the children of this graph node. Use addChild, insertChild, removeChild or reparent to change the hierarchy.
get enabled(): boolean
set enabled(enabled: boolean)
Gets the enabled state of the GraphNode.
get forward(): Readonly<Vec3>
Gets the normalized local space negative Z-axis vector of the graph node in world space.
get graphDepth(): number
Gets the depth of this child within the graph. Note that for performance reasons this is only recalculated when a node is added to a new parent. In other words, it is not recalculated when a node is simply removed from the graph.
get parent(): GraphNode | null
Gets the parent of this graph node.
get path(): string
Gets the path of this graph node relative to the root of the hierarchy.
get right(): Readonly<Vec3>
Gets the normalized local space X-axis vector of the graph node in world space.
get root(): GraphNode
Gets the oldest ancestor graph node from this graph node.
get up(): Readonly<Vec3>
Gets the normalized local space Y-axis vector of the graph node in world space.
protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void
Parameters
node (GraphNode): Graph node to update.enabled (boolean): True if enabled in the hierarchy, false if disabled.protected _onHierarchyStateChanged(enabled: boolean): void
Called when the enabled flag of the entity or one of its parents changes.
Parameters
enabled (boolean): True if enabled in the hierarchy, false if disabled.addChild(node: GraphNode): void
Add a new child to the child list and update the parent value of the child node. If the node already had a parent, it is removed from its child list.
The child keeps its existing local transform, which is now interpreted relative to the new parent, so a node placed in world space before being added will appear to move. Set the transform after adding, or re-apply the world placement with GraphNode#setPosition.
Parameters
node (GraphNode): The new child to add.Example
const e = new Entity(app);
this.entity.addChild(e);
clone(): GraphNode
Clone a graph node.
Returns GraphNode: A clone of the specified graph node.
destroy(): void
Destroy the graph node and all of its descendants. First, the graph node is removed from the hierarchy. This is then repeated recursively for all descendants of the graph node.
The last thing the graph node does is fire the destroy event.
Example
const firstChild = graphNode.children[0];
firstChild.destroy(); // destroy child and all of its descendants
find(attr: string | FindNodeCallback, value?: any): GraphNode[]
Search the graph node and all of its descendants for the nodes that satisfy some search criteria.
Parameters
attr (string | FindNodeCallback): This can either be a function or a string. If it's a
function, it is executed for each descendant node to test if node satisfies the search
logic. Returning true from the function will include the node into the results. If it's a
string then it represents the name of a field or a method of the node. If this is the name
of a field then the value passed as the second argument will be checked for equality. If
this is the name of a function then the return value of the function will be checked for
equality against the value passed as the second argument to this function.value (any, optional): If the first argument (attr) is a property name then this value
will be checked against the value of the property.Returns GraphNode[]: The array of graph nodes that match the search criteria.
Example
// Finds all nodes that have a model component and have 'door' in their lower-cased name
const doors = house.find((node) => {
return node.model && node.name.toLowerCase().indexOf('door') !== -1;
});
Example
// Finds all nodes that have the name property set to 'Test'
const entities = parent.find('name', 'Test');
findByName(name: string): GraphNode | null
Get the first node found in the graph with the name. The search is depth first.
Parameters
name (string): The name of the node.Returns GraphNode | null: The first node to be found matching the supplied name. Returns
null if no node is found.
findByPath(path: string | string[]): GraphNode | null
Get the first node found in the graph by its full path in the graph. The full path has this form 'parent/child/sub-child'. The search is depth first.
Parameters
path (string | string[]): The full path of the GraphNode as either a string or array
of GraphNode names.Returns GraphNode | null: The first node to be found matching the supplied path. Returns
null if no node is found.
Example
// String form
const grandchild = this.entity.findByPath('child/grandchild');
Example
// Array form
const grandchild = this.entity.findByPath(['child', 'grandchild']);
findByTag(...query: any[]): GraphNode[]
Return all graph nodes that satisfy the search query. Query can be simply a string, or comma separated strings, to have inclusive results of graph nodes that match at least one query. A query that consists of an array of tags can be used to match graph nodes that have each tag of the array.
Parameters
query (any[]): Name of a tag or array of tags.Returns GraphNode[]: A list of all graph nodes that match the query.
Example
// Return all graph nodes tagged with `animal`
const animals = node.findByTag("animal");
Example
// Return all graph nodes tagged with `bird` OR `mammal`
const birdsAndMammals = node.findByTag("bird", "mammal");
Example
// Return all graph nodes tagged with `carnivore` AND `mammal`
const meatEatingMammals = node.findByTag(["carnivore", "mammal"]);
Example
// Return all graph nodes tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`)
const meatEatingMammalsAndReptiles = node.findByTag(["carnivore", "mammal"], ["carnivore", "reptile"]);
findOne(attr: string | FindNodeCallback, value?: any): GraphNode | null
Search the graph node and all of its descendants for the first node that satisfies some search criteria.
Parameters
attr (string | FindNodeCallback): This can either be a function or a string. If it's a
function, it is executed for each descendant node to test if node satisfies the search
logic. Returning true from the function will result in that node being returned from
findOne. If it's a string then it represents the name of a field or a method of the node. If
this is the name of a field then the value passed as the second argument will be checked for
equality. If this is the name of a function then the return value of the function will be
checked for equality against the value passed as the second argument to this function.value (any, optional): If the first argument (attr) is a property name then this value
will be checked against the value of the property.Returns GraphNode | null: A graph node that matches the search criteria. Returns null if no
node is found.
Example
// Find the first node that is called 'head' and has a model component
const head = player.findOne((node) => {
return node.model && node.name === 'head';
});
Example
// Finds the first node that has the name property set to 'Test'
const node = parent.findOne('name', 'Test');
forEach(callback: ForEachNodeCallback, thisArg?: any): void
Executes a provided function once on this graph node and all of its descendants.
Parameters
callback (ForEachNodeCallback): The function to execute on the graph node and each
descendant.thisArg (any, optional): Optional value to use as this when executing callback function.Example
// Log the path and name of each node in descendant tree starting with "parent"
parent.forEach((node) => {
console.log(node.path + "/" + node.name);
});
getEulerAngles(): Readonly<Vec3>
Get the world space rotation for the specified GraphNode in Euler angles. The angles are in degrees and in XYZ order.
Important: The value returned by this function should be considered read-only. In order to set the world space rotation of the graph node, use setEulerAngles.
Returns Readonly<Vec3>: The world space rotation of the graph node in Euler angle form.
Example
const angles = this.entity.getEulerAngles();
angles.y = 180; // rotate the entity around Y by 180 degrees
this.entity.setEulerAngles(angles);
getLocalEulerAngles(): Readonly<Vec3>
Get the local space rotation for the specified GraphNode in Euler angles. The angles are in degrees and in XYZ order.
Important: The value returned by this function should be considered read-only. In order to set the local space rotation of the graph node, use setLocalEulerAngles.
Returns Readonly<Vec3>: The local space rotation of the graph node as Euler angles in XYZ order.
Example
const angles = this.entity.getLocalEulerAngles();
angles.y = 180;
this.entity.setLocalEulerAngles(angles);
getLocalPosition(): Readonly<Vec3>
Get the position in local space for the specified GraphNode. The position is returned as a Vec3. The returned vector should be considered read-only. To update the local position, use setLocalPosition.
Returns Readonly<Vec3>: The local space position of the graph node.
Example
const position = this.entity.getLocalPosition().clone();
position.x += 1; // move the entity 1 unit along x.
this.entity.setLocalPosition(position);
getLocalRotation(): Readonly<Quat>
Get the rotation in local space for the specified GraphNode. The rotation is returned as a Quat. The returned quaternion should be considered read-only. To update the local rotation, use setLocalRotation.
Returns Readonly<Quat>: The local space rotation of the graph node as a quaternion.
Example
const rotation = this.entity.getLocalRotation();
getLocalScale(): Readonly<Vec3>
Get the scale in local space for the specified GraphNode. The scale is returned as a Vec3. The returned vector should be considered read-only. To update the local scale, use setLocalScale.
Returns Readonly<Vec3>: The local space scale of the graph node.
Example
const scale = this.entity.getLocalScale().clone();
scale.x = 100;
this.entity.setLocalScale(scale);
getLocalTransform(): Readonly<Mat4>
Get the local transform matrix for this graph node. This matrix is the transform relative to the node's parent's world transformation matrix.
Returns Readonly<Mat4>: The node's local transformation matrix.
Example
const transform = this.entity.getLocalTransform();
getPosition(): Readonly<Vec3>
Get the world space position for the specified GraphNode. The position is returned as a Vec3. The value returned by this function should be considered read-only. In order to set the world space position of the graph node, use setPosition.
Returns Readonly<Vec3>: The world space position of the graph node.
Example
const position = this.entity.getPosition().clone();
position.x = 10;
this.entity.setPosition(position);
getRotation(): Readonly<Quat>
Get the world space rotation for the specified GraphNode. The rotation is returned as a Quat. The value returned by this function should be considered read-only. In order to set the world space rotation of the graph node, use setRotation.
Returns Readonly<Quat>: The world space rotation of the graph node as a quaternion.
Example
const rotation = this.entity.getRotation();
getWorldTransform(): Readonly<Mat4>
Get the world transformation matrix for this graph node.
Returns Readonly<Mat4>: The node's world transformation matrix.
Example
const transform = this.entity.getWorldTransform();
insertChild(node: GraphNode, index: number): void
Insert a new child to the child list at the specified index and update the parent value of the child node. If the node already had a parent, it is removed from its child list.
Parameters
node (GraphNode): The new child to insert.index (number): The index in the child list of the parent where the new node will be
inserted.Example
const e = new Entity(app);
this.entity.insertChild(e, 1);
isAncestorOf(node: GraphNode): boolean
Check if node is ancestor for another node.
Parameters
node (GraphNode): Potential descendant of node.Returns boolean: If node is ancestor for another node.
Example
if (body.isAncestorOf(foot)) {
// foot is within body's hierarchy
}
isDescendantOf(node: GraphNode): boolean
Check if node is descendant of another node.
Parameters
node (GraphNode): Potential ancestor of node.Returns boolean: If node is descendant of another node.
Example
if (roof.isDescendantOf(house)) {
// roof is descendant of house entity
}
lookAt(x: number, y: number, z: number, ux?: number, uy?: number, uz?: number): void
Reorients the graph node so that the negative z-axis points towards the target.
The up vector must not be parallel to the direction from the node to the target. When it is — looking straight up or down with the default up vector, or at the node's own position — the basis is degenerate and the node's rotation is reset to identity, discarding whatever rotation it already had, with nothing reported. Pass a different up vector in those cases.
Parameters
x (number): X-component of the world space coordinate to look at.y (number): Y-component of the world space coordinate to look at.z (number): Z-component of the world space coordinate to look at.ux (number, optional): X-component of the up vector for the look at transform. Defaults to 0.uy (number, optional): Y-component of the up vector for the look at transform. Defaults to 1.uz (number, optional): Z-component of the up vector for the look at transform. Defaults to 0.Returns void
Example
// Look at the world space origin, using the (default) positive y-axis for up
this.entity.lookAt(0, 0, 0);
Example
// Look at world space coordinate [10, 10, 10], using the negative world y-axis for up
this.entity.lookAt(10, 10, 10, 0, -1, 0);
lookAt(target: Vec3, up?: Vec3): void
Reorients the graph node so that the negative z-axis points towards the target.
Parameters
target (Vec3): The world space coordinate to look at.up (Vec3, optional): The world space up vector for look at transform. Defaults to Vec3.UP.Returns void
Example
// Look at another entity, using the (default) positive y-axis for up
const target = otherEntity.getPosition();
this.entity.lookAt(target);
Example
// Look at another entity, using the negative world y-axis for up
const target = otherEntity.getPosition();
this.entity.lookAt(target, Vec3.DOWN);
remove(): void
Remove graph node from current parent.
removeChild(child: GraphNode): void
Remove the node from the child list and update the parent value of the child.
This detaches the node without disabling it: the removed subtree still reports
enabled === true, and its lights, cameras, scripts and sounds keep running. Set
enabled = false to deactivate a node, or destroy the entity to remove it outright.
Parameters
child (GraphNode): The node to remove.Example
const child = this.entity.children[0];
this.entity.removeChild(child);
reparent(parent: GraphNode, index?: number): void
Remove graph node from current parent and add as child to new parent.
Parameters
parent (GraphNode): New parent to attach graph node to.index (number, optional): The child index where the child node should be placed.rotate(x: number, y: number, z: number): void
Rotates the graph node in world space by the specified Euler angles. Eulers are specified in degrees in XYZ order.
Parameters
x (number): Rotation around world space x-axis in degrees.y (number): Rotation around world space y-axis in degrees.z (number): Rotation around world space z-axis in degrees.Returns void
Example
this.entity.rotate(0, 90, 0);
rotate(rotation: Vec3): void
Rotates the graph node in world space by the specified Euler angles. Eulers are specified in degrees in XYZ order.
Parameters
rotation (Vec3): Vector holding world space rotation.Returns void
Example
const rotation = new Vec3(0, 90, 0);
this.entity.rotate(rotation);
rotateLocal(x: number, y: number, z: number): void
Rotates the graph node in local space by the specified Euler angles. Eulers are specified in degrees in XYZ order.
Parameters
x (number): Rotation around local space x-axis in degrees.y (number): Rotation around local space y-axis in degrees.z (number): Rotation around local space z-axis in degrees.Returns void
Example
this.entity.rotateLocal(0, 90, 0);
rotateLocal(rotation: Vec3): void
Rotates the graph node in local space by the specified Euler angles. Eulers are specified in degrees in XYZ order.
Parameters
rotation (Vec3): Vector holding local space rotation.Returns void
Example
const rotation = new Vec3(0, 90, 0);
this.entity.rotateLocal(rotation);
setEulerAngles(x: number, y: number, z: number): void
Sets the world space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.
Parameters
x (number): Rotation around world space x-axis in degrees.y (number): Rotation around world space y-axis in degrees.z (number): Rotation around world space z-axis in degrees.Returns void
Example
this.entity.setEulerAngles(0, 90, 0);
setEulerAngles(angles: Vec3): void
Sets the world space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.
Parameters
angles (Vec3): Vector holding rotations around world space axes in degrees.Returns void
Example
const angles = new Vec3(0, 90, 0);
this.entity.setEulerAngles(angles);
setLocalEulerAngles(x: number, y: number, z: number): void
Sets the local space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.
Parameters
x (number): Rotation around local space x-axis in degrees.y (number): Rotation around local space y-axis in degrees.z (number): Rotation around local space z-axis in degrees.Returns void
Example
// Set rotation of 90 degrees around y-axis via 3 numbers
this.entity.setLocalEulerAngles(0, 90, 0);
setLocalEulerAngles(angles: Vec3): void
Sets the local space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.
Parameters
angles (Vec3): Vector holding rotations around local space axes in degrees.Returns void
Example
// Set rotation of 90 degrees around y-axis via a vector
const angles = new Vec3(0, 90, 0);
this.entity.setLocalEulerAngles(angles);
setLocalPosition(x: number, y: number, z: number): void
Sets the local space position of the specified graph node.
Parameters
x (number): X-coordinate of local space position.y (number): Y-coordinate of local space position.z (number): Z-coordinate of local space position.Returns void
Example
this.entity.setLocalPosition(0, 10, 0);
setLocalPosition(position: Vec3): void
Sets the local space position of the specified graph node.
Parameters
position (Vec3): Vector holding local space position.Returns void
Example
const pos = new Vec3(0, 10, 0);
this.entity.setLocalPosition(pos);
setLocalRotation(x: number, y: number, z: number, w: number): void
Sets the local space rotation of the specified graph node.
Parameters
x (number): X-component of local space quaternion rotation.y (number): Y-component of local space quaternion rotation.z (number): Z-component of local space quaternion rotation.w (number): W-component of local space quaternion rotation.Returns void
Example
this.entity.setLocalRotation(0, 0, 0, 1);
setLocalRotation(rotation: Quat): void
Sets the local space rotation of the specified graph node.
Parameters
rotation (Quat): Quaternion holding local space rotation.Returns void
Example
const q = new Quat();
this.entity.setLocalRotation(q);
setLocalScale(x: number, y: number, z: number): void
Sets the local space scale factor of the specified graph node.
Parameters
x (number): X-coordinate of local space scale.y (number): Y-coordinate of local space scale.z (number): Z-coordinate of local space scale.Returns void
Example
this.entity.setLocalScale(10, 10, 10);
setLocalScale(scale: Vec3): void
Sets the local space scale factor of the specified graph node.
Parameters
scale (Vec3): Vector holding local space scale.Returns void
Example
const scale = new Vec3(10, 10, 10);
this.entity.setLocalScale(scale);
setPosition(x: number, y: number, z: number): void
Sets the world space position of the specified graph node.
Parameters
x (number): X-coordinate of world space position.y (number): Y-coordinate of world space position.z (number): Z-coordinate of world space position.Returns void
Example
this.entity.setPosition(0, 10, 0);
setPosition(position: Vec3): void
Sets the world space position of the specified graph node.
Parameters
position (Vec3): Vector holding world space position.Returns void
Example
const position = new Vec3(0, 10, 0);
this.entity.setPosition(position);
setPositionAndRotation(position: Vec3, rotation: Quat): void
Sets the world space position and rotation of the specified graph node. This is faster than setting the position and rotation independently.
Parameters
Example
const position = new Vec3(0, 10, 0);
const rotation = new Quat().setFromEulerAngles(0, 90, 0);
this.entity.setPositionAndRotation(position, rotation);
setRotation(x: number, y: number, z: number, w: number): void
Sets the world space rotation of the specified graph node.
Parameters
x (number): X-component of world space quaternion rotation.y (number): Y-component of world space quaternion rotation.z (number): Z-component of world space quaternion rotation.w (number): W-component of world space quaternion rotation.Returns void
Example
this.entity.setRotation(0, 0, 0, 1);
setRotation(rotation: Quat): void
Sets the world space rotation of the specified graph node.
Parameters
rotation (Quat): Quaternion holding world space rotation.Returns void
Example
const rotation = new Quat();
this.entity.setRotation(rotation);
translate(x: number, y: number, z: number): void
Translates the graph node in world space by the specified translation vector.
Parameters
x (number): X-coordinate of world space translation.y (number): Y-coordinate of world space translation.z (number): Z-coordinate of world space translation.Returns void
Example
this.entity.translate(10, 0, 0);
translate(translation: Vec3): void
Translates the graph node in world space by the specified translation vector.
Parameters
translation (Vec3): Vector holding world space translation.Returns void
Example
const translation = new Vec3(10, 0, 0);
this.entity.translate(translation);
translateLocal(x: number, y: number, z: number): void
Translates the graph node in local space by the specified translation vector.
Parameters
x (number): X-coordinate of local space translation.y (number): Y-coordinate of local space translation.z (number): Z-coordinate of local space translation.Returns void
Example
this.entity.translateLocal(10, 0, 0);
translateLocal(translation: Vec3): void
Translates the graph node in local space by the specified translation vector.
Parameters
translation (Vec3): Vector holding local space translation.Returns void
Example
const t = new Vec3(10, 0, 0);
this.entity.translateLocal(t);
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Framework
Used to send and receive HTTP requests.
del(url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest
Perform an HTTP DELETE request to the given url with additional options such as headers, retries, credentials, etc.
Parameters
url (string): The URL to make the request to.options (object): Additional options.
options.async (boolean, optional): Make the request asynchronously. Defaults to true.options.cache (boolean, optional): If false, then add a timestamp to the request to prevent caching.options.headers ({}, optional): HTTP headers to add to the request.options.maxRetries (number, optional): If options.retry is true this specifies the maximum
number of retries. Defaults to 5.options.maxRetryDelay (number, optional): If options.retry is true this specifies the
maximum amount of time to wait between retries in milliseconds. Defaults to 5000.options.postdata (any, optional): Data to send in the body of the request.
Some content types are handled automatically. If postdata is an XML Document, it is handled.
If the Content-Type header is set to 'application/json' then the postdata is JSON
stringified. Otherwise, by default, the data is sent as form-urlencoded.options.responseType (string, optional): Override the response type.options.retry (boolean, optional): If true then if the request fails it will be retried with
an exponential backoff.options.withCredentials (boolean, optional): Send cookies with this request. Defaults to false.callback (HttpResponseCallback): The callback used when the response has returned.
Passed (err, data) where data is the response (format depends on response type: text,
Object, ArrayBuffer, XML) and err is the error code.Returns XMLHttpRequest: The request object.
Example
http.del("http://example.com/", {
"retry": true,
"maxRetries": 5
}, (err, response) => {
console.log(response);
});
get(url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest
Perform an HTTP GET request to the given url with additional options such as headers, retries, credentials, etc.
Parameters
url (string): The URL to make the request to.options (object): Additional options.
options.async (boolean, optional): Make the request asynchronously. Defaults to true.options.cache (boolean, optional): If false, then add a timestamp to the request to prevent caching.options.headers ({}, optional): HTTP headers to add to the request.options.maxRetries (number, optional): If options.retry is true this specifies the maximum number of retries. Defaults to 5.options.maxRetryDelay (number, optional): If options.retry is true this specifies the maximum amount of time to wait between retries in milliseconds. Defaults to 5000.options.postdata (any, optional): Data to send in the body of the request.
Some content types are handled automatically. If postdata is an XML Document, it is handled. If
the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
Otherwise, by default, the data is sent as form-urlencoded.options.progress (EventHandler, optional): Object to use for firing progress events.options.responseType (string, optional): Override the response type.options.retry (boolean, optional): If true then if the request fails it will be retried with an exponential backoff.options.withCredentials (boolean, optional): Send cookies with this request. Defaults to false.callback (HttpResponseCallback): The callback used when the response has returned. Passed (err, data)
where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
err is the error code.Returns XMLHttpRequest: The request object.
Example
http.get("http://example.com/", {
"retry": true,
"maxRetries": 5
}, (err, response) => {
console.log(response);
});
post(url: string, data: any, options: object, callback: HttpResponseCallback): XMLHttpRequest
Perform an HTTP POST request to the given url with additional options such as headers, retries, credentials, etc.
Parameters
url (string): The URL to make the request to.data (any): Data to send in the body of the request.
Some content types are handled automatically. If postdata is an XML Document, it is handled.
If the Content-Type header is set to 'application/json' then the postdata is JSON
stringified. Otherwise, by default, the data is sent as form-urlencoded.options (object): Additional options.
options.async (boolean, optional): Make the request asynchronously. Defaults to true.options.cache (boolean, optional): If false, then add a timestamp to the request to prevent caching.options.headers ({}, optional): HTTP headers to add to the request.options.maxRetries (number, optional): If options.retry is true this specifies the maximum
number of retries. Defaults to 5.options.maxRetryDelay (number, optional): If options.retry is true this specifies the
maximum amount of time to wait between retries in milliseconds. Defaults to 5000.options.responseType (string, optional): Override the response type.options.retry (boolean, optional): If true then if the request fails it will be retried with an exponential backoff.options.withCredentials (boolean, optional): Send cookies with this request. Defaults to false.callback (HttpResponseCallback): The callback used when the response has returned.
Passed (err, data) where data is the response (format depends on response type: text,
Object, ArrayBuffer, XML) and err is the error code.Returns XMLHttpRequest: The request object.
Example
http.post("http://example.com/", {
"name": "Alex"
}, {
"retry": true,
"maxRetries": 5
}, (err, response) => {
console.log(response);
});
put(url: string, data: any, options: object, callback: HttpResponseCallback): XMLHttpRequest
Perform an HTTP PUT request to the given url with additional options such as headers, retries, credentials, etc.
Parameters
url (string): The URL to make the request to.data (any): Data to send in the body of the request. Some content types
are handled automatically. If postdata is an XML Document, it is handled. If the
Content-Type header is set to 'application/json' then the postdata is JSON stringified.
Otherwise, by default, the data is sent as form-urlencoded.options (object): Additional options.
options.async (boolean, optional): Make the request asynchronously. Defaults to true.options.cache (boolean, optional): If false, then add a timestamp to the request to prevent caching.options.headers ({}, optional): HTTP headers to add to the request.options.maxRetries (number, optional): If options.retry is true this specifies the maximum
number of retries. Defaults to 5.options.maxRetryDelay (number, optional): If options.retry is true this specifies the
maximum amount of time to wait between retries in milliseconds. Defaults to 5000.options.responseType (string, optional): Override the response type.options.retry (boolean, optional): If true then if the request fails it will be retried with
an exponential backoff.options.withCredentials (boolean, optional): Send cookies with this request. Defaults to false.callback (HttpResponseCallback): The callback used when the response has returned.
Passed (err, data) where data is the response (format depends on response type: text,
Object, ArrayBuffer, XML) and err is the error code.Returns XMLHttpRequest: The request object.
Example
http.put("http://example.com/", {
"name": "Alex"
}, {
"retry": true,
"maxRetries": 5
}, (err, response) => {
console.log(response);
});
request(method: string, url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest
Make a general purpose HTTP request with additional options such as headers, retries, credentials, etc.
Parameters
method (string): The HTTP method "GET", "POST", "PUT", "DELETE".url (string): The url to make the request to.options (object): Additional options.
options.async (boolean, optional): Make the request asynchronously. Defaults to true.options.cache (boolean, optional): If false, then add a timestamp to the request to prevent caching.options.headers ({}, optional): HTTP headers to add to the request.options.maxRetries (number, optional): If options.retry is true this specifies the maximum
number of retries. Defaults to 5.options.maxRetryDelay (number, optional): If options.retry is true this specifies the
maximum amount of time to wait between retries in milliseconds. Defaults to 5000.options.postdata (any, optional): Data to send in the body of the request.
Some content types are handled automatically. If postdata is an XML Document, it is handled.
If the Content-Type header is set to 'application/json' then the postdata is JSON
stringified. Otherwise, by default, the data is sent as form-urlencoded.options.responseType (string, optional): Override the response type.options.retry (boolean, optional): If true then if the request fails it will be retried with
an exponential backoff.options.withCredentials (boolean, optional): Send cookies with this request. Defaults to false.callback (HttpResponseCallback): The callback used when the response has returned.
Passed (err, data) where data is the response (format depends on response type: text,
Object, ArrayBuffer, XML) and err is the error code.Returns XMLHttpRequest: The request object.
Example
http.request("get", "http://example.com/", {
"retry": true,
"maxRetries": 5
}, (err, response) => {
console.log(response);
});
Class · extends EventHandler · category: Framework
Handles localization. Responsible for loading localization assets and returning translations for a certain key. Can also handle plural forms. To override its default behavior define a different implementation for getText and getPluralText.
new I18n(app: AppBase)
Create a new I18n instance.
Parameters
app (AppBase): The application.get assets(): number[] | Asset<string>[]
set assets(value: number[] | Asset<string>[])
Gets the array of asset ids that contain localization data in the expected format.
get locale(): string
set locale(value: string)
Gets the current locale.
addData(data: any): void
Adds localization data. If the locale and key for a translation already exists it will be overwritten.
Parameters
data (any): The localization data. See example for the expected format of the
data.Example
this.app.i18n.addData({
header: {
version: 1
},
data: [{
info: {
locale: 'en-US'
},
messages: {
"key": "translation",
// The number of plural forms depends on the locale. See the manual for more information.
"plural_key": ["one item", "more than one items"]
}
}, {
info: {
locale: 'fr-FR'
},
messages: {
// ...
}
}]
});
destroy(): void
Frees up memory.
findAvailableLocale(desiredLocale: string): string
Returns the first available locale based on the desired locale specified. First tries to find the desired locale in the loaded translations and then tries to find an alternative locale based on the language.
Parameters
desiredLocale (string): The desired locale e.g. en-US.Returns string: The locale found or if no locale is available returns the default en-US
locale.
Example
const locale = this.app.i18n.getText('en-US');
getPluralText(key: string, n: number, locale?: string): string
Returns the pluralized translation for the specified key, number n and locale. If the locale is not specified it will use the current locale.
Parameters
key (string): The localization key.n (number): The number used to determine which plural form to use. E.g. For the
phrase "5 Apples" n equals 5.locale (string, optional): The desired locale.Returns string: The translated text. If no translations are found at all for the locale
then it will return the en-US translation. If no translation exists for that key then it
will return the localization key.
Example
// manually replace {number} in the resulting translation with our number
const localized = this.app.i18n.getPluralText('{number} apples', number).replace("{number}", number);
getText(key: string, locale?: string): string
Returns the translation for the specified key and locale. If the locale is not specified it will use the current locale.
Parameters
key (string): The localization key.locale (string, optional): The desired locale.Returns string: The translated text. If no translations are found at all for the locale
then it will return the en-US translation. If no translation exists for that key then it will
return the localization key.
Example
const localized = this.app.i18n.getText('localization-key');
const localizedFrench = this.app.i18n.getText('localization-key', 'fr-FR');
removeData(data: any): void
Removes localization data.
Parameters
data (any): The localization data. The data is expected to be in the same format
as addData.static EVENT_CHANGE: string = 'change'
Fired when the locale is changed.
Example
app.i18n.on('change', (newLocale, oldLocale) => {
console.log(`Locale changed from ${oldLocale} to ${newLocale}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Framework
Base class that implements reference counting for objects.
get refCount(): number
Gets the current reference count.
decRefCount(): void
Decrements the reference counter.
incRefCount(): void
Increments the reference counter.
Class · extends EventHandler · category: Framework
Tags is a powerful tag management system for categorizing and filtering objects in PlayCanvas applications. It provides an efficient way to attach string identifiers to objects and query them using logical operations.
Tags are automatically available on Assets and Entitys (see Asset#tags and GraphNode#tags). You can search for specific assets via AssetRegistry#findByTag and specific entities via GraphNode#findByTag.
new Tags(parent?: any)
Create a new Tags instance.
Parameters
parent (any, optional): Parent object who tags belong to.get size(): number
Number of tags in set.
add(...args: any[]): boolean
Add a tag, duplicates are ignored. Can be array or comma separated arguments for multiple tags.
Parameters
args (any[]): Name of a tag, or array of tags.Returns boolean: True if any tag were added.
Example
tags.add('level-1');
Example
tags.add('ui', 'settings');
Example
tags.add(['level-2', 'mob']);
clear(): void
Remove all tags.
Example
tags.clear();
has(...query: any[]): boolean
Check if tags satisfy filters. Filters can be provided by simple name of tag, as well as by array of tags. When an array is provided it will check if tags contain each tag within the array. If any of comma separated argument is satisfied, then it will return true. Any number of combinations are valid, and order is irrelevant.
Parameters
query (any[]): Name of a tag or array of tags.Returns boolean: True if filters are satisfied.
Example
tags.has('player'); // player
Example
tags.has('mob', 'player'); // player OR mob
Example
tags.has(['level-1', 'mob']); // monster AND level-1
Example
tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels)
list(): string[]
Returns immutable array of tags.
Returns string[]: Copy of tags array.
remove(...args: any[]): boolean
Remove tag.
Parameters
args (any[]): Name of a tag or array of tags.Returns boolean: True if any tag were removed.
Example
tags.remove('level-1');
Example
tags.remove('ui', 'settings');
Example
tags.remove(['level-2', 'mob']);
static EVENT_ADD: string = 'add'
Fired for each individual tag that is added.
Example
tags.on('add', (tag, parent) => {
console.log(`${tag} added to ${parent.name}`);
});
static EVENT_CHANGE: string = 'change'
Fired when tags have been added or removed. It will fire once on bulk changes, while add
and remove will fire on each tag operation.
Example
tags.on('change', (parent) => {
console.log(`Tags changed on ${parent.name}`);
});
static EVENT_REMOVE: string = 'remove'
Fired for each individual tag that is removed.
Example
tags.on('remove', (tag, parent) => {
console.log(`${tag} removed from ${parent.name}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Framework
Create a Template resource from raw database data.
new Template(app: AppBase, data: any)
Create a new Template instance.
Parameters
app (AppBase): The application.data (any): Asset data from the database.instantiate(): Entity
Create an instance of this template.
Returns Entity: The root entity of the created instance.
Class · category: Framework
A pure static utility class which supports immediate and lazy loading of WebAssembly modules. Note that you can load WebAssembly modules even before instantiating your AppBase instance.
This class is generally only needed if you are developing against the Engine directly. Editor projects automatically load WebAssembly modules included in the project's assets.
Do not use this class to load the Basis WebAssembly module. Instead, please refer to basisInitialize.
Example
// Load the Ammo.js physics engine
WasmModule.setConfig('Ammo', {
glueUrl: `ammo.wasm.js`,
wasmUrl: `ammo.wasm.wasm`,
fallbackUrl: `ammo.js`
});
await new Promise((resolve) => {
WasmModule.getInstance('Ammo', () => resolve());
});
static getConfig(moduleName: string): any
Get a wasm module's configuration.
Parameters
moduleName (string): Name of the module.Returns any: The previously set configuration.
static getInstance(moduleName: string, callback: ModuleInstanceCallback): void
Get a wasm module instance. The instance will be created if necessary and returned in the second parameter to callback.
Parameters
moduleName (string): Name of the module.callback (ModuleInstanceCallback): The function called when the instance is
available.static setConfig(moduleName: string, config?: object): void
Set a wasm module's configuration.
Parameters
moduleName (string): Name of the module.config (object, optional): The configuration object.
config.errorHandler (ModuleErrorCallback, optional): Function to be called if the module fails
to download.config.fallbackUrl (string, optional): URL of the fallback script to use when wasm modules
aren't supported.config.glueUrl (string, optional): URL of glue script.config.numWorkers (number, optional): For modules running on worker threads, the number of
threads to use. Default value is based on module implementation.config.wasmUrl (string, optional): URL of the wasm script.Class · extends EventHandler · category: Gizmo
The base class for all gizmos.
A gizmo is an interactive widget drawn over the scene in its own Layer;
createLayer makes such a layer and adds it to the scene and the camera. Construct a gizmo
for a CameraComponent, then attach the GraphNodes it should act on, which
are then listed in nodes; detach releases them. A gizmo updates and renders
itself from the application's update and prerender hooks, so it needs no per-frame call and is
torn down with destroy. size scales the widget, which otherwise keeps a constant
apparent size as the camera moves; coordSpace selects 'world' or 'local' axes;
enabled hides it without detaching; and mouseButtons chooses which buttons
interact. Pointer interaction is reported through the pointer:down, pointer:move and
pointer:up events, node changes through nodes:attach and nodes:detach, and the
resulting transforms through position:update, rotation:update and scale:update.
TransformGizmo builds the translate, rotate and scale gizmos on this base.
new Gizmo(camera: CameraComponent, layer: Layer, name?: string)
Creates a new Gizmo object.
Parameters
camera (CameraComponent): The camera component.layer (Layer): The render layer. This can be provided by the user or will be created
and added to the scene and camera if not provided. Successive gizmos will share the same layer
and will be removed from the camera and scene when the last gizmo is destroyed.name (string, optional, default 'gizmo'): The name of the gizmo. Defaults to 'gizmo'.Example
const gizmo = new Gizmo(camera, layer);
protected _app: AppBase
Internal reference to the app containing the gizmo.
protected _camera: CameraComponent
Internal reference to camera component to view the gizmo.
protected _coordSpace: GizmoSpace = 'world'
Internal version of coordinate space. Defaults to 'world'.
protected _device: GraphicsDevice
Internal reference to the graphics device of the app.
protected _handles: EventHandle[] = []
Internal list of app event handles for the gizmo.
protected _layer: Layer
Internal reference to layer to render the gizmo..
protected _mouseButtons: [boolean, boolean, boolean]
Internal array of mouse buttons that can interact with the gizmo.
protected _renderUpdate: boolean = false
Internal flag to track if a render update is required.
protected _scale: number = 1
Internal version of the gizmo scale. Defaults to 1.
intersectShapes: Shape[] = []
The intersection shapes for the gizmo.
nodes: GraphNode[] = []
The graph nodes attached to the gizmo.
preventDefault: boolean = true
Flag to indicate whether to call preventDefault on pointer events.
root: Entity
The root gizmo entity.
get camera(): CameraComponent
set camera(camera: CameraComponent)
Gets the camera component to view the gizmo.
protected get cameraDir(): Vec3
get coordSpace(): GizmoSpace
set coordSpace(value: GizmoSpace)
Gets the gizmo coordinate space.
get enabled(): boolean
set enabled(state: boolean)
Gets the gizmo enabled state.
protected get facingDir(): Vec3
get layer(): Layer
set layer(layer: Layer)
Gets the gizmo render layer.
get mouseButtons(): [boolean, boolean, boolean]
Array of mouse buttons that can interact with the gizmo. The button indices are defined as:
The full list of button indices can be found here: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
get size(): number
set size(value: number)
Gets the gizmo size.
protected _updatePosition(): void
protected _updateRotation(): void
protected _updateScale(): void
attach(nodes?: GraphNode | GraphNode[]): void
Attach an array of graph nodes to the gizmo.
Parameters
Example
const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
destroy(): void
Detaches all graph nodes and destroys the gizmo instance.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.destroy();
detach(): void
Detaches all graph nodes from the gizmo.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.detach();
prerender(): void
Pre-render method. This is called before the gizmo is rendered.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.prerender();
update(): void
Updates the gizmo position, rotation, and scale.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.update();
static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer
Creates a new gizmo layer and adds it to the scene.
Parameters
app (AppBase): The app.layerName (string, optional, default 'Gizmo'): The layer name. Defaults to 'Gizmo'.layerIndex (number, optional, default app.scene.layers.layerList.length): The layer index. Defaults to the end of the layer list.Returns Layer: The new layer.
static EVENT_NODESATTACH: string = 'nodes:attach'
Fired when graph nodes are attached.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('nodes:attach', () => {
console.log('Graph nodes attached');
});
static EVENT_NODESDETACH: string = 'nodes:detach'
Fired when graph nodes are detached.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('nodes:detach', () => {
console.log('Graph nodes detached');
});
static EVENT_POINTERDOWN: string = 'pointer:down'
Fired when the pointer is down on the gizmo.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:down', (x, y, meshInstance) => {
console.log(`Pointer was down on ${meshInstance.node.name} at ${x}, ${y}`);
});
static EVENT_POINTERMOVE: string = 'pointer:move'
Fired when the pointer is moving over the gizmo.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:move', (x, y, meshInstance) => {
console.log(`Pointer was moving on ${meshInstance.node.name} at ${x}, ${y}`);
});
static EVENT_POINTERUP: string = 'pointer:up'
Fired when the pointer is up off the gizmo.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:up', (x, y, meshInstance) => {
console.log(`Pointer was up on ${meshInstance.node.name} at ${x}, ${y}`);
})
static EVENT_POSITIONUPDATE: string = 'position:update'
Fired when the gizmo's position is updated.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('position:update', (position) => {
console.log(`The gizmo's position was updated to ${position}`);
})
static EVENT_RENDERUPDATE: string = 'render:update'
Fired when the gizmo render has updated.
Example
const gizmo = new TransformGizmo(camera, layer);
gizmo.on('render:update', () => {
console.log('Gizmo render has been updated');
});
static EVENT_ROTATIONUPDATE: string = 'rotation:update'
Fired when the gizmo's rotation is updated.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('rotation:update', (rotation) => {
console.log(`The gizmo's rotation was updated to ${rotation}`);
});
static EVENT_SCALEUPDATE: string = 'scale:update'
Fired when the gizmo's scale is updated.
Example
const gizmo = new Gizmo(camera, layer);
gizmo.on('scale:update', (scale) => {
console.log(`The gizmo's scale was updated to ${scale}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends TransformGizmo · category: Gizmo
The RotateGizmo provides interactive 3D manipulation handles for rotating/reorienting Entitys in a Scene. It creates a visual widget with a draggable ring for each axis of rotation, plus a fourth ring for rotation in the camera's view plane, allowing precise control over object orientation through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.
Note that the gizmo can be driven by both mouse+keyboard and touch input.
// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);
// Create a rotate gizmo
const gizmo = new RotateGizmo(cameraComponent, gizmoLayer);
// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
type: 'box'
});
app.root.addChild(entity);
// Attach the gizmo to the entity
gizmo.attach([entity]);
Relevant Engine API examples:
new RotateGizmo(camera: CameraComponent, layer: Layer)
Creates a new RotateGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.
Parameters
camera (CameraComponent): The camera component.layer (Layer): The layer responsible for rendering the gizmo.Example
const gizmo = new RotateGizmo(camera, layer);
protected _shapes: { f: ArcShape; x: ArcShape; xyz: SphereShape; y: ArcShape; z: ArcShape }
Internal object containing the gizmo shapes to render.
Properties
f (ArcShape, optional)x (ArcShape, optional)xyz (SphereShape, optional)y (ArcShape, optional)z (ArcShape, optional)rotationMode: "absolute" | "orbit" = 'absolute'
The rotation mode of the gizmo. This can be either:
snapIncrement: number = 5
get angleGuideThickness(): number
set angleGuideThickness(value: number)
Gets the angle guide line thickness.
get centerRadius(): number
set centerRadius(value: number)
Gets the center radius.
get faceRingRadius(): number
set faceRingRadius(value: number)
Gets the face ring radius.
get faceTubeRadius(): number
set faceTubeRadius(value: number)
Gets the face tube radius.
get ringTolerance(): number
set ringTolerance(value: number)
Gets the ring tolerance.
get xyzRingRadius(): number
set xyzRingRadius(value: number)
Gets the XYZ ring radius.
get xyzTubeRadius(): number
set xyzTubeRadius(value: number)
Gets the XYZ tube radius.
protected _calculateArcAngle(point: Vec3, x: number, y: number): number
Parameters
point (Vec3): The point.x (number): The x coordinate.y (number): The y coordinate.Returns number: The angle.
_drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void
Parameters
pos (Vec3): The position.rot (Quat): The rotation.activeAxis (GizmoAxis): The active axis.activeIsPlane (boolean): Whether the active axis is a plane.protected _screenToPoint(x: number, y: number): Vec3
Parameters
x (number): The x coordinate.y (number): The y coordinate.Returns Vec3: The point (space is TransformGizmo#coordSpace).
destroy(): void
prerender(): void
protected _app: AppBaseprotected _camera: CameraComponentprotected _coordSpace: GizmoSpace = 'world'protected _device: GraphicsDeviceprotected _handles: EventHandle[] = []protected _layer: Layerprotected _mouseButtons: [boolean, boolean, boolean]protected _renderUpdate: boolean = falseprotected _rootStartPos: Vec3protected _rootStartRot: Quatprotected _scale: number = 1protected _selectedAxis: "" | GizmoAxis = ''protected _selectedIsPlane: boolean = falseprotected _selectionStartPoint: Vec3protected _theme: GizmoThemedragMode: GizmoDragMode = 'selected'intersectShapes: Shape[] = []nodes: GraphNode[] = []preventDefault: boolean = trueroot: Entitysnap: boolean = falseprotected get _dragging(): booleanget camera(): CameraComponent · set camera(camera: CameraComponent)protected get cameraDir(): Vec3get coordSpace(): GizmoSpace · set coordSpace(value: GizmoSpace)get enabled(): boolean · set enabled(state: boolean)protected get facingDir(): Vec3get layer(): Layer · set layer(layer: Layer)get mouseButtons(): [boolean, boolean, boolean]get size(): number · set size(value: number)get theme(): GizmoThemeprotected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Planeprotected _createRay(mouseWPos: Vec3): Rayprotected _createTransform(): voidprotected _dirFromAxis(axis: string, dir: Vec3): Vec3protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): voidprotected _projectToAxis(point: Vec3, axis: string): voidprotected _updatePosition(): voidprotected _updateRotation(): voidprotected _updateScale(): voidattach(nodes?: GraphNode | GraphNode[]): voiddetach(): voidenableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanisShapeEnabled(shapeAxis: "face" | GizmoAxis): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlesetTheme(partial: object): voidupdate(): voidstatic createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layerstatic EVENT_NODESATTACH: string = 'nodes:attach'static EVENT_NODESDETACH: string = 'nodes:detach'static EVENT_POINTERDOWN: string = 'pointer:down'static EVENT_POINTERMOVE: string = 'pointer:move'static EVENT_POINTERUP: string = 'pointer:up'static EVENT_POSITIONUPDATE: string = 'position:update'static EVENT_RENDERUPDATE: string = 'render:update'static EVENT_ROTATIONUPDATE: string = 'rotation:update'static EVENT_SCALEUPDATE: string = 'scale:update'static EVENT_TRANSFORMEND: string = 'transform:end'static EVENT_TRANSFORMMOVE: string = 'transform:move'static EVENT_TRANSFORMSTART: string = 'transform:start'Class · extends TransformGizmo · category: Gizmo
The ScaleGizmo provides interactive 3D manipulation handles for scaling/resizing Entitys in a Scene. It creates a visual widget with box-tipped lines along the X, Y and Z axes, planes at their intersections, and a center box, allowing precise control over object scaling through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.
Note that the gizmo can be driven by both mouse+keyboard and touch input.
// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);
// Create a scale gizmo
const gizmo = new ScaleGizmo(cameraComponent, gizmoLayer);
// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
type: 'box'
});
app.root.addChild(entity);
// Attach the gizmo to the entity
gizmo.attach([entity]);
Relevant Engine API examples:
new ScaleGizmo(camera: CameraComponent, layer: Layer)
Creates a new ScaleGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.
Parameters
camera (CameraComponent): The camera component.layer (Layer): The layer responsible for rendering the gizmo.Example
const gizmo = new ScaleGizmo(camera, layer);
protected _coordSpace: GizmoSpace = 'local'
protected _shapes: { x: BoxLineShape; xy: PlaneShape; xyz: BoxShape; xz: PlaneShape; y: BoxLineShape; yz: PlaneShape; z: BoxLineShape }
Internal object containing the gizmo shapes to render.
Properties
x (BoxLineShape, optional)xy (PlaneShape, optional)xyz (BoxShape, optional)xz (PlaneShape, optional)y (BoxLineShape, optional)yz (PlaneShape, optional)z (BoxLineShape, optional)protected _uniform: boolean = false
Internal state if transform should use uniform scaling.
flipPlanes: boolean = true
Flips the planes to face the camera.
lowerBoundScale: Vec3
The lower bound for scaling.
snapIncrement: number = 1
get axisBoxSize(): number
set axisBoxSize(value: number)
Gets the axis box size.
get axisCenterSize(): number
set axisCenterSize(value: number)
Gets the axis center size.
get axisGap(): number
set axisGap(value: number)
Gets the axis gap.
get axisLineLength(): number
set axisLineLength(value: number)
Gets the axis line length.
get axisLineThickness(): number
set axisLineThickness(value: number)
Gets the axis line thickness.
get axisLineTolerance(): number
set axisLineTolerance(value: number)
Gets the axis line tolerance.
get axisPlaneGap(): number
set axisPlaneGap(value: number)
Gets the plane gap.
get axisPlaneSize(): number
set axisPlaneSize(value: number)
Gets the plane size.
get coordSpace(): GizmoSpace
set coordSpace(value: GizmoSpace)
Sets the gizmo coordinate space. Defaults to 'world'
get uniform(): boolean
set uniform(value: boolean)
Gets the uniform scaling state for planes.
protected _screenToPoint(x: number, y: number): Vec3
Parameters
x (number): The x coordinate.y (number): The y coordinate.Returns Vec3: The point (space is TransformGizmo#coordSpace).
prerender(): void
protected _app: AppBaseprotected _camera: CameraComponentprotected _device: GraphicsDeviceprotected _handles: EventHandle[] = []protected _layer: Layerprotected _mouseButtons: [boolean, boolean, boolean]protected _renderUpdate: boolean = falseprotected _rootStartPos: Vec3protected _rootStartRot: Quatprotected _scale: number = 1protected _selectedAxis: "" | GizmoAxis = ''protected _selectedIsPlane: boolean = falseprotected _selectionStartPoint: Vec3protected _theme: GizmoThemedragMode: GizmoDragMode = 'selected'intersectShapes: Shape[] = []nodes: GraphNode[] = []preventDefault: boolean = trueroot: Entitysnap: boolean = falseprotected get _dragging(): booleanget camera(): CameraComponent · set camera(camera: CameraComponent)protected get cameraDir(): Vec3get enabled(): boolean · set enabled(state: boolean)protected get facingDir(): Vec3get layer(): Layer · set layer(layer: Layer)get mouseButtons(): [boolean, boolean, boolean]get size(): number · set size(value: number)get theme(): GizmoThemeprotected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Planeprotected _createRay(mouseWPos: Vec3): Rayprotected _createTransform(): voidprotected _dirFromAxis(axis: string, dir: Vec3): Vec3protected _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: "" | GizmoAxis, activeIsPlane: boolean): voidprotected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): voidprotected _projectToAxis(point: Vec3, axis: string): voidprotected _updatePosition(): voidprotected _updateRotation(): voidprotected _updateScale(): voidattach(nodes?: GraphNode | GraphNode[]): voiddestroy(): voiddetach(): voidenableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanisShapeEnabled(shapeAxis: "face" | GizmoAxis): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlesetTheme(partial: object): voidupdate(): voidstatic createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layerstatic EVENT_NODESATTACH: string = 'nodes:attach'static EVENT_NODESDETACH: string = 'nodes:detach'static EVENT_POINTERDOWN: string = 'pointer:down'static EVENT_POINTERMOVE: string = 'pointer:move'static EVENT_POINTERUP: string = 'pointer:up'static EVENT_POSITIONUPDATE: string = 'position:update'static EVENT_RENDERUPDATE: string = 'render:update'static EVENT_ROTATIONUPDATE: string = 'rotation:update'static EVENT_SCALEUPDATE: string = 'scale:update'static EVENT_TRANSFORMEND: string = 'transform:end'static EVENT_TRANSFORMMOVE: string = 'transform:move'static EVENT_TRANSFORMSTART: string = 'transform:start'Class · extends Gizmo · category: Gizmo
The base class for all transform gizmos.
It adds to Gizmo everything the TranslateGizmo, RotateGizmo and
ScaleGizmo share: colored X, Y and Z handles with plane and center shapes, any of which
enableShape can turn off; a drag interaction that fires transform:start,
transform:move with the position or angle delta so far, and transform:end; snap
with snapIncrement to quantize the change; dragMode to show, hide or keep only
the selected shape while dragging; and a color theme adjusted through setTheme,
xAxisColor, yAxisColor, zAxisColor and colorAlpha. The
subclasses decide what a drag does to the attached nodes.
new TransformGizmo(camera: CameraComponent, layer: Layer, name?: string)
Creates a new TransformGizmo object.
Parameters
camera (CameraComponent): The camera component.layer (Layer): The render layer.name (string, optional, default 'gizmo:transform'): The name of the gizmo.Example
const gizmo = new TransformGizmo(camera, layer);
protected _rootStartPos: Vec3
Internal gizmo starting rotation in world space.
protected _rootStartRot: Quat
Internal gizmo starting rotation in world space.
protected _selectedAxis: "" | GizmoAxis = ''
Internal currently selected axis.
protected _selectedIsPlane: boolean = false
Internal state of if currently selected shape is a plane.
protected _selectionStartPoint: Vec3
Internal selection starting coordinates in world space.
protected _shapes: { f?: Shape; x?: Shape; xy?: Shape; xyz?: Shape; xz?: Shape; y?: Shape; yz?: Shape; z?: Shape } = {}
Internal object containing the gizmo shapes to render.
Properties
f (Shape, optional)x (Shape, optional)xy (Shape, optional)xyz (Shape, optional)xz (Shape, optional)y (Shape, optional)yz (Shape, optional)z (Shape, optional)protected _theme: GizmoTheme
Internal theme.
dragMode: GizmoDragMode = 'selected'
Whether to hide the shapes when dragging. Defaults to 'selected'.
snap: boolean = false
Whether snapping is enabled. Defaults to false.
snapIncrement: number = 1
Snapping increment. Defaults to 1.
protected get _dragging(): boolean
get theme(): GizmoTheme
Gets the current theme for the gizmo.
protected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Plane
Parameters
axis (string): The axis to create the plane for.isFacing (boolean): Whether the axis is facing the camera.isLine (boolean): Whether the axis is a line.Returns Plane: - The plane.
protected _createRay(mouseWPos: Vec3): Ray
Parameters
mouseWPos (Vec3): The mouse world position.Returns Ray: - The ray.
protected _createTransform(): void
protected _dirFromAxis(axis: string, dir: Vec3): Vec3
Parameters
axis (string): The axisdir (Vec3): The directionReturns Vec3: - The direction
protected _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: "" | GizmoAxis, activeIsPlane: boolean): void
Parameters
pos (Vec3): The position.rot (Quat): The rotation.activeAxis ("" | GizmoAxis): The active axis.activeIsPlane (boolean): Whether the active axis is a plane.protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void
Parameters
protected _projectToAxis(point: Vec3, axis: string): void
Parameters
point (Vec3): The point to project.axis (string): The axis to project to.protected _screenToPoint(x: number, y: number, isFacing?: boolean, isLine?: boolean): Vec3
Parameters
x (number): The x coordinate.y (number): The y coordinate.isFacing (boolean, optional, default false): Whether the axis is facing the camera.isLine (boolean, optional, default false): Whether the axis is a line.Returns Vec3: The point (space is Gizmo#coordSpace).
destroy(): void
enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void
Set the shape to be enabled or disabled.
Parameters
shapeAxis ("face" | GizmoAxis): The shape axis.enabled (boolean): The enabled state of shape.isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean
Get the enabled state of the shape.
Parameters
shapeAxis ("face" | GizmoAxis): The shape axis. Can be:Returns boolean: - Then enabled state of the shape
prerender(): void
setTheme(partial: object): void
Sets the theme or partial theme for the gizmo.
Parameters
partial (object): The partial theme to set.
partial.disabled (Partial<Color>, optional): The disabled color.partial.guideBase (Partial<{ x: Color; y: Color; z: Color }>, optional): The guide line colors.partial.guideOcclusion (number, optional): The guide occlusion value. Defaults to 0.8.partial.shapeBase (Partial<{ f: Color; x: Color; xyz: Color; y: Color; z: Color }>, optional): The axis colors.partial.shapeHover (Partial<{ f: Color; x: Color; xyz: Color; y: Color; z: Color }>, optional): The hover colors.static EVENT_TRANSFORMEND: string = 'transform:end'
Fired when the transformation has ended.
Example
const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:end', () => {
console.log('Transformation ended');
});
static EVENT_TRANSFORMMOVE: string = 'transform:move'
Fired during the transformation.
Example
const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:move', (pointDelta, angleDelta) => {
console.log(`Transformation moved by ${pointDelta} (angle: ${angleDelta})`);
});
static EVENT_TRANSFORMSTART: string = 'transform:start'
Fired when the transformation has started.
Example
const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:start', () => {
console.log('Transformation started');
});
protected _app: AppBaseprotected _camera: CameraComponentprotected _coordSpace: GizmoSpace = 'world'protected _device: GraphicsDeviceprotected _handles: EventHandle[] = []protected _layer: Layerprotected _mouseButtons: [boolean, boolean, boolean]protected _renderUpdate: boolean = falseprotected _scale: number = 1intersectShapes: Shape[] = []nodes: GraphNode[] = []preventDefault: boolean = trueroot: Entityget camera(): CameraComponent · set camera(camera: CameraComponent)protected get cameraDir(): Vec3get coordSpace(): GizmoSpace · set coordSpace(value: GizmoSpace)get enabled(): boolean · set enabled(state: boolean)protected get facingDir(): Vec3get layer(): Layer · set layer(layer: Layer)get mouseButtons(): [boolean, boolean, boolean]get size(): number · set size(value: number)protected _updatePosition(): voidprotected _updateRotation(): voidprotected _updateScale(): voidattach(nodes?: GraphNode | GraphNode[]): voiddetach(): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleupdate(): voidstatic createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layerstatic EVENT_NODESATTACH: string = 'nodes:attach'static EVENT_NODESDETACH: string = 'nodes:detach'static EVENT_POINTERDOWN: string = 'pointer:down'static EVENT_POINTERMOVE: string = 'pointer:move'static EVENT_POINTERUP: string = 'pointer:up'static EVENT_POSITIONUPDATE: string = 'position:update'static EVENT_RENDERUPDATE: string = 'render:update'static EVENT_ROTATIONUPDATE: string = 'rotation:update'static EVENT_SCALEUPDATE: string = 'scale:update'Class · extends TransformGizmo · category: Gizmo
The TranslateGizmo provides interactive 3D manipulation handles for translating/moving Entitys in a Scene. It creates a visual widget with arrows along the X, Y and Z axes, planes at their intersections, and a center sphere, allowing precise control over object positioning through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.
Note that the gizmo can be driven by both mouse+keyboard and touch input.
// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);
// Create a translate gizmo
const gizmo = new TranslateGizmo(cameraComponent, gizmoLayer);
// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
type: 'box'
});
app.root.addChild(entity);
// Attach the gizmo to the entity
gizmo.attach([entity]);
Relevant Engine API examples:
new TranslateGizmo(camera: CameraComponent, layer: Layer)
Creates a new TranslateGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.
Parameters
camera (CameraComponent): The camera component.layer (Layer): The layer responsible for rendering the gizmo.Example
const gizmo = new TranslateGizmo(camera, layer);
protected _shapes: { x: ArrowShape; xy: PlaneShape; xyz: SphereShape; xz: PlaneShape; y: ArrowShape; yz: PlaneShape; z: ArrowShape }
Internal object containing the gizmo shapes to render.
Properties
x (ArrowShape, optional)xy (PlaneShape, optional)xyz (SphereShape, optional)xz (PlaneShape, optional)y (ArrowShape, optional)yz (PlaneShape, optional)z (ArrowShape, optional)flipPlanes: boolean = true
Flips the planes to face the camera.
snapIncrement: number = 1
get axisArrowLength(): number
set axisArrowLength(value: number)
Gets the arrow length.
get axisArrowThickness(): number
set axisArrowThickness(value: number)
Gets the arrow thickness.
get axisCenterSize(): number
set axisCenterSize(value: number)
Gets the axis center size.
get axisGap(): number
set axisGap(value: number)
Gets the axis gap.
get axisLineLength(): number
set axisLineLength(value: number)
Gets the axis line length.
get axisLineThickness(): number
set axisLineThickness(value: number)
Gets the axis line thickness.
get axisLineTolerance(): number
set axisLineTolerance(value: number)
Gets the axis line tolerance.
get axisPlaneGap(): number
set axisPlaneGap(value: number)
Gets the plane gap.
get axisPlaneSize(): number
set axisPlaneSize(value: number)
Gets the plane size.
_drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void
Parameters
pos (Vec3): The position.rot (Quat): The rotation.activeAxis (GizmoAxis): The active axis.activeIsPlane (boolean): Whether the active axis is a plane.protected _screenToPoint(x: number, y: number): Vec3
Parameters
x (number): The x coordinate.y (number): The y coordinate.Returns Vec3: The point (space is TransformGizmo#coordSpace).
prerender(): void
protected _app: AppBaseprotected _camera: CameraComponentprotected _coordSpace: GizmoSpace = 'world'protected _device: GraphicsDeviceprotected _handles: EventHandle[] = []protected _layer: Layerprotected _mouseButtons: [boolean, boolean, boolean]protected _renderUpdate: boolean = falseprotected _rootStartPos: Vec3protected _rootStartRot: Quatprotected _scale: number = 1protected _selectedAxis: "" | GizmoAxis = ''protected _selectedIsPlane: boolean = falseprotected _selectionStartPoint: Vec3protected _theme: GizmoThemedragMode: GizmoDragMode = 'selected'intersectShapes: Shape[] = []nodes: GraphNode[] = []preventDefault: boolean = trueroot: Entitysnap: boolean = falseprotected get _dragging(): booleanget camera(): CameraComponent · set camera(camera: CameraComponent)protected get cameraDir(): Vec3get coordSpace(): GizmoSpace · set coordSpace(value: GizmoSpace)get enabled(): boolean · set enabled(state: boolean)protected get facingDir(): Vec3get layer(): Layer · set layer(layer: Layer)get mouseButtons(): [boolean, boolean, boolean]get size(): number · set size(value: number)get theme(): GizmoThemeprotected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Planeprotected _createRay(mouseWPos: Vec3): Rayprotected _createTransform(): voidprotected _dirFromAxis(axis: string, dir: Vec3): Vec3protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): voidprotected _projectToAxis(point: Vec3, axis: string): voidprotected _updatePosition(): voidprotected _updateRotation(): voidprotected _updateScale(): voidattach(nodes?: GraphNode | GraphNode[]): voiddestroy(): voiddetach(): voidenableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanisShapeEnabled(shapeAxis: "face" | GizmoAxis): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlesetTheme(partial: object): voidupdate(): voidstatic createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layerstatic EVENT_NODESATTACH: string = 'nodes:attach'static EVENT_NODESDETACH: string = 'nodes:detach'static EVENT_POINTERDOWN: string = 'pointer:down'static EVENT_POINTERMOVE: string = 'pointer:move'static EVENT_POINTERUP: string = 'pointer:up'static EVENT_POSITIONUPDATE: string = 'position:update'static EVENT_RENDERUPDATE: string = 'render:update'static EVENT_ROTATIONUPDATE: string = 'rotation:update'static EVENT_SCALEUPDATE: string = 'scale:update'static EVENT_TRANSFORMEND: string = 'transform:end'static EVENT_TRANSFORMMOVE: string = 'transform:move'static EVENT_TRANSFORMSTART: string = 'transform:start'Class · category: Graphics
Holds information about batched mesh instances. Created in BatchManager#create.
new Batch(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId: number)
Create a new Batch instance.
Parameters
meshInstances (MeshInstance[]): The mesh instances to be batched.dynamic (boolean): Whether this batch is dynamic (supports transforming mesh
instances at runtime).batchGroupId (number): Link this batch to a specific batch group. This is done
automatically with default batches.batchGroupId: number
Link this batch to a specific batch group. This is done automatically with default batches.
dynamic: boolean
Whether this batch is dynamic (supports transforming mesh instances at runtime).
meshInstance: MeshInstance = null
A single combined mesh instance, the result of batching.
origMeshInstances: MeshInstance[]
An array of original mesh instances, from which this batch was generated.
destroy(scene: Scene, layers: number[]): void
Removes the batch from the layers and destroys it.
Parameters
scene (Scene): The scene.layers (number[]): The layers to remove the batch from.Class · category: Graphics
Holds mesh batching settings and a unique id. Created via BatchManager#addGroup.
new BatchGroup(id: number, name: string, dynamic: boolean, maxAabbSize: number, layers?: number[])
Create a new BatchGroup instance.
Parameters
id (number): Unique id. Can be assigned to model, render and element components.name (string): The name of the group.dynamic (boolean): Whether objects within this batch group should support
transforming at runtime.maxAabbSize (number): Maximum size of any dimension of a bounding box around batched
objects. BatchManager#prepare will split objects into local groups based on this
size.layers (number[], optional): Layer ID array. Default is [LAYERID_WORLD]. The whole
batch group will belong to these layers. Layers of source models will be ignored.dynamic: boolean
Whether objects within this batch group should support transforming at runtime.
id: number
Unique id. Can be assigned to model, render and element components.
layers: number[]
Layer ID array. Default is [LAYERID_WORLD]. The whole batch group will belong to these layers. Layers of source models will be ignored.
maxAabbSize: number
Maximum size of any dimension of a bounding box around batched objects. BatchManager#prepare will split objects into local groups based on this size.
name: string
Name of the group.
Class · category: Graphics
Glues many mesh instances into a single one for better performance.
new BatchManager(device: GraphicsDevice, root: Entity, scene: Scene)
Create a new BatchManager instance.
Parameters
device (GraphicsDevice): The graphics device used by the batch manager.root (Entity): The entity under which batched models are added.scene (Scene): The scene that the batch manager affects.addGroup(name: string, dynamic: boolean, maxAabbSize: number, id?: number, layers?: number[]): BatchGroup
Adds new global batch group.
Parameters
name (string): Custom name.dynamic (boolean): Is this batch group dynamic? Will these objects move/rotate/scale
after being batched?maxAabbSize (number): Maximum size of any dimension of a bounding box around batched
objects. prepare will split objects into local groups based on this size.id (number, optional): Optional custom unique id for the group (will be generated
automatically otherwise).layers (number[], optional): Optional layer ID array. Default is [LAYERID_WORLD].
The whole batch group will belong to these layers. Layers of source models will be ignored.Returns BatchGroup: Group object.
create(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId?: number): Batch
Takes a mesh instance list that has been prepared by prepare, and returns a Batch object. This method assumes that all mesh instances provided can be rendered in a single draw call.
Parameters
meshInstances (MeshInstance[]): Input list of mesh instances.dynamic (boolean): Is it a static or dynamic batch? Will objects be transformed
after batching?batchGroupId (number, optional): Link this batch to a specific batch group. This is done
automatically with default batches.Returns Batch: The resulting batch object.
generate(groupIds?: number[]): void
Destroys all batches and creates new based on scene models. Hides original models. Called by engine automatically on app start, and if batchGroupIds on models are changed.
Parameters
groupIds (number[], optional): Optional array of batch group IDs to update. Otherwise all
groups are updated.getGroupById(id: number): BatchGroup | null
Retrieves a BatchGroup object with a corresponding id, if it exists, or null otherwise.
Parameters
id (number): The batch group id.Returns BatchGroup | null: The batch group matching the id or null if not found.
getGroupByName(name: string): BatchGroup | null
Retrieves a BatchGroup object with a corresponding name, if it exists, or null otherwise.
Parameters
name (string): Name.Returns BatchGroup | null: The batch group matching the name or null if not found.
markGroupDirty(id: number): void
Mark a specific batch group as dirty. Dirty groups are re-batched before the next frame is rendered. Note, re-batching a group is a potentially expensive operation.
Parameters
id (number): Batch Group ID to mark as dirty.prepare(meshInstances: MeshInstance[], dynamic: boolean, maxAabbSize?: number, translucent: boolean): MeshInstance[][]
Takes a list of mesh instances to be batched and sorts them into lists one for each draw call. The input list will be split, if:
Parameters
meshInstances (MeshInstance[]): Input list of mesh instancesdynamic (boolean): Are we preparing for a dynamic batch? Instance count will matter
then (otherwise not).maxAabbSize (number, optional, default Number.POSITIVE_INFINITY): Maximum size of any dimension of a bounding box around batched
objects.translucent (boolean): Are we batching UI elements or sprites
This is useful to keep a balance between the number of draw calls and the number of drawn
triangles, because smaller batches can be hidden when not visible in camera.Returns MeshInstance[][]: An array of arrays of mesh instances, each valid to pass to
create.
removeGroup(id: number): void
Remove global batch group by id. Note, this traverses the entire scene graph and clears the batch group id from all components.
Parameters
id (number): Batch Group ID.Class · category: Graphics
A base class to describe the format of the resource for BindGroupFormat.
new BindBaseFormat(name: string, visibility: number)
Create a new instance.
Parameters
name (string): The name of the resource.
visibility (number): A bit-flag that specifies the shader stages in which the resource
is visible. Can be:
name: string
Class · category: Graphics
BindGroupFormat is a data structure that defines the layout of resources (buffers, textures, samplers) used by rendering or compute shaders. It describes the binding points for each resource type, and the visibility of these resources in the shader stages. Currently this class is only used on WebGPU platform to specify the input and output resources for vertex, fragment and compute shaders written in SHADERLANGUAGE_WGSL language.
Call BindGroupFormat#destroy when no longer needed. On WebGPU, the graphics device retains bind group formats for device recovery until they are explicitly destroyed.
new BindGroupFormat(graphicsDevice: GraphicsDevice, formats: (BindTextureFormat | BindStorageTextureFormat | BindUniformBufferFormat | BindStorageBufferFormat)[])
Create a new instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this vertex format.formats ((BindTextureFormat | BindStorageTextureFormat | BindUniformBufferFormat | BindStorageBufferFormat)[]): An array of bind formats. Note that each entry in the array uses up one slot. The exception
is a texture format that has a sampler, which uses up two slots. The slots are allocated
sequentially, starting from 0.bufferFormatsMap: Map<string, number>
device: GraphicsDevice
storageBufferFormatsMap: Map<string, number>
storageTextureFormatsMap: Map<string, number>
textureFormatsMap: Map<string, number>
destroy(): void
Frees resources associated with this bind group.
Class · extends BindBaseFormat · category: Graphics
A class to describe the format of the storage buffer for BindGroupFormat.
new BindStorageBufferFormat(name: string, visibility: number, readOnly?: boolean)
Create a new instance.
Parameters
name (string): The name of the storage buffer.
visibility (number): A bit-flag that specifies the shader stages in which the storage
buffer is visible. Can be:
readOnly (boolean, optional, default false): Whether the storage buffer is read-only, or read-write. Defaults
to false. This has to be true for the storage buffer used in the vertex shader.
name: stringClass · extends BindBaseFormat · category: Graphics
A class to describe the format of the storage texture for BindGroupFormat. Storage texture is a texture created with the storage flag set to true, which allows it to be used as an output of a compute shader.
Note: At the current time, storage textures are only supported in compute shaders in a write-only mode.
new BindStorageTextureFormat(name: string, format?: number, textureDimension?: string, write?: boolean, read?: boolean)
Create a new instance.
Parameters
name (string): The name of the storage buffer.
format (number, optional, default PIXELFORMAT_RGBA8): The pixel format of the texture. Note that not all formats can be
used. Defaults to PIXELFORMAT_RGBA8.
textureDimension (string, optional, default TEXTUREDIMENSION_2D): The dimension of the texture. Defaults to
TEXTUREDIMENSION_2D. Can be:
write (boolean, optional, default true): Whether the storage texture is writable. Defaults to true.
read (boolean, optional, default false): Whether the storage texture is readable. Defaults to false. Note
that storage texture reads are only supported if
GraphicsDevice#supportsStorageTextureRead is true. Also note that only a subset of
pixel formats can be used for storage texture reads - as an example, PIXELFORMAT_RGBA8 is not
compatible, but PIXELFORMAT_R32U is.
name: stringClass · extends BindBaseFormat · category: Graphics
A class to describe the format of the texture for BindGroupFormat.
new BindTextureFormat(name: string, visibility: number, textureDimension?: string, sampleType?: number, hasSampler?: boolean, samplerName?: string | null, multisampled?: boolean)
Create a new instance.
Parameters
name (string): The name of the texture.
visibility (number): A bit-flag that specifies the shader stages in which the texture
is visible. Can be:
textureDimension (string, optional, default TEXTUREDIMENSION_2D): The dimension of the texture. Defaults to
TEXTUREDIMENSION_2D. Can be:
When multisampled is true, must be TEXTUREDIMENSION_2D.
sampleType (number, optional, default SAMPLETYPE_FLOAT): The type of the texture samples. Defaults to
SAMPLETYPE_FLOAT. Can be:
When multisampled is true, SAMPLETYPE_FLOAT is coerced to
SAMPLETYPE_UNFILTERABLE_FLOAT (WebGPU rejects sampleType: "float" on a
multisampled binding).
hasSampler (boolean, optional, default true): True if the sampler for the texture is needed. Note that if the
sampler is used, it will take up an additional slot, directly following the texture slot.
Defaults to true. Forced to false when multisampled is true.
samplerName (string | null, optional, default null): Sampler uniform name. If omitted, generated as
${name}_sampler. Ignored and stored as null when multisampled is true.
multisampled (boolean, optional, default false): True if this is a multisampled texture binding
(texture_multisampled_2d / texture_depth_multisampled_2d). When set, hasSampler is
forced to false and samplerName to null (WGSL only allows textureLoad, and a WebGPU
multisampled texture binding cannot be paired with a sampler). Defaults to false.
hasSampler: boolean
Whether a sampler binding follows this texture. Always false when multisampled is true.
multisampled: boolean
Whether this is a multisampled (texture_multisampled_*) binding.
samplerName: string | null = null
Sampler uniform name. null when multisampled is true; otherwise the provided name or
${name}_sampler.
name: stringClass · extends BindBaseFormat · category: Graphics
A class to describe the format of the uniform buffer for BindGroupFormat.
new BindUniformBufferFormat(name: string, visibility: number)name: stringClass · category: Graphics
BlendState is a descriptor that defines how output of fragment shader is written and blended into render target. A blend state can be set on a material using Material#blendState, or in some cases on the graphics device using GraphicsDevice#setBlendState.
For the best performance, do not modify blend state after it has been created, but create multiple blend states and assign them to the material or graphics device as needed.
By default the blend state applies to all color attachments of the render target. When multiple color attachments are used, individual attachments can be given an independent blend state using BlendState#setAttachment. This requires GraphicsDevice#supportsIndependentBlending - on devices without support, the state of the attachment 0 is used for all attachments.
new BlendState(blend?: boolean, colorOp?: number, colorSrcFactor?: number, colorDstFactor?: number, alphaOp?: number, alphaSrcFactor?: number, alphaDstFactor?: number, redWrite?: boolean, greenWrite?: boolean, blueWrite?: boolean, alphaWrite?: boolean)
Create a new BlendState instance.
All factor parameters can take the following values:
All op parameters can take the following values:
Parameters
blend (boolean, optional, default false): Enables or disables blending. Defaults to false.colorOp (number, optional, default BLENDEQUATION_ADD): Configures color blending operation. Defaults to
BLENDEQUATION_ADD.colorSrcFactor (number, optional, default BLENDMODE_ONE): Configures source color blending factor. Defaults to
BLENDMODE_ONE.colorDstFactor (number, optional, default BLENDMODE_ZERO): Configures destination color blending factor. Defaults to
BLENDMODE_ZERO.alphaOp (number, optional): Configures alpha blending operation. Defaults to
BLENDEQUATION_ADD.alphaSrcFactor (number, optional): Configures source alpha blending factor. Defaults to
BLENDMODE_ONE.alphaDstFactor (number, optional): Configures destination alpha blending factor. Defaults to
BLENDMODE_ZERO.redWrite (boolean, optional, default true): True to enable writing of the red channel and false otherwise.
Defaults to true.greenWrite (boolean, optional, default true): True to enable writing of the green channel and false
otherwise. Defaults to true.blueWrite (boolean, optional, default true): True to enable writing of the blue channel and false otherwise.
Defaults to true.alphaWrite (boolean, optional, default true): True to enable writing of the alpha channel and false
otherwise. Defaults to true.static readonly ADDBLEND: BlendState
A blend state that does simple additive blending.
static readonly ALPHABLEND: BlendState
A blend state that does simple translucency using alpha channel.
static readonly NOBLEND: BlendState
A blend state that has blending disabled and writes to all color channels.
static readonly NOWRITE: BlendState
A blend state that does not write to color channels.
get blend(): boolean
set blend(value: boolean)
Gets whether blending is enabled.
get hasAttachmentOverrides(): boolean
Gets whether any color attachment has been given an independent blend state using BlendState#setAttachment.
clearAttachment(index: number): void
Removes the independent blend state of the specified color attachment, making it follow attachment 0 again.
Parameters
index (number): The index of the color attachment, in 1 to 7 range.clone(): BlendState
Returns an identical copy of the specified blend state.
Returns BlendState: The result of the cloning.
copy(rhs: BlendState): BlendState
Copies the contents of a source blend state to this blend state.
Parameters
rhs (BlendState): A blend state to copy from.Returns BlendState: Self for chaining.
equals(rhs: BlendState): boolean
Reports whether two BlendStates are equal.
Parameters
rhs (BlendState): The blend state to compare to.Returns boolean: True if the blend states are equal and false otherwise.
getAttachment(index: number, dst: BlendState): BlendState
Stores the blend state of the specified color attachment in the supplied blend state. When the attachment does not have an independent blend state, the state of attachment 0 is stored.
Parameters
index (number): The index of the color attachment, in 0 to 7 range.dst (BlendState): The blend state to store the result in. This avoids allocations, as
a single instance can be reused.Returns BlendState: The supplied dst, for chaining.
setAttachment(index: number, src: BlendState | null): void
Assigns an independent blend state to the specified color attachment. The blend state of the supplied source is copied, and so subsequent changes to either the source or to attachment 0 do not affect it. An attachment which has not been assigned an independent state instead follows attachment 0.
Note that this requires GraphicsDevice#supportsIndependentBlending - on devices without support, the state of attachment 0 is used for all attachments.
Parameters
index (number): The index of the color attachment, in 1 to 7 range. Attachment 0 is
configured using the other functions and properties of this class.src (BlendState | null): The blend state to copy from, or null to make the attachment
follow attachment 0 again.Example
// attachment 1 keeps the blending of attachment 0, but does not write any channels
const state = material.blendState.clone();
const noWrite = state.clone();
noWrite.setColorWrite(false, false, false, false);
state.setAttachment(1, noWrite);
Class · extends Geometry · category: Graphics
A procedural box-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new BoxGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new BoxGeometry(opts?: object)
Create a new BoxGeometry instance.
By default, the constructor creates a box centered on the object space origin with a width, length and height of 1 unit and 1 segment in either axis (2 triangles per face). The box is created with UVs in the range of 0 to 1 on each face.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.halfExtents (Vec3, optional): The half dimensions of the box in each axis. Defaults to
[0.5, 0.5, 0.5].opts.heightSegments (number, optional): The number of divisions along the Y axis of the box.
Defaults to 1.opts.lengthSegments (number, optional): The number of divisions along the Z axis of the box.
Defaults to 1.opts.widthSegments (number, optional): The number of divisions along the X axis of the box.
Defaults to 1.opts.yOffset (number, optional): Move the box vertically by given offset in local space. Pass
0.5 to generate the box with pivot point at the bottom face. Defaults to 0.Example
const geometry = new BoxGeometry({
halfExtents: new Vec3(1, 1, 1),
widthSegments: 2,
lengthSegments: 2,
heightSegments: 2
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · extends Component · category: Graphics
The CameraComponent enables an Entity to render the scene. A scene requires at least one enabled camera component to be rendered. The camera's view direction is along the negative z-axis of the owner entity.
Note that multiple camera components can be enabled simultaneously (for split-screen or offscreen rendering, for example).
You should never need to use the CameraComponent constructor directly. To add a CameraComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('camera', {
nearClip: 1,
farClip: 100,
fov: 55
});
Once the CameraComponent is added to the entity, you can access it via the Entity#camera property:
entity.camera.nearClip = 2; // Set the near clip of the camera
console.log(entity.camera.nearClip); // Get the near clip of the camera
For ready-made camera behaviour, attach the CameraControls script from
playcanvas/scripts/esm/camera-controls.mjs, which provides orbit, fly and pan driven by mouse,
touch and gamepad input.
Relevant Engine API examples:
get aperture(): number
set aperture(value: number)
Gets the camera aperture in f-stops.
get aspectRatio(): number
set aspectRatio(value: number)
Gets the aspect ratio (width divided by height) of the camera.
get aspectRatioMode(): number
set aspectRatioMode(value: number)
Gets the aspect ratio mode of the camera.
get calculateProjection(): CalculateMatrixCallback
set calculateProjection(value: CalculateMatrixCallback)
Gets the custom function to calculate the camera projection matrix manually.
get calculateTransform(): CalculateMatrixCallback
set calculateTransform(value: CalculateMatrixCallback)
Gets the custom function to calculate the camera transformation matrix manually.
get clearColor(): Color
set clearColor(value: Color)
Gets the camera component's clear color.
get clearColorBuffer(): boolean
set clearColorBuffer(value: boolean)
Gets whether the camera will automatically clear the color buffer before rendering.
get clearDepth(): number
set clearDepth(value: number)
Gets the depth value to clear the depth buffer to.
get clearDepthBuffer(): boolean
set clearDepthBuffer(value: boolean)
Gets whether the camera will automatically clear the depth buffer before rendering.
get clearStencilBuffer(): boolean
set clearStencilBuffer(value: boolean)
Gets whether the camera will automatically clear the stencil buffer before rendering.
get cullFaces(): boolean
set cullFaces(value: boolean)
Gets whether the camera will cull triangle faces.
get disablePostEffectsLayer(): number
set disablePostEffectsLayer(layer: number)
Gets the layer id of the layer on which the post-processing of the camera stops being applied to.
get farClip(): number
set farClip(value: number)
Gets the distance from the camera after which no rendering will take place.
get flipFaces(): boolean
set flipFaces(value: boolean)
Gets whether the camera will flip the face direction of triangles.
get fog(): FogParams | null
set fog(value: FogParams | null)
Gets a FogParams that defines fog parameters, or null if those are not set.
get fov(): number
set fov(value: number)
Gets the field of view of the camera in degrees.
get frustum(): Frustum
Gets the camera's frustum shape.
get frustumCulling(): boolean
set frustumCulling(value: boolean)
Gets whether frustum culling is enabled.
get gammaCorrection(): number
set gammaCorrection(value: number)
Gets the gamma correction used when rendering the scene.
get horizontalFov(): boolean
set horizontalFov(value: boolean)
Gets whether the camera's field of view (fov) is horizontal or vertical.
get jitter(): number
set jitter(value: number)
Gets the jitter intensity applied in the projection matrix.
get layers(): readonly number[]
set layers(newValue: readonly number[])
Gets the array of layer IDs (Layer#id) to which this camera belongs.
get nearClip(): number
set nearClip(value: number)
Gets the distance from the camera before which no rendering will take place.
get orthoHeight(): number
set orthoHeight(value: number)
Gets the half-height of the orthographic view window (in the Y-axis).
get postEffects(): PostEffectQueue
Gets the post effects queue for this camera. Use this to add or remove post effects from the camera.
get priority(): number
set priority(newValue: number)
Gets the priority to control the render order of this camera.
get projection(): number
set projection(value: number)
Gets the type of projection used to render the camera.
get projectionMatrix(): Mat4
Gets the camera's projection matrix.
get projectionOffset(): Vec2
set projectionOffset(value: Vec2)
Gets the offset of the projection window.
get rect(): Readonly<Vec4>
set rect(value: Readonly<Vec4>)
Gets the rendering rectangle for the camera.
get renderTarget(): RenderTarget
set renderTarget(value: RenderTarget)
Gets the render target to which rendering of the camera is performed.
get scissorRect(): Vec4
set scissorRect(value: Vec4)
Gets the scissor rectangle for the camera.
get sensitivity(): number
set sensitivity(value: number)
Gets the camera sensitivity in ISO.
get shutter(): number
set shutter(value: number)
Gets the camera shutter speed in seconds.
get toneMapping(): number
set toneMapping(value: number)
Gets the tonemapping transform applied to the rendered color buffer.
get viewMatrix(): Mat4
Gets the camera's view matrix.
calculateAspectRatio(rt?: RenderTarget | null): number
Computes the aspect ratio this camera would produce when rendering to the given render
target, without changing the camera's state. When rt is omitted, the camera's own
CameraComponent#renderTarget is used, and if that is also null, the backbuffer
is used. The camera's CameraComponent#rect viewport is taken into account.
Parameters
rt (RenderTarget | null, optional): Optional render target to compute the aspect ratio
against. Defaults to the camera's current render target, or the backbuffer if none is
assigned.Returns number: The computed aspect ratio.
endXr(callback?: XrErrorCallback): void
Attempt to end XR session of this camera.
Parameters
callback (XrErrorCallback, optional): Optional callback function called once session is
ended. The callback has one argument Error - it is null if successfully ended XR session.Example
// On an entity with a camera component
this.entity.camera.endXr((err) => {
// not anymore in XR
});
getClearColor(index: number): Color
Gets the clear color of a color attachment of the camera's render target.
Parameters
index (number): The index of the color attachment.Returns Color: The clear color of the attachment.
getShaderPass(): string | undefined
Shader pass name.
Returns string | undefined: The name of the shader pass, or undefined if no shader pass is set.
requestSceneColorMap(enabled: boolean): void
Request the scene to generate a texture containing the scene color map. Note that this call
is accumulative, and for each enable request, a disable request need to be called. Note that
this setting is ignored when framePasses is used.
Parameters
enabled (boolean): True to request the generation, false to disable it.requestSceneDepthMap(enabled: boolean): void
Request the scene to generate a texture containing the scene depth map. Note that this call
is accumulative, and for each enable request, a disable request need to be called. Note that
this setting is ignored when framePasses is used.
Parameters
enabled (boolean): True to request the generation, false to disable it.screenToWorld(screenx: number, screeny: number, cameraz: number, worldCoord?: Vec3): Vec3
Convert a point from 2D screen space to 3D world space.
Parameters
screenx (number): X coordinate on PlayCanvas' canvas element. Should be in the range
0 to canvas.offsetWidth of the application's canvas element.screeny (number): Y coordinate on PlayCanvas' canvas element. Should be in the range
0 to canvas.offsetHeight of the application's canvas element.cameraz (number): The distance from the camera in world space to create the new
point.worldCoord (Vec3, optional): 3D vector to receive world coordinate result.Returns Vec3: The world space coordinate.
Example
// Get the start and end points of a 3D ray fired from a screen click position
const start = entity.camera.screenToWorld(clickX, clickY, entity.camera.nearClip);
const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip);
// Use the ray coordinates to perform a raycast
const result = app.systems.rigidbody.raycastFirst(start, end);
if (result) {
console.log(`Entity ${result.entity.name} was selected`);
}
setClearColor(index: number, color: Color | null): void
Sets the clear color of a color attachment of the camera's render target, which allows the color buffers of a RenderTarget with multiple color buffers to clear to different colors. The attachment 0 clears to CameraComponent#clearColor, and the other attachments clear to the same color unless given their own here. Pass null to remove the color of an attachment, so that it clears to the attachment 0 color again. The components of the clear color of an integer format attachment are the integer values to clear to.
Parameters
index (number): The index of the color attachment.color (Color | null): The clear color, specified in sRGB space, or null to clear to
the color of the attachment 0.Example
// clear the second color buffer of the render target to a different color
entity.camera.setClearColor(1, new pc.Color(0.5, 0.5, 1, 1));
setShaderPass(name: string): number
Sets the name of the shader pass the camera will use when rendering.
In addition to existing names (see the parameter description), a new name can be specified, which creates a new shader pass with the given name. The name provided can only use alphanumeric characters and underscores. When a shader is compiled for the new pass, a define is added to the shader. For example, if the name is 'custom_rendering', the define 'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally execute code only when that shader pass is active.
Another instance where this approach may prove useful is when a camera needs to render a more cost-effective version of shaders, such as when creating a reflection texture. To accomplish this, a callback on the material that triggers during shader compilation can be used. This callback can modify the shader generation options specifically for this shader pass.
const shaderPassId = camera.setShaderPass('custom_rendering');
material.onUpdateShader = function (options) {
if (options.pass === shaderPassId) {
options.litOptions.normalMapEnabled = false;
options.litOptions.useSpecular = false;
}
return options;
};
Parameters
name (string): The name of the shader pass. Defaults to undefined, which is
equivalent to SHADERPASS_FORWARD. Can be:
The returned index can be used with MeshInstance#shaderPassMask to control which mesh instances are rendered in this pass.
Returns number: The id of the shader pass.
startXr(type: string, spaceType: string, options?: object): void
Attempt to start XR session with this camera.
Parameters
type (string): The type of session. Can be one of the following:
spaceType (string): Reference space type. Can be one of the following:
options (object, optional): Object with options for XR session initialization.
options.anchors (boolean, optional): Optional boolean to attempt to enable XrAnchors.options.callback (XrErrorCallback, optional): Optional callback function called once the
session is started. The callback has one argument Error - it is null if the XR session
started successfully.options.depthSensing (object, optional): Optional object with parameters to attempt to enable
depth sensing.
options.depthSensing.dataFormatPreference (string, optional): Optional data format
preference for depth sensing. Can be 'luminance-alpha' or 'float32' (XRDEPTHSENSINGFORMAT_*),
defaults to 'luminance-alpha'. Most preferred and supported will be chosen by the underlying
depth sensing system.options.depthSensing.usagePreference (string, optional): Optional usage preference for depth
sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to
'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing
system.options.imageTracking (boolean, optional): Set to true to attempt to enable XrImageTracking.options.optionalFeatures (string[], optional): Optional features for XRSession start. It is
used for getting access to additional WebXR spec extensions.options.planeDetection (boolean, optional): Set to true to attempt to enable XrPlaneDetection.Example
// On an entity with a camera component
this.entity.camera.startXr(XRTYPE_VR, XRSPACE_LOCAL, {
callback: (err) => {
if (err) {
// failed to start XR session
} else {
// in XR
}
}
});
worldToScreen(worldCoord: Vec3, screenCoord?: Vec3): Vec3
Convert a point from 3D world space to 2D screen space.
The returned z is the unnormalized clip space depth, not a behind-the-camera flag: it also
goes negative for points in front of a perspective camera that are nearer than twice the
near clip, and for an orthographic camera it is negative across the whole near half of the
depth range. To reject points behind the camera, test the view space depth instead - pass
the world position through CameraComponent#viewMatrix and discard it when the
resulting z is zero or greater.
Parameters
worldCoord (Vec3): The world space coordinate.screenCoord (Vec3, optional): 3D vector to receive screen coordinate result.Returns Vec3: The screen space coordinate.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Used to add and remove CameraComponents from Entities. It also holds an array of all active cameras.
cameras: CameraComponent[] = []
Holds all the active camera components.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
Implementation of a simple to use camera rendering pass, which supports SSAO, Bloom and other rendering effects.
Overriding compose shader chunks:
The final compose pass registers its shader chunks in a way that does not override any chunks
that were already provided. To customize the compose pass output, set your shader chunks on the
ShaderChunks map before creating the CameraFrame. Those chunks will be picked up by
the compose pass and preserved.
Example (GLSL):
Example
// Provide custom compose chunk(s) before constructing CameraFrame
ShaderChunks.get(graphicsDevice, SHADERLANGUAGE_GLSL).set('composeVignettePS', `
#ifdef VIGNETTE
vec3 applyVignette(vec3 color, vec2 uv) {
return color * uv.u;
}
#endif
`);
// For WebGPU, use SHADERLANGUAGE_WGSL instead.
new CameraFrame(app: AppBase, cameraComponent: CameraComponent)
Creates a new CameraFrame instance.
Parameters
app (AppBase): The application.cameraComponent (CameraComponent): The camera component.bloom: Bloom
Bloom settings.
colorEnhance: ColorEnhance
Color enhancement settings.
colorLUT: ColorLUT
Color LUT settings.
debug: "depth" | "scene" | "ssao" | "bloom" | "vignette" | "dofcoc" | "dofblur" | null = null
Debug rendering, which displays an intermediate value of the frame in place of the composed result. This never changes what the frame renders - a mode whose value this frame does not generate simply displays nothing: 'depth' renders black when no effect has produced the scene depth, and the modes of a disabled effect are ignored. Set to null to disable.
dof: Dof
DoF settings.
fringing: Fringing
Fringing settings.
grading: Grading
Grading settings.
rendering: Rendering
Rendering settings.
ssao: Ssao
SSAO settings.
taa: Taa
Taa settings.
vignette: Vignette
Vignette settings.
volumetricFog: VolumetricFog
Volumetric fog settings.
get enabled(): boolean
set enabled(value: boolean)
Gets the enabled state of the camera frame.
createRenderPass(): FramePassCameraFrame
Creates a frame pass for the camera frame. Override this method to utilize a custom frame
pass, typically one that extends FramePassCameraFrame.
Returns FramePassCameraFrame: - The frame pass.
destroy(): void
Destroys the camera frame, removing all render passes.
update(): void
Applies any changes made to the properties of this instance.
static isSplatSceneDepthSupported(device: GraphicsDevice): boolean
Returns whether a device is able to let the gaussian splats contribute to the scene depth, which the volumetric fog and the depth of field need in order to be bounded by the splats instead of drawing through them. Their contribution additionally has to be turned on using GSplatParams#sceneDepthWrite; this reports whether doing so can take effect, so that an application rendering gaussian splats can disable those effects on the devices which cannot respect them.
This tests the device alone, and so can be called before any camera frame is created. Whether a particular one then renders the depth this way also depends on its own settings - multi-sampling and a camera not clearing the whole of its render target both rule it out - and a debug build warns, naming the reason, when the splats end up not contributing.
Parameters
device (GraphicsDevice): The graphics device.Returns boolean: True if the splats can contribute to the scene depth.
Class · extends ConeBaseGeometry · category: Graphics
A procedural capsule-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new CapsuleGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new CapsuleGeometry(opts?: object)
Create a new CapsuleGeometry instance.
By default, the constructor creates a capsule standing vertically centered on the XZ-plane with a radius of 0.3, a height of 1.0, 1 height segment and 20 cap segments. The capsule is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.height (number, optional): The length of the body of the capsule from tip to tip.
Defaults to 1.opts.heightSegments (number, optional): The number of divisions along the tubular length of
the capsule. Defaults to 1.opts.radius (number, optional): The radius of the tube forming the body of the capsule.
Defaults to 0.3.opts.sides (number, optional): The number of divisions around the tubular body of the capsule.
Defaults to 20.Example
const geometry = new CapsuleGeometry({
radius: 1,
height: 2,
heightSegments: 2,
sides: 20
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · extends Geometry · category: Graphics
A procedural circle-shaped geometry - a flat disc in the XZ plane.
Typically, you would:
// Create a mesh instance
const geometry = new CircleGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new CircleGeometry(opts?: object)
Create a new CircleGeometry instance.
By default, the constructor creates a circle centered on the object space origin with a radius of 0.5, 64 sectors and 8 rings. The normal vector of the circle is aligned along the positive Y axis. The circle is created with UVs in the range of 0 to 1, mapped planarly across its bounding square.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.radius (number, optional): The radius of the circle. Defaults to 0.5.opts.ringExponent (number, optional): Controls the radial distribution of the rings. A value
of 1 spaces the rings uniformly, larger values concentrate the rings (and so the
tessellation detail) towards the center of the circle. Defaults to 1.opts.rings (number, optional): The number of concentric rings of vertices between the center
and the outer edge of the circle. Defaults to 8.opts.sectors (number, optional): The number of divisions around the circumference of the
circle. Defaults to 64.Example
const geometry = new CircleGeometry({
radius: 100,
sectors: 128,
rings: 64,
ringExponent: 2
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
A representation of a compute shader with the associated resources, that can be executed on the GPU. Only supported on WebGPU platform.
Call Compute#destroy when no longer needed. The graphics device retains compute instances for device recovery until they are explicitly destroyed.
new Compute(graphicsDevice: GraphicsDevice, shader: Shader, name?: string)
Create a compute instance. Note that this is supported on WebGPU only and is a no-op on other platforms.
Parameters
graphicsDevice (GraphicsDevice): The graphics device.shader (Shader): The compute shader.name (string, optional, default 'Unnamed'): The name of the compute instance, used for debugging only.name: string
The non-unique name of an instance of the class. Defaults to 'Unnamed'.
deleteParameter(name: string): void
Deletes a shader parameter from the compute instance.
Parameters
name (string): The name of the parameter to delete.destroy(): void
Frees resources associated with this compute instance.
getParameter(name: string): number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined
Returns the value of a shader parameter from the compute instance.
Parameters
name (string): The name of the parameter to get.Returns number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined: The value of the specified parameter.
setParameter(name: string, value: number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView): void
Sets a shader parameter on a compute instance.
Parameters
name (string): The name of the parameter to set.value (number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView): The value for the specified parameter.setupDispatch(x: number, y?: number, z?: number): void
Prepare the compute work dispatch.
Parameters
x (number): X dimension of the grid of work-groups to dispatch.y (number, optional): Y dimension of the grid of work-groups to dispatch.z (number, optional): Z dimension of the grid of work-groups to dispatch.setupIndirectDispatch(slotIndex: number, buffer?: StorageBuffer | null): void
Prepare the compute work dispatch to use indirect parameters from a buffer. The dispatch parameters (x, y, z workgroup counts) are read from the buffer at the specified slot index.
When using the device's built-in buffer (buffer parameter is null), this method must be called each frame as slots are only valid for the current frame.
Parameters
slotIndex (number): Slot index in the indirect dispatch buffer. When using the
device's built-in buffer, obtain this by calling GraphicsDevice#getIndirectDispatchSlot.buffer (StorageBuffer | null, optional, default null): Optional custom storage buffer containing dispatch
parameters. If not provided, uses the device's built-in GraphicsDevice#indirectDispatchBuffer.
When providing a custom buffer, the user is responsible for its lifetime and contents.Example
// Reserve a slot in the indirect dispatch buffer
const slot = device.getIndirectDispatchSlot();
// First compute shader writes dispatch parameters to the buffer
prepareCompute.setParameter('indirectBuffer', device.indirectDispatchBuffer);
prepareCompute.setParameter('slot', slot);
prepareCompute.setupDispatch(1, 1, 1);
device.computeDispatch([prepareCompute]);
// Second compute shader uses indirect dispatch
processCompute.setupIndirectDispatch(slot);
device.computeDispatch([processCompute]);
Class · extends Geometry · category: Graphics
Shared superclass of CapsuleGeometry, ConeGeometry and CylinderGeometry. Use those classes instead of this one.
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · extends ConeBaseGeometry · category: Graphics
A procedural cone-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new ConeGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new ConeGeometry(opts?: object)
Create a new ConeGeometry instance.
By default, the constructor creates a cone standing vertically centered on the XZ-plane with a base radius of 0.5, a height of 1.0, 5 height segments and 18 cap segments. The cone is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.baseRadius (number, optional): The base radius of the cone. Defaults to 0.5.opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.capSegments (number, optional): The number of divisions around the tubular body of the
cone. Defaults to 18.opts.height (number, optional): The length of the body of the cone. Defaults to 1.opts.heightSegments (number, optional): The number of divisions along the length of the cone.
Defaults to 5.opts.peakRadius (number, optional): The peak radius of the cone. Defaults to 0.Example
const geometry = new ConeGeometry({
baseRadius: 1,
height: 2,
heightSegments: 2,
capSegments: 20
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
Container for a list of animations, textures, materials, renders, gsplats and a model.
animations: Asset<"animation">[] = []
An array of the animation assets. Each resource is an AnimTrack.
gsplats: Asset<"gsplat">[] = []
An array of the gsplat assets, created for meshes using the KHR_gaussian_splatting glTF extension.
materials: Asset<"material">[] = []
An array of the Material and/or StandardMaterial assets.
renders: Asset<"render">[] = []
An array of the render assets. Each holds the meshes of one glTF mesh.
textures: Asset<"texture">[] = []
An array of the Texture assets.
applyMaterialVariant(entity: Entity, name?: string): void
Applies a material variant to an entity hierarchy.
Parameters
entity (Entity): The entity root to which material variants will be applied.name (string, optional): The name of the variant, as queried from getMaterialVariants, if
null the variant will be reset to the default.Example
// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
const entity = asset.resource.instantiateRenderEntity({
castShadows: true
});
app.root.addChild(entity);
const materialVariants = asset.resource.getMaterialVariants();
asset.resource.applyMaterialVariant(entity, materialVariants[0]);
});
applyMaterialVariantInstances(instances: MeshInstance[], name?: string): void
Applies a material variant to a set of mesh instances. Compared to the applyMaterialVariant, this method allows for setting the variant on a specific set of mesh instances instead of the whole entity.
Parameters
instances (MeshInstance[]): An array of mesh instances.name (string, optional): The name of the variant, as queried by getMaterialVariants. If null,
the variant will be reset to the default.Example
// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
const entity = asset.resource.instantiateRenderEntity({
castShadows: true
});
app.root.addChild(entity);
const materialVariants = asset.resource.getMaterialVariants();
const renders = entity.findComponents("render");
for (let i = 0; i < renders.length; i++) {
const renderComponent = renders[i];
asset.resource.applyMaterialVariantInstances(renderComponent.meshInstances, materialVariants[0]);
}
});
getMaterialVariants(): string[]
Queries the list of available material variants.
Returns string[]: An array of variant names.
instantiateModelEntity(options?: any): Entity
Instantiates an entity with a model component.
Parameters
options (any, optional): The initialization data for the model component type
ModelComponent.Returns Entity: A single entity with a model component. Model component internally
contains a hierarchy based on GraphNode.
Example
// load a glb file and instantiate an entity with a model component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
const entity = asset.resource.instantiateModelEntity({
castShadows: true
});
app.root.addChild(entity);
});
instantiateRenderEntity(options?: any): Entity
Instantiates an entity with a render component.
Parameters
options (any, optional): The initialization data for the render component type
RenderComponent.Returns Entity: A hierarchy of entities with render components on entities containing
renderable geometry.
Example
// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
const entity = asset.resource.instantiateRenderEntity({
castShadows: true
});
app.root.addChild(entity);
// find all render components containing mesh instances, and change blend mode on their materials
const renders = entity.findComponents("render");
renders.forEach((render) => {
render.meshInstances.forEach((meshInstance) => {
meshInstance.material.blendType = BLEND_MULTIPLICATIVE;
meshInstance.material.update();
});
});
});
Class · extends ConeBaseGeometry · category: Graphics
A procedural cylinder-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new CylinderGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new CylinderGeometry(opts?: object)
Create a new CylinderGeometry instance.
By default, the constructor creates a cylinder standing vertically centered on the XZ-plane with a radius of 0.5, a height of 1.0, 1 height segment and 20 cap segments. The cylinder is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.capSegments (number, optional): The number of divisions around the tubular body of the
cylinder. Defaults to 20.opts.height (number, optional): The length of the body of the cylinder. Defaults to 1.opts.heightSegments (number, optional): The number of divisions along the length of the
cylinder. Defaults to 5.opts.radius (number, optional): The radius of the tube forming the body of the cylinder.
Defaults to 0.5.Example
const geometry = new CylinderGeometry({
radius: 1,
height: 2,
heightSegments: 2,
capSegments: 10
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
DepthState is a descriptor that defines how the depth value of the fragment is used by the rendering pipeline. A depth state can be set on a material using Material#depthState, or in some cases on the graphics device using GraphicsDevice#setDepthState.
For the best performance, do not modify depth state after it has been created, but create multiple depth states and assign them to the material or graphics device as needed.
new DepthState(func?: number, write?: boolean)
Create a new Depth State instance.
Parameters
func (number, optional, default FUNC_LESSEQUAL): Controls how the depth of the fragment is compared against the
current depth contained in the depth buffer. See DepthState#func for details.
Defaults to FUNC_LESSEQUAL.write (boolean, optional, default true): If true, depth values are written to the depth buffer of the
currently active render target. Defaults to true.key: number = 0
A unique number representing the depth state. You can use this number to quickly compare two depth states for equality. The key is always maintained valid without a dirty flag, to avoid condition check at runtime, considering these change rarely.
static readonly DEFAULT: DepthState
A default depth state that has the depth testing function set to FUNC_LESSEQUAL and depth writes enabled.
static readonly NODEPTH: DepthState
A depth state that always passes the fragment but does not write depth to the depth buffer.
static readonly WRITEDEPTH: DepthState
A depth state that always passes the fragment and writes depth to the depth buffer.
get depthBias(): number
set depthBias(value: number)
Gets the constant depth bias added to each fragment's depth.
get depthBiasSlope(): number
set depthBiasSlope(value: number)
Gets the depth bias that scales with the fragment's slope.
get func(): number
set func(value: number)
Gets the depth testing function.
get test(): boolean
set test(value: boolean)
Gets whether depth testing is performed.
get write(): boolean
set write(value: boolean)
Gets whether depth writing is performed.
clone(): DepthState
Returns an identical copy of the specified depth state.
Returns DepthState: The result of the cloning.
copy(rhs: DepthState): DepthState
Copies the contents of a source depth state to this depth state.
Parameters
rhs (DepthState): A depth state to copy from.Returns DepthState: Self for chaining.
equals(rhs: DepthState): boolean
Reports whether two DepthStates are equal.
Parameters
rhs (DepthState): The depth state to compare to.Returns boolean: True if the depth states are equal and false otherwise.
Class · extends SphereGeometry · category: Graphics
A procedural dome-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new DomeGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new DomeGeometry(opts?: object)
Create a new DomeGeometry instance.
By default, the constructor creates a dome with a radius of 0.5, 16 latitude bands and 16 longitude bands. The dome is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.latitudeBands (number, optional): The number of divisions along the latitudinal axis of
the sphere. Defaults to 16.opts.longitudeBands (number, optional): The number of divisions along the longitudinal axis of
the sphere. Defaults to 16.Example
const geometry = new DomeGeometry({
latitudeBands: 32,
longitudeBands: 32
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
Container holding parameters for multi-draw commands.
Obtain an instance via MeshInstance#setMultiDraw and populate it using add followed by update.
get count(): number
Number of draw calls to perform.
get maxCount(): number
Maximum number of multi-draw calls the space is allocated for.
add(i: number, indexOrVertexCount: number, instanceCount: number, firstIndexOrVertex: number, baseVertex?: number, firstInstance?: number): void
Writes one draw command into the allocated storage.
Parameters
i (number): Draw index to update.indexOrVertexCount (number): Number of indices or vertices to draw.instanceCount (number): Number of instances to draw (use 1 if not instanced).firstIndexOrVertex (number): Starting index (in indices, not bytes) or starting vertex.baseVertex (number, optional, default 0): Signed base vertex (WebGPU only). Defaults to 0.firstInstance (number, optional, default 0): First instance (WebGPU only). Defaults to 0.update(count: number): void
Finalize and set draw count after all commands have been added.
Parameters
count (number): Number of draws to execute.Class · category: Graphics
Fog parameters.
color: Color
The color of the fog (if enabled), specified in sRGB color space. Defaults to black (0, 0, 0).
density: number = 0
The density of the fog (if enabled). This property is only valid if the fog property is set to FOG_EXP or FOG_EXP2. Defaults to 0.
end: number = 1000
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. Defaults to 1000.
start: number = 1
The distance from the viewpoint where linear fog begins. This property is only valid if the fog property is set to FOG_LINEAR. Defaults to 1.
type: string = FOG_NONE
The type of fog used by the scene. Can be:
Defaults to FOG_NONE.
Class · category: Graphics
The Geometry class serves as a container for storing geometric information. It encapsulates data such as positions, normals, colors, and indices.
blendIndices: ArrayLike<number> | undefined
Blend indices.
blendWeights: ArrayLike<number> | undefined
Blend weights.
colors: ArrayLike<number> | undefined
Colors.
indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined
Indices.
normals: ArrayLike<number> | undefined
Normals.
positions: ArrayLike<number> | undefined
Positions.
tangents: ArrayLike<number> | undefined
Tangents.
uvs: ArrayLike<number> | undefined
UVs.
uvs1: ArrayLike<number> | undefined
Additional Uvs.
calculateNormals(): void
Generates normal information from the positions and triangle indices.
calculateTangents(): void
Generates tangent information from the positions, normals, texture coordinates and triangle indices.
Class · extends EventHandler · category: Graphics
The graphics device manages the underlying graphics context. It is responsible for submitting render state changes and graphics primitives to the hardware. A graphics device is tied to a specific canvas HTML element. It is valid to have more than one canvas element per page and create a new graphics device against each.
backBufferAntialias: boolean = false
True if the back buffer should use anti-aliasing.
readonly canvas: HTMLCanvasElement
The canvas DOM element that provides the underlying WebGL context used by the graphics device.
gpuProfiler: GpuProfiler
The GPU profiler.
insideRenderPass: boolean = false
isHdr: boolean = false
True if the back-buffer is using HDR format, which means that the browser will display the rendered images in high dynamic range mode. This is true if the options.displayFormat is set to DISPLAYFORMAT_HDR when creating the graphics device using createGraphicsDevice, and HDR is supported by the device.
readonly isNull: boolean = false
True if the deviceType is Null
readonly isWebGL2: boolean = false
True if the deviceType is WebGL2
readonly isWebGPU: boolean = false
True if the deviceType is WebGPU
readonly maxAnisotropy: number
The maximum supported texture anisotropy setting.
readonly maxColorAttachments: number = 1
The maximum supported number of color buffers attached to a render target.
readonly maxCubeMapSize: number
The maximum supported dimension of a cube map.
maxIndirectDispatchCount: number = 256
The maximum number of indirect compute dispatches that can be used within a single frame. Used on WebGPU only. Defaults to 256.
maxIndirectDrawCount: number = 1024
The maximum number of indirect draw calls that can be used within a single frame. Used on WebGPU only. This needs to be adjusted based on the maximum number of draw calls that can be used within a single frame. Defaults to 1024.
readonly maxSamples: number = 1
The maximum supported number of hardware anti-aliasing samples.
readonly maxSubgroupSize: number = 0
Maximum subgroup (warp/wavefront) size reported for the device. Zero means either the device does not expose subgroup sizes, or the WebGPU implementation did not report the value.
readonly maxTextureSize: number
The maximum supported dimension of a texture.
readonly maxVolumeSize: number
The maximum supported dimension of a 3D texture (any axis).
readonly minSubgroupSize: number = 0
Minimum subgroup (warp/wavefront) size reported for the device. Zero means either the device does not expose subgroup sizes, or the WebGPU implementation did not report the value.
readonly precision: string
The highest shader precision supported by this graphics device. Can be 'highp', 'mediump' or 'lowp'.
readonly samples: number
The number of hardware anti-aliasing samples used by the frame buffer.
readonly scope: ScopeSpace
The scope namespace for shader attributes and variables.
supportsClipDistances: boolean = false
True if the device supports clip distances (WebGPU only). Clip distances allow you to restrict primitives' clip volume with user-defined half-spaces in the output of vertex stage.
readonly supportsCompute: boolean = false
True if the device supports compute shaders.
readonly supportsDualSourceBlending: boolean = false
True if the device supports dual-source blending, which allows a fragment shader to output a secondary color used by the source 1 blend factors.
readonly supportsHtmlTextures: boolean = false
True if HTML elements (e.g. <div>) can be used as texture sources via the HTML-in-Canvas
API. When supported, an HTML element appended to a canvas with the layoutsubtree attribute
can be passed to Texture#setSource and rendered as a live texture in the 3D scene.
readonly supportsIndependentBlending: boolean = false
True if the device supports independent blending, which allows each color attachment of a render target to use its own blend state and color write mask, specified using BlendState#setAttachment. When false, the state of the attachment 0 is used for all attachments.
readonly supportsIndirectDraw: boolean = false
True if the device supports indirect draw calls, where the draw parameters are sourced from a GPU buffer instead of being supplied by the CPU (WebGPU only). Also see MeshInstance#setIndirect.
readonly supportsLinearIndexing: boolean = false
True if the device supports the WGSL linear_indexing extension, which provides the
global_invocation_index and workgroup_index built-in values in compute shaders. The
requires linear_indexing; directive is then automatically injected for compute shader
modules, and the shader define CAPS_LINEAR_INDEXING is set for conditional
compilation.
supportsMultiDraw: boolean = true
True if the device supports multi-draw. This is always supported on WebGPU, and support on WebGL2 is optional, but pretty common.
readonly supportsPacked4x8IntegerDotProduct: boolean = false
True if the device supports the WGSL packed_4x8_integer_dot_product language feature,
which exposes the DP4a-family built-in functions for 8-bit packed integer dot products:
dot4U8Packed, dot4I8Packed, and the pack4x{I,U}8, pack4x{I,U}8Clamp,
unpack4x{I,U}8 helpers. Useful for accelerating quantized inference and similar
integer-heavy compute workloads. The requires packed_4x8_integer_dot_product;
directive is automatically injected into WGSL shaders when this feature is available,
and the shader define CAPS_PACKED_4X8_INTEGER_DOT_PRODUCT is set for conditional
compilation.
readonly supportsPointerCompositeAccess: boolean = false
True if the device supports the WGSL pointer_composite_access language feature, which
provides syntactic sugar for dereferencing pointers to composite types: p.field and
p[i] may be written instead of (*p).field and (*p)[i]. The
requires pointer_composite_access; directive is automatically injected into WGSL
shaders when this feature is available, and the shader define
CAPS_POINTER_COMPOSITE_ACCESS is set for conditional compilation.
readonly supportsPrimitiveIndex: boolean = false
True if the device supports primitive index in fragment shaders (WebGPU only). When
supported, fragment shaders can access the pcPrimitiveIndex built-in variable which
uniquely identifies the current primitive being processed.
readonly supportsShaderF16: boolean = false
True if the device supports 16-bit floating-point types in shaders (WebGPU only). When
supported, shaders can use native WGSL types: f16, vec2h, vec3h, vec4h, mat2x2h,
mat3x3h, mat4x4h. For convenience, PlayCanvas also provides type aliases (half,
half2, half3, half4, half2x2, half3x3, half4x4) that resolve to f16 types when
supported, or fall back to f32 types when not supported.
readonly supportsStorageTextureRead: boolean = false
True if the device can read from StorageTexture in the compute shader. By default, the
storage texture can be only used with the write operation.
When a shader uses this feature, add a requires directive to signal non-portability at the
top of the WGSL shader code. The shader define CAPS_STORAGE_TEXTURE_READ is set when this
capability is available.
requires readonly_and_readwrite_storage_textures;
readonly supportsSubgroupId: boolean = false
True if the device supports the WGSL subgroup_id extension, which provides access to
subgroup_id and num_subgroups built-in values in workgroups. The requires subgroup_id;
directive is automatically injected into WGSL shaders when this feature is available.
readonly supportsSubgroups: boolean = false
True if the device supports subgroup operations in shaders (WebGPU only). When supported,
compute and fragment shaders can use WGSL subgroup builtins such as subgroupBroadcast,
subgroupAll, subgroupAny, subgroupAdd, subgroupShuffle, etc. The enable subgroups;
directive is automatically injected into WGSL shaders when this feature is available.
readonly supportsSubgroupSizeControl: boolean = false
True if the device supports subgroup size control (WebGPU only). This depends on
supportsSubgroups and, when available, allows a compute shader to pin its execution
to a specific subgroup size (a power of two within the minSubgroupSize to
maxSubgroupSize range) via the WGSL @subgroup_size attribute. The
subgroup-size-control device feature is automatically requested when this is supported, and
the shader define CAPS_SUBGROUP_SIZE_CONTROL is set for conditional compilation.
readonly supportsSubgroupUniformity: boolean = false
True if the device supports the WGSL subgroup_uniformity extension, which allows
subgroup functionality to be considered uniform in more cases during shader compilation.
This is automatically enabled via the enable subgroups; directive when
supportsSubgroups is true.
readonly supportsTextureAndSamplerLet: boolean = false
True if the device supports the WGSL texture_and_sampler_let language feature, which
allows assigning texture and sampler variables to let bindings within a WGSL shader
(preparation for bindless-style indirection patterns). The
requires texture_and_sampler_let; directive is automatically injected into WGSL
shaders when this feature is available, and the shader define
CAPS_TEXTURE_AND_SAMPLER_LET is set for conditional compilation.
readonly supportsTextureFormatsTier1: boolean = false
True if the device supports the WebGPU 'texture-formats-tier1' feature (WebGPU only). When available, 16-bit unorm and snorm texture formats become usable, the 8-bit snorm formats become renderable, blendable and multisample-capable, and a wider set of 8-bit and 16-bit formats can be bound as storage textures. Implied by supportsTextureFormatsTier2.
readonly supportsTextureFormatsTier2: boolean = false
True if the device supports the WebGPU 'texture-formats-tier2' feature (WebGPU only). This extends tier 1 and enables read-write storage access for additional texture formats.
readonly supportsTransientAttachments: boolean = false
True if the device supports transient ("memoryless") render target attachments (WebGPU only).
When supported, attachments that are only used within a single render pass (cleared on load
and discarded on store) can be allocated as memoryless, allowing tile-based GPUs to keep their
contents in on-chip memory and avoid VRAM allocation. See the transientColor /
transientDepth options of RenderTarget and createGraphicsDevice.
readonly supportsUnrestrictedPointerParameters: boolean = false
True if the device supports the WGSL unrestricted_pointer_parameters language feature,
which allows passing pointers in the storage, uniform, and workgroup address spaces
as function arguments. The requires unrestricted_pointer_parameters; directive is
automatically injected into WGSL shaders when this feature is available, and the shader
define CAPS_UNRESTRICTED_POINTER_PARAMETERS is set for conditional compilation.
readonly textureFloatBlendable: boolean = false
True if blending can be used when rendering to 32-bit floating-point render targets. Note that 16-bit floating-point render targets are always blendable when they are renderable.
readonly textureFloatFilterable: boolean = false
True if filtering can be applied when sampling float textures.
readonly textureFloatRenderable: boolean
True if 32-bit floating-point textures can be used as a frame buffer.
readonly textureHalfFloatRenderable: boolean
True if 16-bit floating-point textures can be used as a frame buffer.
readonly textureRG11B10Renderable: boolean = false
True if small-float textures with format PIXELFORMAT_111110F can be used as a frame buffer. This is always true on WebGL2, but optional on WebGPU device.
get deviceType(): "webgl2" | "webgpu"
Gets the type of the device. Can be:
get fullscreen(): boolean
set fullscreen(fullscreen: boolean)
Gets whether the device is currently in fullscreen mode.
get height(): number
Height of the back buffer in pixels.
get indirectDispatchBuffer(): StorageBuffer | null
Returns the buffer used to store arguments for indirect compute dispatch calls. The size of the buffer is controlled by the maxIndirectDispatchCount property. This buffer can be passed to a Compute shader along with a slot obtained by calling getIndirectDispatchSlot, in order to prepare indirect dispatch parameters.
Only available on WebGPU, returns null on other platforms.
get indirectDrawBuffer(): StorageBuffer | null
Returns the buffer used to store arguments for indirect draw calls. The size of the buffer is controlled by the maxIndirectDrawCount property. This buffer can be passed to a Compute shader along with a slot obtained by calling getIndirectDrawSlot, in order to prepare indirect draw parameters. Also see MeshInstance#setIndirect.
Only available on WebGPU, returns null on other platforms.
get maxPixelRatio(): number
set maxPixelRatio(ratio: number)
Gets the maximum pixel ratio.
get width(): number
Width of the back buffer in pixels.
computeDispatch(computes: Compute[], name?: string): void
Dispatch multiple compute shaders inside a single compute shader pass.
Parameters
computes (Compute[]): An array of compute shaders to dispatch.name (string, optional, default 'Unnamed'): The name of the dispatch, used for debugging and reporting only.destroy(): void
Destroy the graphics device.
getIndirectDispatchSlot(count?: number): number
Retrieves the first available slot in the indirectDispatchBuffer used for indirect compute dispatch, which can be utilized by a Compute shader to generate indirect dispatch parameters for another compute shader.
When reserving multiple consecutive slots, specify the optional count parameter.
Parameters
count (number, optional, default 1): Number of consecutive slots to reserve. Defaults to 1.Returns number: - The first reserved slot index used for indirect dispatch.
getIndirectDrawSlot(count?: number): number
Retrieves the first available slot in the indirectDrawBuffer used for indirect rendering, which can be utilized by a Compute shader to generate indirect draw parameters and by MeshInstance#setIndirect to configure indirect draw calls.
When reserving multiple consecutive slots, specify the optional count parameter.
Only available on WebGPU, see GraphicsDevice#supportsIndirectDraw. Returns 0 on other platforms.
Parameters
count (number, optional, default 1): Number of consecutive slots to reserve. Defaults to 1.Returns number: - The first reserved slot index used for indirect rendering.
getRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefined
Get a renderable HDR pixel format supported by the graphics device.
Note:
filterable parameter is set to false, this function returns one of the supported
formats on the majority of devices apart from some very old iOS and Android devices (99%).filterable parameter is set to true, the function returns a format on a
considerably lower number of devices (70%).Parameters
formats (number[], optional): An array of pixel formats to check for support. Can contain:
Any other format in the array is skipped, allowing a non-HDR format to be included in the list and handled by the caller's own fallback.
filterable (boolean, optional, default true): If true, the format also needs to be filterable, allowing it
to be sampled with linear filtering. Defaults to true.
samples (number, optional, default 1): The number of samples to check for. Some formats are not
compatible with multi-sampling, for example PIXELFORMAT_RGBA32F on WebGPU platform.
Defaults to 1.
blendable (boolean, optional, default false): If true, the format also needs to be blendable, allowing it to
be used as a blended render target attachment. This is an independent capability to
filtering, and only the 32bit float formats can fail to support it. Defaults to false.
Returns number | undefined: The first supported renderable HDR format or undefined if none is
supported.
getRenderTarget(): RenderTarget
Queries the currently set render target on the device.
Returns RenderTarget: The current render target.
Example
// Get the current render target
const renderTarget = device.getRenderTarget();
postInit(): void
Function that executes after the device has been created.
setBlendColor(r: number, g: number, b: number, a: number): void
Sets the constant blend color and alpha values used with BLENDMODE_CONSTANT and BLENDMODE_ONE_MINUS_CONSTANT factors specified in BlendState. Defaults to [0, 0, 0, 0].
Parameters
r (number): The value for red.g (number): The value for green.b (number): The value for blue.a (number): The value for alpha.setBlendState(blendState: BlendState): void
Sets the specified blend state.
Parameters
blendState (BlendState): New blend state.setCullMode(cullMode: number): void
Controls how triangles are culled based on their face direction. The default cull mode is CULLFACE_BACK.
Parameters
cullMode (number): The cull mode to set. Can be:
setDepthState(depthState: DepthState): void
Sets the specified depth state.
Parameters
depthState (DepthState): New depth state.setDrawStates(blendState?: BlendState, depthState?: DepthState, cullMode?: number, frontFace?: number, stencilFront?: StencilParameters, stencilBack?: StencilParameters): void
Sets all draw-related render states in a single call. All parameters have sensible defaults
for utility rendering (full-screen quads, particles, etc.), so calling setDrawStates() with
no arguments resets to a safe baseline.
Parameters
blendState (BlendState, optional, default BlendState.NOBLEND): Blend state. Defaults to BlendState.NOBLEND.depthState (DepthState, optional, default DepthState.NODEPTH): Depth state. Defaults to DepthState.NODEPTH.cullMode (number, optional, default CULLFACE_NONE): Cull mode. Defaults to CULLFACE_NONE.frontFace (number, optional, default FRONTFACE_CCW): Front face winding. Defaults to FRONTFACE_CCW.stencilFront (StencilParameters, optional): Front stencil parameters.stencilBack (StencilParameters, optional): Back stencil parameters.setFrontFace(frontFace: number): void
Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is FRONTFACE_CCW.
Parameters
frontFace (number): The front face to set. Can be:
setRenderTarget(renderTarget: RenderTarget | null): void
Sets the specified render target on the device. If null is passed as a parameter, the back buffer becomes the current target for all rendering operations.
Parameters
renderTarget (RenderTarget | null): The render target to activate.Example
// Set a render target to receive all rendering output
device.setRenderTarget(renderTarget);
// Set the back buffer to receive all rendering output
device.setRenderTarget(null);
setStencilState(stencilFront?: StencilParameters, stencilBack?: StencilParameters): void
Sets the specified stencil state. If both stencilFront and stencilBack are null, stencil operation is disabled.
Parameters
stencilFront (StencilParameters, optional): The front stencil parameters. Defaults to
StencilParameters.DEFAULT if not specified.stencilBack (StencilParameters, optional): The back stencil parameters. Defaults to
StencilParameters.DEFAULT if not specified.protected validateAttributes(shader: Shader, vertexBuffers: (VertexBuffer | null | undefined)[]): void
Validate that all attributes required by the shader are present in the currently assigned vertex buffers.
Parameters
shader (Shader): The shader to validate.vertexBuffers ((VertexBuffer | null | undefined)[]): The vertex buffers of the draw.fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: Graphics
The GSplatComponent enables an Entity to render 3D Gaussian Splats. Splats are always
loaded from Assets rather than being created programmatically. The asset type is
gsplat which supports multiple file formats including .ply, .sog, .meta.json (SOG
format), and .lod-meta.json (streaming LOD format).
You should never need to use the GSplatComponent constructor directly. To add a GSplatComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('gsplat', {
asset: asset
});
Once the GSplatComponent is added to the entity, you can access it via the Entity#gsplat property:
entity.gsplat.customAabb = new BoundingBox(new Vec3(), new Vec3(10, 10, 10));
console.log(entity.gsplat.customAabb);
Relevant Engine API examples:
get asset(): number | Asset<string>
set asset(value: number | Asset<string>)
Gets the gsplat asset id for this gsplat component.
get castShadows(): boolean
set castShadows(value: boolean)
Gets whether gsplat will cast shadows for lights that have shadow casting enabled.
get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)
Gets the custom object space bounding box for visibility culling of the attached gsplat. Returns the custom AABB if set, otherwise falls back to the resource's AABB.
get id(): number
Gets the unique identifier for this component. This ID is used by the picking system
and is also written to the work buffer when app.scene.gsplat.enableIds is enabled, making
it available to custom shaders for effects like highlighting or animation.
get layers(): number[]
set layers(value: number[])
Gets the array of layer IDs (Layer#id) to which this gsplat belongs.
get lodBaseDistance(): number
set lodBaseDistance(value: number)
Gets the base distance for the first LOD transition.
get lodMultiplier(): number
set lodMultiplier(value: number)
Gets the geometric multiplier between successive LOD distance thresholds.
get lodRangeMax(): number
set lodRangeMax(value: number)
Gets the maximum allowed LOD index.
get lodRangeMin(): number
set lodRangeMin(value: number)
Gets the minimum allowed LOD index.
get resource(): GSplatResourceBase | null
set resource(value: GSplatResourceBase | null)
Gets the GSplat resource. Returns the directly set resource if available, otherwise returns the resource from the assigned asset.
get workBufferUpdate(): number
set workBufferUpdate(value: number)
Gets the work buffer update mode.
deleteParameter(name: string): void
Deletes a shader parameter previously set with setParameter.
Parameters
name (string): The name of the parameter to delete.getInstanceTexture(name: string): Texture | null
Gets an instance texture by name. Instance textures are per-component textures defined
in the resource's format with storage: GSPLAT_STREAM_INSTANCE.
Parameters
name (string): The name of the texture.Returns Texture | null: The texture, or null if not found.
Example
// Add an instance stream to the resource format
resource.format.addExtraStreams([
{ name: 'instanceTint', format: PIXELFORMAT_RGBA8, storage: GSPLAT_STREAM_INSTANCE }
]);
// Get the instance texture and fill it with data
const texture = entity.gsplat.getInstanceTexture('instanceTint');
if (texture) {
const data = texture.lock();
// Fill texture data...
texture.unlock();
}
getParameter(name: string): number | number[] | ArrayBufferView<ArrayBufferLike> | undefined
Gets a shader parameter value previously set with setParameter.
Parameters
name (string): The name of the parameter.Returns number | number[] | ArrayBufferView<ArrayBufferLike> | undefined: The parameter value, or undefined if not set.
hide(): void
Stop rendering this component without removing its mesh instance from the scene hierarchy.
setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void
Sets a shader parameter for this gsplat instance. Parameters set here are applied during rendering.
Parameters
name (string): The name of the parameter (uniform name in shader).data (number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): The value for the parameter.setWorkBufferModifier(value: { glsl?: string; wgsl?: string } | null): void
Sets custom shader code for modifying splats when written to the work buffer.
Must provide all three functions:
modifySplatCenter: Modify the splat center positionmodifySplatRotationScale: Modify the splat rotation and scalemodifySplatColor: Modify the splat colorCalling this method automatically triggers a work buffer re-render.
Parameters
value ({ glsl?: string; wgsl?: string } | null): The modifier code for GLSL and/or WGSL.Example
entity.gsplat.setWorkBufferModifier({
glsl: `
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) { color.rgb *= vec3(1.0, 0.0, 0.0); }
`,
wgsl: `
fn modifySplatCenter(center: ptr<function, vec3f>) {}
fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) {}
fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) { (*color).r = 1.0; (*color).g = 0.0; (*color).b = 0.0; }
`
});
show(): void
Enable rendering of the component if hidden using hide.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Manages the GSplatComponents of an application. Reach it through app.systems.gsplat;
components are created with Entity#addComponent, never by calling the system directly.
getMaterial(camera: Camera, layer: Layer): ShaderMaterial | null
Gets the GSplat material for the given camera and layer.
Returns null if the material hasn't been created yet. Materials are created during the first frame update when the GSplat is rendered. To be notified immediately when materials are created, listen to the 'material:created' event on GSplatComponentSystem:
Parameters
camera (Camera): The camera instance.layer (Layer): The layer instance.Returns ShaderMaterial | null: The material, or null if not created yet.
Example
app.systems.gsplat.on('material:created', (material, camera, layer) => {
// Material is now available
material.setParameter('myParam', value);
});
static EVENT_FRAMEREADY: string = 'frame:ready'
Fired every frame for each camera and layer combination rendering GSplats. The handler is passed the CameraComponent, the Layer, a boolean indicating if the current frame has up-to-date sorting, and a number indicating how many resources are loading.
The ready parameter indicates whether the current frame reflects all recent changes (camera
movement, splat transforms, lod updates, etc.) with the latest sorting applied. The loadingCount
parameter reports the total number of octree LOD resources currently loading or queued to load.
This event is useful for video capture or other workflows that need to wait for frames
to be fully ready. Only capture frames and move camera to next position when both
ready === true and loadingCount === 0. Note that loadingCount can be used as a boolean
in conditionals (0 is falsy, non-zero is truthy) for backward compatibility.
Example
// Wait for frame to be ready before capturing
app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => {
if (ready && !loadingCount) {
console.log(`Frame ready to capture for camera ${camera.entity.name}`);
// Capture frame here
}
});
Example
// Track loading progress (0..1)
let maxLoadingCount = 0;
app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => {
maxLoadingCount = Math.max(maxLoadingCount, loadingCount);
const progress = maxLoadingCount > 0 ? (maxLoadingCount - loadingCount) / maxLoadingCount : 1;
console.log(`Loading progress: ${(progress * 100).toFixed(1)}%`);
});
static EVENT_FRAMEREQUEST: string = 'frame:request'
Fired once per frame, after the component/script updates and before rendering, when GSplat streaming has produced new data that a render would show (newly streamed octree LOD) or a CPU sort result is ready to be applied. This drives on-demand rendering for apps that run with AppBase#autoRender set to false: a typical handler sets AppBase#renderNextFrame so the new data is shown.
Streaming (LOD evaluation, file loading) runs every frame regardless of autoRender, so the
scene keeps loading in the background; this event tells you when it's worth rendering.
Note: this event covers streaming changes only. Changes you make yourself — moving the camera, modifying the scene, or adding, removing, or changing properties of gsplat components — should trigger a render yourself.
Example
app.autoRender = false;
app.systems.gsplat.on('frame:request', () => {
app.renderNextFrame = true;
});
static EVENT_MATERIALCREATED: string = 'material:created'
Fired when a GSplat material is created for a camera and layer combination. Materials are created during the first frame update when the GSplat is rendered. The handler is passed the ShaderMaterial, the CameraComponent, and the Layer.
This event is useful for setting up custom material chunks and parameters before the first render.
Example
app.systems.gsplat.on('material:created', (material, camera, layer) => {
console.log(`Material created for camera ${camera.entity.name} on layer ${layer.name}`);
// Set custom material parameters before first render
material.setParameter('myParam', value);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
A container for procedural Gaussian Splat data. This class allows you to create splat data programmatically using either a built-in format or a custom format with your own texture streams and read code.
A default format is provided via GSplatFormat.createDefaultFormat which uses float textures for easy CPU population.
Example
// Example 1: Using the default format (easy CPU population)
const format = GSplatFormat.createDefaultFormat(device);
const container = new GSplatContainer(device, 100, format);
// Float format textures are straightforward to fill
const centerTex = container.getTexture('dataCenter');
const pixels = centerTex.lock();
// pixels is Float32Array, fill with [x, y, z, 0, x, y, z, 0, ...]
centerTex.unlock();
// Set bounding box
container.aabb = new BoundingBox();
// fill centers only if you need CPU sorting
container.centers.set([x0, y0, z0, x1, y1, z1, ...]); // xyz per splat
// Add to scene
entity.addComponent('gsplat', { resource: container });
Example
// Example 2: Using a custom format
const format = new GSplatFormat(device, [
{ name: 'data', format: PIXELFORMAT_RGBA32F }
], {
// Shader code to read splat attributes from the texture
readGLSL: `
vec4 d = loadData();
splatCenter = d.xyz;
splatColor = vec4(1.0);
splatScale = vec3(d.w);
splatRotation = vec4(0, 0, 0, 1);
`,
readWGSL: `
let d = loadData();
splatCenter = d.xyz;
splatColor = vec4f(1.0);
splatScale = vec3f(d.w);
splatRotation = vec4f(0, 0, 0, 1);
`
});
const container = new GSplatContainer(device, 100, format);
new GSplatContainer(device: GraphicsDevice, maxSplats: number, format: GSplatFormat)
Creates a new GSplatContainer instance.
Parameters
device (GraphicsDevice): The graphics device.maxSplats (number): Maximum number of splats this container can hold.format (GSplatFormat): The format descriptor with streams and read code. Use
GSplatFormat.createDefaultFormat for the built-in format, or create a custom
GSplatFormat.get centers(): Float32Array<ArrayBufferLike>
set centers(value: Float32Array<ArrayBufferLike>)
CPU-side splat center positions (xyz per splat), or null when not built for this resource.
get maxSplats(): number
Maximum number of splats this container can hold.
get numSplats(): number
Gets the number of splats to render.
update(numSplats?: number, centersUpdated?: boolean): void
Updates the container after modifying texture data and centers. Call this after filling data to signal that the container contents have changed.
Parameters
numSplats (number, optional): Number of splats to render. Defaults to current value.
Must be between 0 and maxSplats.centersUpdated (boolean, optional, default true): Whether the centers array was modified. Set to
false when only numSplats changes but center positions remain the same, to avoid the cost
of re-cloning centers in the sorter (can be significant for large containers).protected _centers: Float32Array<ArrayBufferLike> | nullaabb: BoundingBoxget format(): GSplatFormatget hasCenters(): booleanget textureDimensions(): Vec2protected _actualDestroy(): voiddestroy(): voidgetTexture(name: string): Texture | nullClass · category: Graphics
Gsplat resources store per-splat data (positions, colors, rotations, scales, spherical harmonics) in GPU textures. This class describes those texture streams and generates the shader code needed to access them.
Each stream defines a texture with a name and pixel format. The class automatically generates
shader declarations (uniforms/samplers) and load functions (e.g. loadColor()) for each
stream. A read shader can be provided to define how splat attributes are extracted from
these textures.
Users can add extra streams via addExtraStreams for custom per-splat data. These can be per-resource (shared across instances) or per-instance (unique to each gsplat component).
For loaded gsplat resources, base streams are automatically configured based on the loaded data format. For GSplatContainer, users define both base and extra streams to specify the complete data layout.
new GSplatFormat(device: GraphicsDevice, streams: GSplatStreamDescriptor[], options: object)
Creates a new GSplatFormat instance.
Parameters
device (GraphicsDevice): The graphics device.streams (GSplatStreamDescriptor[]): Array of stream descriptors.options (object): Format options.
options.readGLSL (string, optional): GLSL code defining getCenter(), getColor(),
getRotation(), getScale() functions. Can include additional declarations at module scope.
Required for WebGL.options.readWGSL (string, optional): WGSL code defining getCenter(), getColor(),
getRotation(), getScale() functions. Can include additional declarations at module scope.
Required for WebGPU.readonly streams: GSplatStreamDescriptor[]
Array of stream descriptors.
get extraStreams(): GSplatStreamDescriptor[]
Gets the extra streams array. Streams can only be added via addExtraStreams, not removed. Do not modify the returned array directly.
addExtraStreams(streams: GSplatStreamDescriptor[]): void
Adds additional texture streams for custom gsplat data. Each stream defines a texture
that can store extra information, accessible in shaders via generated load functions.
Streams with storage: GSPLAT_STREAM_INSTANCE are created per gsplat component instance,
while others are shared across all instances of the same resource.
Note: Streams cannot be removed once added currently.
Parameters
streams (GSplatStreamDescriptor[]): Array of stream descriptors to add.static createDefaultFormat(device: GraphicsDevice): GSplatFormat
Creates a default format using 32F/16F textures, simple to use for CPU data population. This format can be rendered to by GSplatProcessor when supported. Check GraphicsDevice#textureFloatRenderable (for RGBA32F) and GraphicsDevice#textureHalfFloatRenderable (for RGBA16F).
The format stores:
dataColor (RGBA16F): color.rgba as half floatsdataCenter (RGBA32F): center.xyz as floats (w unused)dataScale (RGBA16F): scale.xyz as half floats (w unused)dataRotation (RGBA16F): rotation.xyzw as half floats (w stored directly, not derived)Parameters
device (GraphicsDevice): The graphics device.Returns GSplatFormat: The default format.
static createSimpleFormat(device: GraphicsDevice): GSplatFormat
Creates a simple format with uniform-scale splats and no rotation. Streams:
dataCenter (RGBA32F): center.xyz + uniform size in wdataColor (RGBA16F): color.rgba as half floatsParameters
device (GraphicsDevice): The graphics device.Returns GSplatFormat: The simple format.
Class · category: Graphics
Parameters for the GSplat system.
new GSplatParams(device: GraphicsDevice)
Creates a new GSplatParams instance.
Parameters
device (GraphicsDevice): The graphics device.colorRampIntensity: number = 1
Intensity multiplier for overdraw visualization mode. Value of 1 uses alpha of 1/32, allowing approximately 32 overdraws to reach full brightness with additive blending. Higher values increase brightness per splat. Defaults to 1.
colorUpdateAngle: number = 10
Viewing angle threshold in degrees for triggering spherical harmonics color updates. When the camera translates enough to change the viewing angle to an octree node or splat by this amount, its SH colors are re-evaluated. Distant nodes naturally update less frequently since they require more camera movement to reach the angle threshold. An orthographic camera views all splats along its forward direction, so their colors are re-evaluated together once the camera rotates by this amount, and moving it has no effect. Set to 0 to update every frame where camera moves. Defaults to 10.
cooldownTicks: number = 100
Number of update ticks before unloading unused streamed resources. When a streamed resource's reference count reaches zero, it enters a cooldown period before being unloaded. This allows recently used data to remain in memory for quick reuse if needed again soon. Set to 0 to unload immediately when unused. Defaults to 100.
dither: string = DITHER_BLUENOISE
The noise pattern the coverage of a GSplatParams#stochastic splat is dithered
against, ignored when stochastic is false. Can be:
Defaults to DITHER_BLUENOISE, which looks best under temporal anti-aliasing.
DITHER_NONE is not a coverage pattern, so it is not accepted here - turn
stochastic off instead.
lodUpdateAngle: number = 90
Angle threshold in degrees to trigger LOD updates based on camera rotation. Set to 0 to disable rotation-based updates. Rotation only affects LOD through lodBehindPenalty, so rotation-based updates also stop when the penalty is 1. Defaults to 90.
lodUpdateDistance: number = 1
Distance threshold in world units to trigger LOD updates for camera and gsplat instances. Defaults to 1.
radialSorting: boolean = false
Enables radial sorting based on distance from camera (for cubemap rendering). When false, uses directional sorting along camera forward vector. Defaults to false.
Note: Radial sorting helps reduce sorting artifacts when the camera rotates (looks around), while linear sorting is better at minimizing artifacts when the camera translates (moves).
sceneDepthWrite: boolean = false
Whether the gaussian splats contribute to the scene depth, which the volumetric fog and the depth of field need in order to be bounded by the splats instead of drawing through them.
This costs an extra full screen render target, and so defaults to false. Enable it for a scene where the splats need to take part in those effects. Requires the camera to render using CameraFrame - see CameraFrame.isSplatSceneDepthSupported.
On some devices enabling this stores the scene depth at a lower precision, which the other effects using it share. The depth stays accurate over camera clip distances of roughly 0.000015 to 16384 there; past the far end of that a distant depth loses accuracy, and the pixels nothing covers stop reading as far away as they are. Keep the far clip inside that range on those devices, or leave the effects which read the depth off.
stochastic: boolean = false
Enables stochastic alpha rendering on the WebGPU GPU-sort renderer. Splats are drawn without sorting, using dithered coverage, opaque blending and depth writes. Ignored by the CPU-sort renderer. Picking continues to use sorted rendering. Defaults to false. Applications can customize the sampling through the material's opacityDitherPS chunk.
useFog: boolean = true
Whether to apply scene fog to Gaussian splats. When false, splats ignore fog settings even if the scene or camera has fog configured. Defaults to true.
useTonemap: boolean = true
Whether to apply the camera's tonemapping and the scene exposure to Gaussian splats. When false, splats render with their stored colors, unaffected by Scene#exposure and the camera's CameraComponent#toneMapping. Fog, when enabled, still applies. Defaults to true.
get alphaClip(): number
set alphaClip(value: number)
Gets the alpha threshold for shadow, pick, and prepass rendering.
get alphaClipForward(): number
set alphaClipForward(value: number)
Gets the forward-pass alpha threshold.
get antiAlias(): boolean
set antiAlias(value: boolean)
Gets whether anti-aliasing compensation is enabled.
get colorizeColorUpdate(): boolean
set colorizeColorUpdate(value: boolean)
Deprecated: Use debug with GSPLAT_DEBUG_SH_UPDATE instead.
get colorRamp(): Texture | null
set colorRamp(value: Texture | null)
Gets the color ramp texture for overdraw visualization.
get currentRenderer(): number
The current rendering pipeline in effect after platform-based fallback resolution. When renderer is set to a mode requiring WebGPU on a WebGL device, this returns the fallback mode actually being used.
get dataFormat(): string
set dataFormat(value: string)
Gets the work buffer data format.
get debug(): number
set debug(value: number)
Gets the debug rendering mode for Gaussian splats.
get enableIds(): boolean
set enableIds(value: boolean)
Gets the ID storage enabled state.
get fisheye(): number
set fisheye(value: number)
Gets the fisheye projection strength.
get format(): GSplatFormat
Format descriptor for work buffer streams. Describes the textures used by the work buffer for intermediate storage during rendering. Users can add extra streams via GSplatFormat#addExtraStreams for custom per-splat data.
Example
// Add a custom stream to store per-splat component IDs
app.scene.gsplat.format.addExtraStreams([{
name: 'splatId',
format: PIXELFORMAT_R32U
}]);
get foveationCenter(): number
set foveationCenter(value: number)
Gets the protected centre radius for foveated contribution culling.
get foveationStrength(): number
set foveationStrength(value: number)
Gets the foveated contribution culling strength.
get lodBehindPenalty(): number
set lodBehindPenalty(value: number)
Gets behind-camera LOD penalty multiplier.
get lodUnderfillLimit(): number
set lodUnderfillLimit(value: number)
Gets the maximum allowed underfill LOD range.
get material(): ShaderMaterial
A material template that can be customized by the user. Any defines, parameters, or shader chunks set on this material will be automatically applied to all GSplat components. After making changes, call Material#update to for the changes to be applied on the next frame.
Example
// Set a custom parameter on all GSplat materials
app.scene.gsplat.material.setParameter('myCustomParam', 1.0);
app.scene.gsplat.material.update();
get minContribution(): number
set minContribution(value: number)
Gets the minimum contribution threshold.
get minPixelSize(): number
set minPixelSize(value: number)
Gets the minimum pixel size threshold.
get renderer(): number
set renderer(value: number)
Gets the requested rendering pipeline for gaussian splatting. This may differ from currentRenderer when a WebGPU mode falls back on a WebGL device.
get splatBudget(): number
set splatBudget(value: number)
Gets the number of splats across all GSplats in the scene.
get splatBudgetMode(): string
set splatBudgetMode(value: string)
Gets how the splat budget is used.
get twoDimensional(): boolean
set twoDimensional(value: boolean)
Gets whether 2D Gaussian Splatting mode is enabled.
get varyings(): GSplatVaryings
Custom varying streams for the gsplat render customization: per-splat values written by
the gsplatModifyVS shader chunk and read per fragment by the gsplatModifyPS shader
chunk. See GSplatVaryings.
Example
// Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value),
// and read per fragment in gsplatModifyPS using getFlag()
app.scene.gsplat.varyings.add([{
name: 'flag',
type: TYPE_UINT32,
components: 1
}]);
Class · category: Graphics
GSplatProcessor enables GPU-based processing of Gaussian Splat data using custom shader code. Gaussian Splats store per-splat attributes (position, rotation, scale, color, spherical harmonics) in texture streams. This processor reads from source streams and writes results to destination streams, enabling operations like painting, selection marking, or custom data transforms.
Custom streams can be added to loaded gsplat resources via GSplatFormat#addExtraStreams, or you can create fully procedural splat data using GSplatContainer.
The source and destination can reference the same resource or component, as long as the read and write streams don't overlap (you cannot read and write the same stream in one pass).
By default (when source streams are not specified), the processor provides access to the format's built-in getCenter(), getRotation(), getScale(), and getColor() functions for reading splat data. Note: getCenter() must be called first as it loads shared data used by the other functions.
Custom uniforms can be passed to the shader via setParameter, including scalar values, vectors, and additional textures for effects like brush patterns or lookup tables.
The following built-in uniforms are available in processing shaders:
srcNumSplats (uint) - Number of splats in source resourcedstNumSplats (uint) - Number of splats in destination resourceExample
// Create a processor that reads splat positions and writes to a customColor texture
const processor = new GSplatProcessor(
app.graphicsDevice,
{ component: entity.gsplat }, // source: all streams auto-bound
{ component: entity.gsplat, streams: ['customColor'] }, // destination: customColor stream only
{
processGLSL: `
uniform vec4 uPaintSphere;
uniform vec4 uPaintColor;
void process() {
vec3 center = getCenter();
float dist = distance(center, uPaintSphere.xyz);
if (dist < uPaintSphere.w) {
writeCustomColor(uPaintColor);
} else {
writeCustomColor(vec4(0.0));
}
}
`,
processWGSL: `
uniform uPaintSphere: vec4f;
uniform uPaintColor: vec4f;
fn process() {
let center = getCenter();
let dist = distance(center, uniform.uPaintSphere.xyz);
if (dist < uniform.uPaintSphere.w) {
writeCustomColor(uniform.uPaintColor);
} else {
writeCustomColor(vec4f(0.0));
}
}
`
}
);
// Set uniforms and execute
processor.setParameter('uPaintSphere', [0, 1, 0, 0.5]);
processor.setParameter('uPaintColor', [1, 0, 0, 1]);
processor.process();
new GSplatProcessor(device: GraphicsDevice, source: GSplatProcessorBinding, destination: GSplatProcessorBinding, options: object)
Creates a new GSplatProcessor instance.
Parameters
device (GraphicsDevice): The graphics device.source (GSplatProcessorBinding): Source configuration specifying where to read from.
Can specify resource directly or component (for instance textures).destination (GSplatProcessorBinding): Destination configuration specifying where to write.
Can specify resource directly or component (for instance textures).options (object): Shader options for the processing logic.
options.processGLSL (string, optional): GLSL code at module scope. Must define a void process()
function that implements the processing logic. Can include uniform declarations and helper functions.options.processWGSL (string, optional): WGSL code at module scope. Must define a fn process()
function that implements the processing logic. Can include uniform declarations and helper functions.blendState: BlendState = BlendState.NOBLEND
The blend state to use when processing. Allows accumulation of results (e.g., additive blending for painting). Defaults to no blending.
deleteParameter(name: string): void
Removes a shader parameter.
Parameters
name (string): The name of the parameter to remove.destroy(): void
Destroys this processor and releases all resources.
getParameter(name: string): number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer | undefined
Gets a shader parameter value previously set with setParameter.
Parameters
name (string): The name of the parameter.Returns number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer | undefined: The parameter value, or undefined if not set.
process(): void
Executes the processing, reading from source streams and writing to destination streams.
setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void
Sets a shader parameter for this processor. Parameters are applied during processing.
Parameters
name (string): The name of the parameter (uniform name in shader).data (number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): The value for the parameter.Class · category: Graphics
Manages custom varying streams for the gsplat render customization. Streams added here generate
set functions available to the gsplatModifyVS shader chunk, where they run once per splat,
and matching get functions available to the gsplatModifyPS shader chunk, where the per-splat
value can be read for each rendered fragment.
Access the instance via GSplatParams#varyings.
get streams(): GSplatVaryingDescriptor[]
Gets the varying stream descriptors. Do not modify the returned array.
add(streams: GSplatVaryingDescriptor[]): void
Adds varying streams. For each stream, a set function (set<Name>) is generated and made
available to the gsplatModifyVS shader chunk, where it runs once per splat, and a
matching get function (get<Name>) is made available to the gsplatModifyPS shader
chunk, where the per-splat value can be read for each rendered fragment.
Supported types are TYPE_FLOAT32, TYPE_INT32 and TYPE_UINT32, with 1 to 4 components. Adding or removing streams rebuilds the gsplat shaders.
Note: on some platforms each component is stored in per-splat video memory, so its size scales with the number of rendered splats. Keep the data as compact as possible - prefer fewer components, and consider bit-packing multiple small values into a single uint component instead of using separate streams.
Parameters
streams (GSplatVaryingDescriptor[]): The streams to add.Example
// Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value),
// and read per fragment in gsplatModifyPS using getFlag()
app.scene.gsplat.varyings.add([{
name: 'flag',
type: TYPE_UINT32,
components: 1
}]);
remove(names: string[]): void
Removes varying streams previously added by GSplatVaryings#add.
Parameters
names (string[]): The names of the streams to remove.Class · extends TextureParser · category: Graphics
Parser for browser-supported image formats.
load(url: any, callback: any, asset: any): void
Load the texture from the remote URL. When loaded (or failed), use the callback to return an the raw resource data (or error).
Parameters
url (any): The URL of the resource to load.callback (any): The callback used when the resource is loaded or
an error occurs.asset (any): Optional asset that is passed by ResourceLoader.open(url: any, data: any, device: any, textureOptions?: {}): Texture
Convert raw resource data into a Texture.
Parameters
url (any): The URL of the resource to open.data (any): The raw resource data passed by callback from ResourceHandler#load.device (any): The graphics device.textureOptions ({}, optional, default {})Returns Texture: The parsed resource data.
Class · category: Graphics
An index buffer stores index values into a VertexBuffer. Indexed graphical primitives can normally utilize less memory that unindexed primitives (if vertices are shared).
Typically, index buffers are set on Mesh objects.
new IndexBuffer(graphicsDevice: GraphicsDevice, format: number, numIndices: number, usage?: number, initialData?: ArrayBuffer | ArrayBufferView<ArrayBufferLike>, options?: object)
Create a new IndexBuffer instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this index buffer.
format (number): The type of each index to be stored in the index buffer. Can be:
numIndices (number): The number of indices to be stored in the index buffer.
usage (number, optional, default BUFFER_STATIC): The usage type of the vertex buffer. Can be:
Defaults to BUFFER_STATIC.
initialData (ArrayBuffer | ArrayBufferView<ArrayBufferLike>, optional): Initial data. Can be an
ArrayBuffer or a typed array (for example a Uint16Array). The data is stored
by reference and is not copied, so a typed array that is a view into a larger buffer is kept
as-is. If left unspecified, the index buffer will be initialized to zeros.
options (object, optional): Object for passing optional arguments.
options.storage (boolean, optional): Defines if the index buffer can be used as a storage
buffer by a compute shader. Defaults to false. Only supported on WebGPU.Example
// Create an index buffer holding 3 16-bit indices. The buffer is marked as
// static, hinting that the buffer will never be modified.
const indices = new Uint16Array([0, 1, 2]);
const indexBuffer = new IndexBuffer(graphicsDevice,
INDEXFORMAT_UINT16,
3,
BUFFER_STATIC,
indices);
destroy(): void
Frees resources associated with this index buffer.
getFormat(): number
Returns the data format of the specified index buffer.
Returns number: The data format of the specified index buffer. Can be:
getNumIndices(): number
Returns the number of indices stored in the specified index buffer.
Returns number: The number of indices stored in the specified index buffer.
lock(): ArrayBuffer | ArrayBufferView<ArrayBufferLike>
Gives access to the block of memory that stores the buffer's indices.
Returns ArrayBuffer | ArrayBufferView<ArrayBufferLike>: The memory that stores the buffer's indices. This
matches whatever was supplied as the initial data: an ArrayBuffer when none was
provided, otherwise the ArrayBuffer or typed array that was passed in. Use
ArrayBufferConstructor.isView to distinguish the two before accessing it.
unlock(byteOffset?: number, byteLength?: number): void
Uploads the client side copy of the index buffer to the GPU. When called without arguments, uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. The first upload always initializes the entire GPU buffer, regardless of the requested range. A zero byte length does nothing, including before the first upload.
Partial uploads do not resize the buffer or change its CPU storage. The caller must upload every modified range before expecting those changes on the GPU. Context restoration uploads the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion in debug builds.
Parameters
byteOffset (number, optional): Offset in bytes from the start of the buffer's storage.
Defaults to 0. Must be a non-negative integer and a multiple of 4 on all graphics backends.byteLength (number, optional): Number of bytes to upload. Defaults to the remaining bytes
after byteOffset. The length must be a non-negative integer and the range must fit within
the buffer. Partial ranges require a length that is a multiple of 4. Full-buffer uploads
support any byte length, whether the range is explicit or the arguments are omitted.Example
// After modifying bytes 16 through 31 of the CPU storage:
indexBuffer.unlock(16, 16);
Class · category: Graphics
A Layer represents a renderable subset of the scene. It can contain a list of mesh instances, lights and cameras, their render settings and also defines custom callbacks before, after or during rendering. Layers are organized inside LayerComposition in a desired order.
A mesh instance is drawn through the layers it belongs to, and a camera draws only the layers listed in CameraComponent#layers. Components place their mesh instances by layer id, for example through RenderComponent#layers, and lights through LightComponent#layers; mesh instances you create yourself go in with addMeshInstances and out with removeMeshInstances.
The application creates five layers, reachable by id from Scene#layers: LAYERID_WORLD for the scene itself, LAYERID_DEPTH, LAYERID_SKYBOX, LAYERID_IMMEDIATE for debug drawing and LAYERID_UI. Within a layer, opaque and transparent mesh instances are drawn as two separate parts, ordered by opaqueSortMode and transparentSortMode, and the composition decides where each part falls in the frame. Set enabled to false to skip a layer entirely, and use onEnable and onDisable to react to that.
Example
// Draw a set of mesh instances in a layer of their own, right after the world's opaque objects
const layers = app.scene.layers;
const layer = new Layer({ name: 'Overlay' });
const world = layers.getLayerById(LAYERID_WORLD);
layers.insert(layer, layers.getOpaqueIndex(world) + 1);
layer.addMeshInstances(meshInstances);
new Layer(options?: any)
Create a new Layer instance.
Parameters
options (any, optional, default {}): Object for passing optional arguments. These arguments are the
same as properties of the Layer.id: number
A unique ID of the layer. Layer IDs are stored inside ModelComponent#layers, RenderComponent#layers, CameraComponent#layers, LightComponent#layers and ElementComponent#layers instead of names. Can be used in LayerComposition#getLayerById.
name: string
Name of the layer. Can be used in LayerComposition#getLayerByName.
onDisable: Function
Custom function that is called after the layer has been disabled. This happens when:
decrementCounter was called and set the counter to zero.onEnable: Function
Custom function that is called after the layer has been enabled. This happens when:
opaqueSortMode: number = SORTMODE_MATERIALMESH
Defines the method used for sorting opaque (that is, not semi-transparent) mesh instances before rendering. Can be:
Defaults to SORTMODE_MATERIALMESH.
transparentSortMode: number = SORTMODE_BACK2FRONT
Defines the method used for sorting semi-transparent mesh instances before rendering. Can be:
Defaults to SORTMODE_BACK2FRONT.
get clearColorBuffer(): boolean
set clearColorBuffer(val: boolean)
Gets whether the camera will clear the color buffer when it renders this layer.
get clearDepthBuffer(): boolean
set clearDepthBuffer(val: boolean)
Gets whether the camera will clear the depth buffer when it renders this layer.
get clearStencilBuffer(): boolean
set clearStencilBuffer(val: boolean)
Gets whether the camera will clear the stencil buffer when it renders this layer.
get enabled(): boolean
set enabled(val: boolean)
Gets the enabled state of the layer.
addCamera(camera: CameraComponent): void
Adds a camera to this layer.
Parameters
camera (CameraComponent): A CameraComponent.addLight(light: LightComponent): void
Adds a light to this layer.
Parameters
light (LightComponent): A LightComponent.addMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void
Adds an array of mesh instances to this layer.
Parameters
meshInstances (MeshInstance[]): Array of MeshInstance.skipShadowCasters (boolean, optional): Set it to true if you don't want these mesh instances
to cast shadows in this layer. Defaults to false.addShadowCasters(meshInstances: MeshInstance[]): void
Adds an array of mesh instances to this layer, but only as shadow casters (they will not be rendered anywhere, but only cast shadows on other objects).
Parameters
meshInstances (MeshInstance[]): Array of MeshInstance.clearCameras(): void
Removes all cameras from this layer.
clearLights(): void
Removes all lights from this layer.
clearMeshInstances(skipShadowCasters?: boolean): void
Removes all mesh instances from this layer.
Parameters
skipShadowCasters (boolean, optional, default false): Set it to true if you want to continue the existing mesh
instances to cast shadows. Defaults to false, which removes shadow casters as well.removeCamera(camera: CameraComponent): void
Removes a camera from this layer.
Parameters
camera (CameraComponent): A CameraComponent.removeLight(light: LightComponent): void
Removes a light from this layer.
Parameters
light (LightComponent): A LightComponent.removeMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void
Removes multiple mesh instances from this layer.
Parameters
meshInstances (MeshInstance[]): Array of MeshInstance. If they were added to
this layer, they will be removed.skipShadowCasters (boolean, optional): Set it to true if you want to still cast shadows from
removed mesh instances or if they never did cast shadows before. Defaults to false.removeShadowCasters(meshInstances: MeshInstance[]): void
Removes multiple mesh instances from the shadow casters list of this layer, meaning they will stop casting shadows.
Parameters
meshInstances (MeshInstance[]): Array of MeshInstance. If they were added to
this layer, they will be removed.Class · extends EventHandler · category: Graphics
Layer Composition is a collection of Layer that is fed to Scene#layers to define rendering order.
Each layer is rendered as two parts, its opaque mesh instances and its transparent ones, and
layerList holds the sequence of parts in the order they are drawn. push and
insert add both parts of a layer together, while pushOpaque,
pushTransparent, insertOpaque and insertTransparent place one part at a
time, which is how the default composition places the depth and skybox layers between the world's
opaque and transparent parts. Look layers up with getLayerById and
getLayerByName, find where a part sits with getOpaqueIndex and
getTransparentIndex, and take a layer out with remove. The composition fires
add and remove as layers come and go.
The composition the application creates ends with the UI layer, so a pushed layer renders after the UI and outside the range a camera's post-processing applies to. To render inside that range, insert at an index taken from getOpaqueIndex or getTransparentIndex.
Example
// Draw decals right after the world's opaque objects and before its transparent ones
const layers = app.scene.layers;
const world = layers.getLayerById(LAYERID_WORLD);
const decals = new Layer({ name: 'Decals' });
layers.insertOpaque(decals, layers.getOpaqueIndex(world) + 1);
new LayerComposition(name?: string)
Create a new layer composition.
Parameters
name (string, optional, default 'Untitled'): Optional non-unique name of the layer composition. Defaults to
"Untitled" if not specified.layerList: Layer[] = []
A read-only array of Layer sorted in the order they will be rendered.
subLayerEnabled: boolean[] = []
A read-only array of boolean values, matching layerList. True means the layer is rendered, false means it's skipped.
getLayerById(id: number): Layer | null
Finds a layer inside this composition by its ID. Null is returned, if nothing is found.
Parameters
id (number): An ID of the layer to find.Returns Layer | null: The layer corresponding to the specified ID. Returns null if layer is
not found.
getLayerByName(name: string): Layer | null
Finds a layer inside this composition by its name. Null is returned, if nothing is found.
Parameters
name (string): The name of the layer to find.Returns Layer | null: The layer corresponding to the specified name. Returns null if layer
is not found.
getOpaqueIndex(layer: Layer): number
Gets index of the opaque part of the supplied layer in the layerList.
Parameters
Returns number: The index of the opaque part of the specified layer, or -1 if it is not
part of the composition.
getTransparentIndex(layer: Layer): number
Gets index of the semi-transparent part of the supplied layer in the layerList.
Parameters
Returns number: The index of the semi-transparent part of the specified layer, or -1 if it
is not part of the composition.
insert(layer: Layer, index: number): void
Inserts a layer (both opaque and semi-transparent parts) at the chosen index in the layerList.
Parameters
insertOpaque(layer: Layer, index: number): void
Inserts an opaque part of the layer (non semi-transparent mesh instances) at the chosen index in the layerList.
Parameters
insertTransparent(layer: Layer, index: number): void
Inserts a semi-transparent part of the layer at the chosen index in the layerList.
Parameters
push(layer: Layer): void
Adds a layer (both opaque and semi-transparent parts) to the end of the layerList.
The default composition ends with the UI layer, so a layer pushed here renders after the UI and after the last layer a camera's post-processing applies to. To place a layer inside the post-processed range instead, use LayerComposition#insert with an index from LayerComposition#getOpaqueIndex.
Parameters
pushOpaque(layer: Layer): void
Adds part of the layer with opaque (non semi-transparent) objects to the end of the layerList.
Parameters
pushTransparent(layer: Layer): void
Adds part of the layer with semi-transparent objects to the end of the layerList.
Parameters
remove(layer: Layer): void
Removes a layer (both opaque and semi-transparent parts) from layerList.
Parameters
removeOpaque(layer: Layer): void
Removes an opaque part of the layer (non semi-transparent mesh instances) from layerList.
Parameters
removeTransparent(layer: Layer): void
Removes a transparent part of the layer from layerList.
Parameters
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: Graphics
The LightComponent enables an Entity to light the scene. There are three types of light:
directional: A global light that emits light in the direction of the negative y-axis of the
owner entity. Emulates light sources that appear to be infinitely far away such as the sun. The
owner entity's position is effectively ignored.omni: A local light that emits light in all directions from the owner entity's position.
Emulates candles, lamps, bulbs, etc.spot: A local light that emits light similarly to an omni light but is bounded by a cone
centered on the owner entity's negative y-axis. Emulates flashlights, spotlights, etc.Directional and spot lights are therefore aimed with the owner entity's rotation, and shine along its negative y-axis - so an unrotated light shines straight down. Note that GraphNode#lookAt orients an entity's negative z-axis, which aims a camera but not a light:
// an unrotated light shines straight down
light.setEulerAngles(0, 0, 0);
// tilted 45 degrees, it shines down and towards negative z
light.setEulerAngles(45, 0, 0);
// to aim it at a target, lookAt orients the negative z-axis and the extra rotation brings the
// negative y-axis onto it
light.lookAt(target.getPosition());
light.rotateLocal(90, 0, 0);
// to aim it along a world space direction, rotate the negative y-axis onto that direction.
// Unlike lookAt, this is well defined even when the direction is straight up or down
const dir = new Vec3(-0.5, -1, -0.3).normalize();
light.setRotation(new Quat().setFromDirections(Vec3.DOWN, dir));
// the direction a light currently shines in is the negative of its world space up vector
const currentDir = light.up.clone().mulScalar(-1);
You should never need to use the LightComponent constructor directly. To add a LightComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('light', {
type: 'omni',
color: new Color(1, 0, 0),
intensity: 2
});
Once the LightComponent is added to the entity, you can access it via the Entity#light property:
entity.light.intensity = 3; // Set the intensity of the light
console.log(entity.light.intensity); // Get the intensity of the light
Relevant Engine API examples:
get affectDynamic(): boolean
set affectDynamic(value: boolean)
Gets whether the light will affect non-lightmapped objects.
get affectLightmapped(): boolean
set affectLightmapped(value: boolean)
Gets whether the light will affect lightmapped objects.
get affectSpecularity(): boolean
set affectSpecularity(value: boolean)
Gets whether material specularity will be affected by this light.
get bake(): boolean
set bake(value: boolean)
Gets whether the light will be rendered into lightmaps.
get bakeArea(): number
set bakeArea(value: number)
Gets the angular size in degrees of the area used when baking soft shadow boundaries for the directional light into the lightmap.
get bakeDir(): boolean
set bakeDir(value: boolean)
Gets whether the light's direction will contribute to directional lightmaps.
get bakeNumSamples(): number
set bakeNumSamples(value: number)
Gets the number of samples used to bake this light into the lightmap.
get cascadeBlend(): number
set cascadeBlend(value: number)
Gets the blend factor for cascaded shadow maps.
get cascadeDistribution(): number
set cascadeDistribution(value: number)
Gets the distribution of subdivision of the camera frustum for individual shadow cascades.
get castShadows(): boolean
set castShadows(value: boolean)
Gets whether the light will cast shadows.
get color(): Readonly<Color>
set color(value: Readonly<Color>)
Gets the color of the light. Use the setter to update the color.
get cookie(): Texture | null
set cookie(value: Texture | null)
Gets the texture to be used as the cookie for this light.
get cookieAngle(): number
set cookieAngle(value: number)
Gets the angle for spotlight cookie rotation (in degrees).
get cookieAsset(): number | null
set cookieAsset(value: number | null)
Gets the id of the texture asset used as the cookie for this light, or null if none is set.
get cookieChannel(): string
set cookieChannel(value: string)
Gets the color channels of the cookie texture to use.
get cookieFalloff(): boolean
set cookieFalloff(value: boolean)
Gets whether normal spotlight falloff is active when a cookie texture is set.
get cookieIntensity(): number
set cookieIntensity(value: number)
Gets the cookie texture intensity.
get cookieOffset(): Vec2 | null
set cookieOffset(value: Vec2 | null)
Gets the spotlight cookie position offset.
get cookieScale(): Vec2 | null
set cookieScale(value: Vec2 | null)
Gets the spotlight cookie scale.
get falloffMode(): number
set falloffMode(value: number)
Gets the fall off mode for the light.
get innerConeAngle(): number
set innerConeAngle(value: number)
Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) at which the spotlight cone starts to fade off.
get intensity(): number
set intensity(value: number)
Gets the brightness of the light.
get isStatic(): boolean
set isStatic(value: boolean)
Gets whether the light ever moves.
get layers(): readonly number[]
set layers(value: readonly number[])
Gets the array of layer IDs (Layer#id) to which this light should belong.
get luminance(): number
set luminance(value: number)
Gets the physically-based luminance.
get mask(): number
set mask(value: number)
Gets the mask to determine which MeshInstances are lit by this light.
get normalOffsetBias(): number
set normalOffsetBias(value: number)
Gets the normal offset depth bias.
get numCascades(): number
set numCascades(value: number)
Gets the number of shadow cascades.
get outerConeAngle(): number
set outerConeAngle(value: number)
Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) at which the spotlight cone has faded to nothing.
get penumbraFalloff(): number
set penumbraFalloff(value: number)
Gets the falloff rate for shadow penumbra for contact hardening shadows.
get penumbraSize(): number
set penumbraSize(value: number)
Gets the size of penumbra for contact hardening shadows.
get range(): number
set range(value: number)
Gets the range of the light.
get shadowBias(): number
set shadowBias(value: number)
Get the depth bias for tuning the appearance of the shadow mapping generated by this light.
get shadowBlockerSamples(): number
set shadowBlockerSamples(value: number)
Gets the number of blocker samples used for contact hardening shadows.
get shadowDistance(): number
set shadowDistance(value: number)
Gets the distance from the viewpoint beyond which shadows are no longer rendered.
get shadowIntensity(): number
set shadowIntensity(value: number)
Gets the intensity of the shadow darkening.
get shadowResolution(): number
set shadowResolution(value: number)
Gets the size of the texture used for the shadow map.
get shadowSamples(): number
set shadowSamples(value: number)
Gets the number of shadow samples used for soft shadows.
get shadowType(): number
set shadowType(value: number)
Gets the type of shadows being rendered by this light.
get shadowUpdateMode(): number
set shadowUpdateMode(value: number)
Gets the shadow update mode.
get shadowUpdateOverrides(): number[] | null
set shadowUpdateOverrides(values: number[] | null)
Gets an array of SHADOWUPDATE_ settings per shadow cascade.
get shape(): number
set shape(value: number)
Gets the light source shape.
get type(): string
set type(value: string)
Gets the type of the light.
get volumetricScattering(): number
set volumetricScattering(value: number)
Gets the multiplier of the light's contribution to the volumetric fog.
get vsmBias(): number
set vsmBias(value: number)
Gets the VSM bias value.
get vsmBlurMode(): number
set vsmBlurMode(value: number)
Gets the blurring mode for variance shadow maps.
get vsmBlurSize(): number
set vsmBlurSize(value: number)
Gets the number of samples used for blurring a variance shadow map.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Manages the LightComponents of an application. Reach it through app.systems.light;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
Lighting parameters, allow configuration of the global lighting parameters. For details see Clustered Lighting.
atlasSplit: number[] | null = null
Atlas textures split description, which applies to both the shadow and cookie texture atlas. Defaults to null, which enables to automatic split mode. For details see Configuring Atlas Split.
debugLayer: number
Layer ID of a layer to contain the debug rendering of clustered lighting. Defaults to undefined, which disables the debug rendering. Debug rendering is only included in the debug version of the engine.
get areaLightsEnabled(): boolean
set areaLightsEnabled(value: boolean)
Gets whether clustered lighting supports area lights.
get cells(): Vec3
set cells(value: Vec3)
Gets the number of cells along each world space axis the space containing lights is subdivided into.
get cookieAtlasResolution(): number
set cookieAtlasResolution(value: number)
Gets the resolution of the atlas texture storing all non-directional cookie textures.
get cookiesEnabled(): boolean
set cookiesEnabled(value: boolean)
Gets whether clustered lighting supports cookie textures.
get maxLights(): number
set maxLights(value: number)
Gets the maximum number of lights the clustered lighting can use in a single frame.
get maxLightsPerCell(): number
set maxLightsPerCell(value: number)
Gets the maximum number of lights a cell can store.
get shadowAtlasResolution(): number
set shadowAtlasResolution(value: number)
Gets the resolution of the atlas texture storing all non-directional shadow textures.
get shadowsEnabled(): boolean
set shadowsEnabled(value: boolean)
Gets whether clustered lighting supports shadow casting.
get shadowType(): number
set shadowType(value: number)
Gets the type of shadow filtering used by all shadows.
Class · category: Graphics
The lightmapper is used to bake scene lights into textures.
bake(nodes: Entity[] | null, mode?: number): void
Generates and applies the lightmaps.
Parameters
nodes (Entity[] | null): An array of entities (with model or render components) to
render lightmaps for. If not supplied, the entire scene will be baked.
mode (number, optional, default BAKE_COLORDIR): Baking mode. Can be:
Only lights with bakeDir=true will be used for generating the dominant light direction. Defaults to BAKE_COLORDIR.
Class · category: Graphics
The lit shader options determines how the lit-shader gets generated. It specifies a set of parameters which triggers different fragment and vertex shader generation in the backend.
You do not create one. The engine fills a LitShaderOptions from the material and scene state
each time a StandardMaterial needs a shader variant, and every distinct set of values
produces a distinct compiled shader. Developers rarely need to touch it: the material properties
such as useFog, useLighting and useSkybox on StandardMaterial cover the usual
cases, and the values here mirror them together with the scene state. It is exposed for the
rare case of customizing shader generation through StandardMaterial#onUpdateShader.
alphaTest: boolean = false
Enable alpha testing. See Material#alphaTest.
alphaToCoverage: boolean = false
Enable alpha to coverage. See Material#alphaToCoverage.
ambientSH: boolean = false
If ambient spherical harmonics are used. Ambient SH replace prefiltered cubemap ambient on certain platforms (mostly Android) for performance reasons.
ambientSource: string = 'constant'
One of "ambientSH", "envAtlas", "constant".
blendType: number = BLEND_NONE
The value of Material#blendType.
cubeMapProjection: number = 0
The value of StandardMaterial#cubeMapProjection.
fog: string = FOG_NONE
The type of fog being applied in the shader. See Scene#fog for the list of possible values.
fresnelModel: number = 0
The value of StandardMaterial#fresnelModel.
gamma: number = GAMMA_NONE
The type of gamma correction being applied in the shader. See CameraComponent#gammaCorrection for the list of possible values.
linearDepth: boolean = false
Make vLinearDepth available in the shader.
occludeDirect: boolean = false
The value of StandardMaterial#occludeDirect.
occludeSpecular: number = 0
The value of StandardMaterial#occludeSpecular.
occludeSpecularFloat: boolean = false
Defines if StandardMaterial#occludeSpecularIntensity constant should affect specular occlusion.
opacityDither: string = DITHER_NONE
Enable opacity dithering. See StandardMaterial#opacityDither.
opacityFadesSpecular: boolean = false
Enable specular fade. See StandardMaterial#opacityFadesSpecular.
opacityShadowDither: string = DITHER_NONE
Enable opacity shadow dithering. See StandardMaterial#opacityShadowDither.
reflectionSource: string = REFLECTIONSRC_NONE
One of REFLECTIONSRC_*** constants.
shaderChunks: ShaderChunks | null = null
Custom shader chunks that will replace default ones.
shadowCatcher: boolean = false
Shader outputs the accumulated shadow value, used for shadow catcher materials.
skyboxIntensity: number = 1.0
Skybox intensity factor.
ssao: boolean = false
Apply SSAO during the lighting.
toneMap: number = -1
The type of tone mapping being applied in the shader. See CameraComponent#toneMapping for the list of possible values.
twoSidedLighting: boolean = false
The value of StandardMaterial#twoSidedLighting.
useCubeMapRotation: boolean = false
If cube map rotation is enabled.
useInstancing: boolean = false
If hardware instancing compatible shader should be generated. Transform is read from per-instance VertexBuffer instead of shader's uniforms.
useMetalness: boolean = false
The value of StandardMaterial#useMetalness.
useMorphNormal: boolean = false
If morphing code should be generated to morph normals.
useMorphPosition: boolean = false
If morphing code should be generated to morph positions.
userAttributes: {} = {}
Object containing a map of user defined vertex attributes to attached shader semantics.
useRefraction: boolean = false
If refraction is used.
useSceneEnv: boolean = false
If the environment chunks sample the scene environment, published by the renderer as
scene_envAtlas and scene_skybox, instead of the textures owned by the material
(texture_envAtlas, texture_cubeMap).
useSpecular: boolean = false
If any specular or reflections are needed at all.
Class · category: Graphics
A material determines how a particular MeshInstance is rendered, and specifies render state including uniforms, textures, defines, and other properties.
This is a base class and cannot be instantiated and used directly. Only subclasses such as ShaderMaterial and StandardMaterial can be used to define materials for rendering.
Choose StandardMaterial for a physically based surface described by properties and textures, and ShaderMaterial to supply your own vertex and fragment shaders. Both share the state defined here: blending through blendType, depth behavior through depthTest, depthWrite and depthFunc, face culling through cull, alpha testing through alphaTest, shader uniforms through setParameter, and preprocessor defines through setDefine. getShaderChunks exposes the GLSL and WGSL chunks the material's shader is built from, so one chunk can be replaced without writing a whole shader.
After changing properties, call update so the change reaches the GPU. Most changes only refresh uniforms; a change that alters how the shader is generated also clears the material's compiled shader variants, which are rebuilt on demand. A material can be shared by any number of mesh instances, and clone makes an independent copy.
Example
// Make a material additive and double-sided, then apply the change
material.blendType = BLEND_ADDITIVE;
material.cull = CULLFACE_NONE;
material.update();
protected new Material()
alphaToCoverage: boolean = false
Enables or disables alpha to coverage. When enabled, and if hardware anti-aliasing is on, limited order-independent transparency can be achieved. Quality depends on the number of MSAA samples of the current render target. It can nicely soften edges of otherwise sharp alpha cutouts, but isn't recommended for large area semi-transparent surfaces. Note, that you don't need to enable blending to make alpha to coverage work. It will work without it, just like alphaTest.
This requires a multi-sampled render target, and is silently ignored when rendering to a single-sampled one. On WebGPU it additionally requires the first color attachment of the render target to use a blendable format with an alpha channel, and is silently ignored otherwise - note that PIXELFORMAT_111110F, the default HDR format used by CameraFrame, has no alpha channel.
cull: number = CULLFACE_BACK
Controls how triangles are culled based on their face direction with respect to the viewpoint. Can be:
Defaults to CULLFACE_BACK.
frontFace: number = FRONTFACE_CCW
Controls whether polygons are front- or back-facing by setting a winding orientation. Can be:
Defaults to FRONTFACE_CCW.
name: string = 'Untitled'
The name of the material.
stencilBack: StencilParameters | null = null
Stencil parameters for back faces (default is null).
stencilFront: StencilParameters | null = null
Stencil parameters for front faces (default is null).
userId: string = ''
A unique id the user can assign to the material. The engine internally does not use this for anything, and the user can assign a value to this id for any purpose they like. Defaults to an empty string.
get alphaTest(): number
set alphaTest(value: number)
Gets the alpha test reference value.
get alphaWrite(): boolean
set alphaWrite(value: boolean)
Gets whether the alpha channel is written to the color buffer.
get blendState(): Readonly<BlendState>
set blendState(value: Readonly<BlendState>)
Gets the blend state for this material. Use the setter to update transparency and sort state.
get blendType(): number
set blendType(type: number)
Gets the blend mode for this material.
get blueWrite(): boolean
set blueWrite(value: boolean)
Gets whether the blue channel is written to the color buffer.
get depthBias(): number
set depthBias(value: number)
Gets the offset for the output depth buffer value.
get depthFunc(): number
set depthFunc(value: number)
Gets the depth test function.
get depthState(): DepthState
set depthState(value: DepthState)
Gets the depth state.
get depthTest(): boolean
set depthTest(value: boolean)
Gets whether depth testing is enabled.
get depthWrite(): boolean
set depthWrite(value: boolean)
Gets whether depth writing is enabled.
get flatShading(): boolean
set flatShading(value: boolean)
Gets whether flat shading is enabled.
get greenWrite(): boolean
set greenWrite(value: boolean)
Gets whether the green channel is written to the color buffer.
get redWrite(): boolean
set redWrite(value: boolean)
Gets whether the red channel is written to the color buffer.
get shaderChunksVersion(): string
set shaderChunksVersion(value: string)
Returns the version of the shader chunks.
get slopeDepthBias(): number
set slopeDepthBias(value: number)
Gets the offset for the output depth buffer value based on the slope of the triangle relative to the camera.
protected _markLayoutDirty(): void
Marks the layout of the material as changed: the next preparation fetches it again, and replaces the uniform buffer and the bind group when it differs.
protected _markPropertyModified(property: MaterialProperty): void
Records that the public value of a typed property changed. The value is written to the uniform buffer by the next Material#update.
Parameters
property (MaterialProperty): The property.protected _markPropertyMutable(property: MaterialProperty, value: any): void
Records that the aggregate value of a typed property was handed out by its getter, so that an in-place mutation of the returned object can be detected by the next Material#update. Only the first exposure allocates a snapshot.
Parameters
property (MaterialProperty): The property.value (any): The value returned by the getter, with clone, equals and copy.clone(): Material
Clone a material.
Returns Material: A newly cloned material.
copy(source: Material): Material
Copy a material.
Parameters
source (Material): The material to copy.Returns Material: The destination material.
deleteParameter(name: string): void
Deletes a shader parameter on a material.
Parameters
name (string): The name of the parameter to delete.destroy(): void
Removes this material from the scene and possibly frees up memory from its shaders (if there are no other materials using it).
getDefine(name: string): boolean
Returns true if a define is enabled on the material, otherwise false.
Parameters
name (string): The name of the define to check.Returns boolean: The value of the define.
getParameter(name: string): any
Retrieves the specified shader parameter from a material.
Parameters
name (string): The name of the parameter to query.Returns any: The named parameter.
getShaderChunks(shaderLanguage?: string): ShaderChunkMap
Returns an object containing shader chunks for a specific shader language for the material.
These chunks define custom GLSL or WGSL code used to construct the final shader for the
material. The chunks can be also be included in shaders using the #include "ChunkName"
directive.
On the WebGL platform:
On the WebGPU platform:
To ensure faster shader compilation, it is recommended to provide shader chunks for all supported platforms.
A simple example on how to override a shader chunk providing emissive color for both GLSL and WGSL to simply return a red color:
material.getShaderChunks(SHADERLANGUAGE_GLSL).set('emissivePS', `
void getEmission() {
dEmission = vec3(1.0, 0.0, 1.0);
}
`);
material.getShaderChunks(SHADERLANGUAGE_WGSL).set('emissivePS', `
fn getEmission() {
dEmission = vec3f(1.0, 0.0, 1.0);
}
`);
// call update to apply the changes
material.update();
Parameters
shaderLanguage (string, optional, default SHADERLANGUAGE_GLSL): Specifies the shader language of shaders. Defaults to
SHADERLANGUAGE_GLSL.Returns ShaderChunkMap: - The shader chunks for the specified shader language.
setDefine(name: string, value: string | boolean | undefined): void
Adds or removes a define on the material. Defines can be used to enable or disable various parts of the shader code.
Parameters
name (string): The name of the define to set.
value (string | boolean | undefined): The value of the define. If undefined or false, the
define is removed.
A simple example on how to set a custom shader define value used by the shader processor.
material.setDefine('MY_DEFINE', true);
// call update to apply the changes, which will recompile the shader using the new define
material.update();
setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void
Sets a shader parameter on a material.
Parameters
name (string): The name of the parameter to set.data (number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): The value for the specified parameter.update(): void
Applies any changes made to the material's properties. This method should be called after modifying material properties to ensure the changes take effect.
The method will clear cached shader variants and trigger recompilation if:
Note: Shaders are not compiled immediately. Instead, existing shader variants are cleared and new variants will be compiled on-demand as they are needed for different render passes (e.g., forward, shadow, pick).
When global shader chunks are modified, update() must be called on each material that
should reflect those changes.
Class · extends RefCountedObject · category: Graphics
A graphical primitive. The mesh is defined by a VertexBuffer and an optional IndexBuffer. It also contains a primitive definition which controls the type of the primitive and the portion of the vertex or index buffer to use.
A mesh holds geometry only. To draw it, pair it with a Material in a MeshInstance and give that instance to a RenderComponent or a Layer; one mesh can back any number of instances. Mesh.fromGeometry builds a mesh from a Geometry such as BoxGeometry in one call. Meshes are reference counted: every MeshInstance holds a reference to its mesh, so call destroy on a mesh you created only once no instance uses it.
There are two ways a mesh can be generated or updated.
Mesh class provides interfaces such as setPositions and setUvs that provide a simple way to provide vertex and index data for the Mesh, and hiding the complexity of creating the VertexFormat. This is the recommended interface to use.
A simple example which creates a Mesh with 3 vertices, containing position coordinates only, to form a single triangle.
const mesh = new Mesh(device);
const positions = [
0, 0, 0, // pos 0
1, 0, 0, // pos 1
1, 1, 0 // pos 2
];
mesh.setPositions(positions);
mesh.update();
An example which creates a Mesh with 4 vertices, containing position and uv coordinates in channel 0, and an index buffer to form two triangles. Float32Array is used for positions and uvs.
const mesh = new Mesh(device);
const positions = new Float32Array([
0, 0, 0, // pos 0
1, 0, 0, // pos 1
1, 1, 0, // pos 2
0, 1, 0 // pos 3
]);
const uvs = new Float32Array([
0, 1 // uv 3
1, 1, // uv 2
1, 0, // uv 1
0, 0, // uv 0
]);
const indices = [
0, 1, 2, // triangle 0
0, 2, 3 // triangle 1
];
mesh.setPositions(positions);
mesh.setNormals(calculateNormals(positions, indices));
mesh.setUvs(0, uvs);
mesh.setIndices(indices);
mesh.update();
This example demonstrates that vertex attributes such as position and normals, and also indices can be provided using Arrays ([]) and also Typed Arrays (Float32Array and similar). Note that typed arrays have higher performance, and are generally recommended for per-frame operations or larger meshes, but their construction using new operator is costly operation. If you only need to operate on a small number of vertices or indices, consider using Arrays to avoid the overhead associated with allocating Typed Arrays.
Follow these links for more complex examples showing the functionality.
This allows greater flexibility, but is more complex to use. It allows more advanced setups, for example sharing a Vertex or Index Buffer between multiple meshes. See VertexBuffer, IndexBuffer and VertexFormat for details.
new Mesh(graphicsDevice: GraphicsDevice, options?: object)
Create a new Mesh instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this mesh.options (object, optional): Object for passing optional arguments.
options.storageIndex (boolean, optional): Defines if the index buffer can be used as
a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU.options.storageVertex (boolean, optional): Defines if the vertex buffer can be used as
a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU.indexBuffer: IndexBuffer[]
An array of index buffers. For unindexed meshes, this array can be empty. The first index
buffer in the array is used by MeshInstances with a renderStyle property set to
RENDERSTYLE_SOLID. The second index buffer in the array is used if renderStyle is
set to RENDERSTYLE_WIREFRAME.
primitive: { base: number; baseVertex: number; count: number; indexed?: boolean; type: number }[]
Array of primitive objects defining how vertex (and index) data in the mesh should be interpreted by the graphics device.
type is the type of primitive to render. Can be:
base is the offset of the first index or vertex to dispatch in the draw call.
baseVertex is the number added to each index value before indexing into the vertex buffers. (supported only in WebGPU, ignored in WebGL2)
count is the number of indices or vertices to dispatch in the draw call.
indexed specifies whether to interpret the primitive as indexed, thereby using the
currently set index buffer.
skin: Skin | null = null
The skin data (if any) that drives skinned mesh animations for this mesh.
vertexBuffer: VertexBuffer = null
The vertex buffer holding the vertex data of the mesh.
get aabb(): BoundingBox
set aabb(aabb: BoundingBox)
Gets the axis-aligned bounding box for the object space vertices of this mesh.
get morph(): Morph | null
set morph(morph: Morph | null)
Gets the morph data that drives morph target animations for this mesh.
clear(verticesDynamic?: boolean, indicesDynamic?: boolean, maxVertices?: number, maxIndices?: number): void
Clears the mesh of existing vertices and indices and resets the VertexFormat associated with the mesh. This call is typically followed by calls to methods such as setPositions, setVertexStream or setIndices and finally update to rebuild the mesh, allowing different VertexFormat.
Parameters
verticesDynamic (boolean, optional): Indicates the VertexBuffer should be created
with BUFFER_DYNAMIC usage. If not specified, BUFFER_STATIC is used.indicesDynamic (boolean, optional): Indicates the IndexBuffer should be created with
BUFFER_DYNAMIC usage. If not specified, BUFFER_STATIC is used.maxVertices (number, optional, default 0): A VertexBuffer will be allocated with at least
maxVertices, allowing additional vertices to be added to it without the allocation. If no
value is provided, a size to fit the provided vertices will be allocated.maxIndices (number, optional, default 0): An IndexBuffer will be allocated with at least
maxIndices, allowing additional indices to be added to it without the allocation. If no
value is provided, a size to fit the provided indices will be allocated.destroy(): void
Destroys the VertexBuffer and IndexBuffers associated with the mesh. This is normally called by Model#destroy and does not need to be called manually.
getColors(colors: NumericArray): number
Gets the vertex color data.
Parameters
colors (NumericArray): An array to populate with the vertex data. When
typed array is supplied, enough space needs to be reserved, otherwise only partial data is
copied.Returns number: Returns the number of vertices populated.
getIndices(indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>): number
Gets the index data.
Parameters
indices (number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>): An array to populate with the
index data. When a typed array is supplied, enough space needs to be reserved, otherwise
only partial data is copied.Returns number: Returns the number of indices populated.
getNormals(normals: NumericArray): number
Gets the vertex normals data.
Parameters
normals (NumericArray): An array to populate with the vertex data. When
typed array is supplied, enough space needs to be reserved, otherwise only partial data is
copied.Returns number: Returns the number of vertices populated.
getPositions(positions: NumericArray): number
Gets the vertex positions data.
Parameters
positions (NumericArray): An array to populate with the vertex data.
When typed array is supplied, enough space needs to be reserved, otherwise only partial data
is copied.Returns number: Returns the number of vertices populated.
getUvs(channel: number, uvs: NumericArray): number
Gets the vertex uv data.
Parameters
channel (number): The uv channel in [0..7] range.uvs (NumericArray): An array to populate with the vertex data. When
typed array is supplied, enough space needs to be reserved, otherwise only partial data is
copied.Returns number: Returns the number of vertices populated.
getVertexStream(semantic: string, data: NumericArray): number
Gets the vertex data corresponding to a semantic.
Parameters
semantic (string): The semantic of the vertex element to get. For supported
semantics, see SEMANTIC_* in VertexFormat.data (NumericArray): An array to populate with the vertex data. When
typed array is supplied, enough space needs to be reserved, otherwise only partial data is
copied.Returns number: Returns the number of vertices populated.
setColors(colors: ArrayLike<number>, componentCount?: number, numVertices?: number): void
Sets the vertex color array. Colors are stored using TYPE_FLOAT32 format, which is useful for HDR colors.
Parameters
colors (ArrayLike<number>): Vertex data containing colors.componentCount (number, optional, default GeometryData.DEFAULT_COMPONENTS_COLORS): The number of values that form a single color element.
Defaults to 4 if not specified, corresponding to r, g, b and a.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setColors32(colors: ArrayLike<number>, numVertices?: number): void
Sets the vertex color array. Colors are stored using TYPE_UINT8 format, which is useful for LDR colors. Values in the array are expected in [0..255] range, and are mapped to [0..1] range in the shader.
Parameters
colors (ArrayLike<number>): Vertex data containing colors. The array is
expected to contain 4 components per vertex, corresponding to r, g, b and a.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setIndices(indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, numIndices?: number): void
Sets the index array. Indices are stored using 16-bit format by default, unless more than 65535 vertices are specified, in which case 32-bit format is used.
Parameters
indices (number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>): The array of indices that
define primitives (lines, triangles, etc.).numIndices (number, optional): The number of indices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setNormals(normals: ArrayLike<number>, componentCount?: number, numVertices?: number): void
Sets the vertex normals array. Normals are stored using TYPE_FLOAT32 format.
Parameters
normals (ArrayLike<number>): Vertex data containing normals.componentCount (number, optional, default GeometryData.DEFAULT_COMPONENTS_NORMAL): The number of values that form a single normal element.
Defaults to 3 if not specified, corresponding to x, y and z direction.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setPositions(positions: ArrayLike<number>, componentCount?: number, numVertices?: number): void
Sets the vertex positions array. Vertices are stored using TYPE_FLOAT32 format.
Parameters
positions (ArrayLike<number>): Vertex data containing positions.componentCount (number, optional, default GeometryData.DEFAULT_COMPONENTS_POSITION): The number of values that form a single position element.
Defaults to 3 if not specified, corresponding to x, y and z coordinates.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setUvs(channel: number, uvs: ArrayLike<number>, componentCount?: number, numVertices?: number): void
Sets the vertex uv array. Uvs are stored using TYPE_FLOAT32 format.
Parameters
channel (number): The uv channel in [0..7] range.uvs (ArrayLike<number>): Vertex data containing uv-coordinates.componentCount (number, optional, default GeometryData.DEFAULT_COMPONENTS_UV): The number of values that form a single uv element.
Defaults to 2 if not specified, corresponding to u and v coordinates.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.setVertexStream(semantic: string, data: ArrayLike<number>, componentCount: number, numVertices?: number, dataType?: number, dataTypeNormalize?: boolean, asInt?: boolean): void
Sets the vertex data for any supported semantic.
Parameters
semantic (string): The meaning of the vertex element. For supported semantics, see
SEMANTIC_* in VertexFormat.data (ArrayLike<number>): Vertex data for the specified semantic.componentCount (number): The number of values that form a single Vertex element. For
example when setting a 3D position represented by 3 numbers per vertex, number 3 should be
specified.numVertices (number, optional): The number of vertices to be used from data array. If not
provided, the whole data array is used. This allows to use only part of the data array.dataType (number, optional, default TYPE_FLOAT32): The format of data when stored in the VertexBuffer, see
TYPE_* in VertexFormat. When not specified, TYPE_FLOAT32 is used.dataTypeNormalize (boolean, optional, default false): If true, vertex attribute data will be mapped from a
0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data is left
unchanged. If this property is unspecified, false is assumed.asInt (boolean, optional, default false): If true, vertex attribute data will be accessible as integer
numbers in shader code. Defaults to false, which means that vertex attribute data will be
accessible as floating point numbers. Can be only used with INT and UINT data types.update(primitiveType?: number, updateBoundingBox?: boolean): void
Applies any changes to vertex stream and indices to mesh. This allocates or reallocates vertexBuffer or indexBuffer to fit all provided vertices and indices, and fills them with data.
Parameters
primitiveType (number, optional, default PRIMITIVE_TRIANGLES): The type of primitive to render. Can be:
Defaults to PRIMITIVE_TRIANGLES if not specified.
updateBoundingBox (boolean, optional, default true): True to update bounding box. Bounding box is updated
only if positions were set since last time update was called, and componentCount for
position was 3, otherwise bounding box is not updated. See setPositions. Defaults to
true if not specified. Set this to false to avoid update of the bounding box and use aabb
property to set it instead.
static fromGeometry(graphicsDevice: GraphicsDevice, geometry: Geometry, options?: object): Mesh
Create a new Mesh instance from Geometry object.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this mesh.geometry (Geometry): The geometry object to create the mesh from.options (object, optional, default {}): An object that specifies optional inputs for the function as follows:
options.storageIndex (boolean, optional): Defines if the index buffer of the mesh can be used as
a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU.options.storageVertex (boolean, optional): Defines if the vertex buffer of the mesh can be used as
a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU.Returns Mesh: A new mesh.
get refCount(): numberdecRefCount(): voidincRefCount(): voidClass · category: Graphics
An instance of a Mesh. A single mesh can be referenced by many mesh instances that can have different transforms and materials.
A mesh instance is created from a Mesh, a Material and the GraphNode
whose world transform places it, and it is drawn only once it belongs to a Layer.
Components such as RenderComponent create mesh instances from their assets and add them
to the layers in their layers list. A mesh instance you construct yourself is placed either
by assigning it to RenderComponent#meshInstances or by adding it to a layer directly
with Layer#addMeshInstances.
Per-instance rendering state lives here rather than on the shared mesh or material:
visible, castShadow and receiveShadow, cull for frustum culling,
drawOrder for manual sorting, and setParameter for shader uniforms that override
the material's. aabb is the world-space bounds derived from the mesh bounds and the
node's transform, and can be assigned to override it.
Hardware instancing lets the GPU draw many copies of the same geometry with a single draw call.
Use setInstancing to attach a vertex buffer that holds per-instance data
(for example a mat4 world-matrix for every instance). Set instancingCount
to control how many instances are rendered. Passing null to setInstancing
disables instancing once again.
// vb is a vertex buffer with one 4×4 matrix per instance
meshInstance.setInstancing(vb);
meshInstance.instancingCount = numInstances;
The default matrix format, VertexFormat.getDefaultInstancingFormat, occupies the
attribute locations of TEXCOORD6 and TEXCOORD7. A material sampling those UV sets on an
instanced mesh needs a custom instancing vertex format on other attributes, as shown by the
instancing-custom example.
Examples
Instead of issuing draw calls from the CPU, parameters are written into a GPU
storage buffer and executed via indirect draw commands. Allocate one or more slots with
GraphicsDevice.getIndirectDrawSlot(count), then bind the mesh instance to those slots:
const slot = app.graphicsDevice.getIndirectDrawSlot(count);
meshInstance.setIndirect(null, slot, count); // first arg can be a CameraComponent or null
Example
Multi-draw lets the engine submit multiple sub-draws with a single API call. On WebGL2 this maps
to the WEBGL_multi_draw extension; on WebGPU, to indirect multi-draw. Use setMultiDraw
to allocate a DrawCommands container, fill it with sub-draws using
DrawCommands#add and finalize with DrawCommands#update whenever the data changes.
Support: GraphicsDevice#supportsMultiDraw is true on WebGPU and commonly true on WebGL2 (high coverage). When not supported, the engine can still render by issuing a fast internal loop of single draws using the multi-draw data.
// two indexed sub-draws from a single mesh
const cmd = meshInstance.setMultiDraw(null, 2);
cmd.add(0, 36, 1, 0);
cmd.add(1, 60, 1, 36);
cmd.update(2);
When draw commands (indirect or multi-draw, see setIndirect and setMultiDraw) are bound, they are the source of truth for rendering: the number of draws and the per-draw instance counts come from the draw commands, and instancingCount is ignored. In this case setting instancingCount to 0 does not skip rendering. instancingCount only takes effect for plain hardware instancing, when no draw commands are bound.
new MeshInstance(mesh: Mesh, material: Material, node?: GraphNode)
Create a new MeshInstance instance.
Parameters
mesh (Mesh): The graphics mesh to instance.material (Material): The material to use for this mesh instance.node (GraphNode, optional, default null): The graph node defining the transform for this instance. This
parameter is optional when used with RenderComponent and will use the node the
component is attached to.Example
// Create a mesh instance pointing to a 1x1x1 'cube' mesh
const mesh = Mesh.fromGeometry(app.graphicsDevice, new BoxGeometry());
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
this.app.scene.root.addChild(entity);
castShadow: boolean = false
Enable shadow casting for this mesh instance. Use this property to enable/disable shadow casting without overhead of removing from scene. Note that this property does not add the mesh instance to appropriate list of shadow casters on a Layer, but allows mesh to be skipped from shadow casting while it is in the list already. Defaults to false.
cull: boolean = true
Controls whether the mesh instance can be culled by frustum culling (see CameraComponent#frustumCulling). Defaults to true.
drawOrder: number = 0
Determines the rendering order of mesh instances. Only used when mesh instances are added to a Layer with Layer#opaqueSortMode or Layer#transparentSortMode (depending on the material) set to SORTMODE_MANUAL.
shaderPassMask: number = 0xFFFFFFFF
A bitmask controlling which shader passes this mesh instance is rendered in. Bit N
corresponds to the shader pass with index N: the built-in forward pass is
SHADER_FORWARD, and indices for custom shader passes are obtained from
CameraComponent#setShaderPass. Defaults to 0xFFFFFFFF (all passes). For example,
clearing the forward pass bit keeps the mesh in the other passes (such as the camera depth
prepass that feeds Depth of Field) while making it invisible in the rendered color image.
Example
// clear the forward (color) pass bit, leaving all other pass bits set: the mesh is no longer
// drawn in the color image, but still takes part in the other passes (such as the prepass)
meshInstance.shaderPassMask &= ~(1 << SHADER_FORWARD);
Example
// set the forward (color) pass bit, leaving all other pass bits unchanged
meshInstance.shaderPassMask |= (1 << SHADER_FORWARD);
Example
// exclude the mesh from a custom shader pass set up on the camera (see
// CameraComponent#setShaderPass), leaving all other pass bits set
const customPass = cameraComponent.setShaderPass('custom_rendering');
meshInstance.shaderPassMask &= ~(1 << customPass);
Example
// test whether the forward (color) pass bit is set
const forwardBitSet = (meshInstance.shaderPassMask & (1 << SHADER_FORWARD)) !== 0;
Example
// set every pass bit (the default value)
meshInstance.shaderPassMask = 0xFFFFFFFF;
shadowCascadeMask: number = SHADOW_CASCADE_ALL
Specifies a bitmask that controls which shadow cascades a mesh instance contributes to when rendered with a LIGHTTYPE_DIRECTIONAL light source. This setting is only effective if the castShadow property is enabled. Defaults to SHADOW_CASCADE_ALL, which means the mesh casts shadows into all available cascades.
visible: boolean = true
Enable rendering for this mesh instance. Use visible property to enable/disable rendering without overhead of removing from scene. But note that the mesh instance is still in the hierarchy and still in the draw call list.
visibleThisFrame: boolean = false
Read this value in the Scene.EVENT_POSTCULL event to determine if the object is actually going to be rendered.
get aabb(): BoundingBox
set aabb(aabb: BoundingBox)
Gets the world space axis-aligned bounding box for this mesh instance.
get calculateSortDistance(): CalculateSortDistanceCallback | null
set calculateSortDistance(calculateSortDistance: CalculateSortDistanceCallback | null)
Gets the callback to calculate sort distance.
get drawBucket(): number
set drawBucket(bucket: number)
Gets the draw bucket for mesh instance.
get instancingCount(): number
set instancingCount(value: number)
Gets the number of instances when using hardware instancing to render the mesh.
get mask(): number
set mask(val: number)
Gets the light mask of this mesh instance: which LightComponents light it.
get material(): Material | null
set material(material: Material | null)
Gets the material used by this mesh instance.
get mesh(): Mesh | null
set mesh(mesh: Mesh | null)
Gets the graphics mesh being instanced.
get morphInstance(): MorphInstance | null
set morphInstance(val: MorphInstance | null)
Gets the morph instance managing morphing of this mesh instance.
get node(): GraphNode
set node(node: GraphNode)
Gets the graph node defining the transform for this instance.
get renderStyle(): number
set renderStyle(renderStyle: number)
Gets the render style of the mesh instance.
get skinInstance(): SkinInstance | null
set skinInstance(val: SkinInstance | null)
Gets the skin instance managing skinning of this mesh instance.
deleteParameter(name: string): void
Deletes a shader parameter on a mesh instance.
Parameters
name (string): The name of the parameter to delete.getIndirectMetaData(): Int32Array<ArrayBufferLike>
Retrieves the mesh metadata needed for indirect rendering.
Returns Int32Array<ArrayBufferLike>: - A typed array with 4 elements representing the mesh metadata, which
is typically needed when generating indirect draw call parameters using Compute shader. These
can be provided to the Compute shader using vec4i uniform. The values are based on
Mesh#primitive, stored in this order: [count, base, baseVertex, 0]. The last value is
always zero and is reserved for future use.
getParameter(name: string): any
Retrieves the specified shader parameter from a mesh instance.
Parameters
name (string): The name of the parameter to query.Returns any: The named parameter, or undefined if no parameter with that
name is set on this mesh instance.
setIndirect(camera: CameraComponent | null, slot: number, count?: number): void
Sets the MeshInstance to be rendered using indirect rendering, where the GPU, typically using a Compute shader, stores draw call parameters in a buffer. Note that this is only supported on WebGPU (see GraphicsDevice#supportsIndirectDraw), and ignored on other platforms, where the mesh instance renders as a normal draw call.
Parameters
camera (CameraComponent | null): Camera component to set indirect data for, or
null if the indirect slot should be used for all cameras.slot (number): Slot in the buffer to set the draw call parameters. Allocate a slot
in the buffer by calling GraphicsDevice#getIndirectDrawSlot. Pass -1 to disable
indirect rendering for the specified camera (or the shared entry when camera is null).count (number, optional, default 1): Optional number of consecutive slots to use. Defaults to 1.setInstancing(vertexBuffer: true | VertexBuffer | null, cull?: boolean): void
Sets up MeshInstance to be rendered using Hardware Instancing. Note that instancingCount is automatically set to the number of vertices of the vertex buffer when it is provided.
Parameters
vertexBuffer (true | VertexBuffer | null): Vertex buffer to hold per-instance vertex data
(usually world matrices). Pass true to enable attributeless instancing where the instance
index is derived from gl_InstanceID / instance_index builtins rather than a vertex
buffer attribute — the caller must set instancingCount manually. Pass null to turn
off hardware instancing.cull (boolean, optional, default false): Whether to perform frustum culling on this instance. If true, the whole
instance will be culled by the camera frustum. This often involves setting
RenderComponent#customAabb containing all instances. Defaults to false, which means
the whole instance is always rendered.setMultiDraw(camera: CameraComponent | null, maxCount?: number): DrawCommands | undefined
Sets the MeshInstance to be rendered using multi-draw, where multiple sub-draws are executed with a single draw call.
Note: Each call to this method invalidates any previously stored draw command data for the specified camera.
Parameters
camera (CameraComponent | null): Camera component to bind commands to, or null to share
across all cameras.maxCount (number, optional, default 1): Maximum number of sub-draws to allocate. Defaults to 1. Pass 0
to disable multi-draw for the specified camera (or the shared entry when camera is null).Returns DrawCommands | undefined: The commands container to populate with sub-draw commands.
setParameter(name: string, data: number | number[] | Float32Array<ArrayBufferLike> | Texture): void
Sets a shader parameter on a mesh instance. Note that this parameter will take precedence over parameter of the same name if set on Material this mesh instance uses for rendering. To change an array value, call this method again with it; the contents of an array are not guaranteed to be re-read on later draws.
Parameters
name (string): The name of the parameter to set.data (number | number[] | Float32Array<ArrayBufferLike> | Texture): The value for the specified parameter.Class · category: Graphics
A model is a graphical object that can be added to or removed from a scene. It contains a hierarchy and any number of mesh instances.
new Model()
Creates a new model.
Example
// Create a new model
const model = new Model();
graph: GraphNode | null = null
The root node of the model's graph node hierarchy.
meshInstances: MeshInstance[] = []
An array of MeshInstances contained in this model.
morphInstances: MorphInstance[] = []
An array of MorphInstances contained in this model.
skinInstances: SkinInstance[] = []
An array of SkinInstances contained in this model.
clone(): Model
Clones a model. The returned model has a newly created hierarchy and mesh instances, but meshes are shared between the clone and the specified model.
Returns Model: A clone of the specified model.
Example
const clonedModel = model.clone();
destroy(): void
Destroys skinning texture and possibly deletes vertex/index buffers of a model. Mesh is reference-counted, so buffers are only deleted if all models with referencing mesh instances were deleted. That means all in-scene models + the "base" one (asset.resource) which is created when the model is parsed. It is recommended to use asset.unload() instead, which will also remove the model from the scene.
generateWireframe(): void
Generates the necessary internal data for a model to be renderable as wireframe. Once this function has been called, any mesh instance in the model can have its renderStyle property set to RENDERSTYLE_WIREFRAME.
Example
model.generateWireframe();
for (let i = 0; i < model.meshInstances.length; i++) {
model.meshInstances[i].renderStyle = RENDERSTYLE_WIREFRAME;
}
Class · extends Component · category: Graphics
The ModelComponent enables an Entity to render 3D models. The type property can
be set to one of several predefined shapes (such as box, sphere, cone and so on).
Alternatively, the component can be configured to manage an arbitrary Model. This can
either be created programmatically or loaded from an Asset.
The Model managed by this component is positioned, rotated, and scaled in world space by the world transformation matrix of the owner Entity. This world matrix is derived by combining the entity's local transformation (position, rotation, and scale) with the world transformation matrix of its parent entity in the scene hierarchy.
You should never need to use the ModelComponent constructor directly. To add a ModelComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('model', {
type: 'box'
});
Once the ModelComponent is added to the entity, you can access it via the Entity#model property:
entity.model.type = 'capsule'; // Set the model component's type
console.log(entity.model.type); // Get the model component's type and print it
isStatic: boolean = false
Mark meshes as non-movable (optimization).
get asset(): number | Asset<string> | null
set asset(value: number | Asset<string> | null)
Gets the model asset id for the component.
get batchGroupId(): number
set batchGroupId(value: number)
Gets the batch group for the mesh instances in this component (see BatchGroup).
get castShadows(): boolean
set castShadows(value: boolean)
Gets whether attached meshes will cast shadows for lights that have shadow casting enabled.
get castShadowsLightmap(): boolean
set castShadowsLightmap(value: boolean)
Gets whether meshes instances will cast shadows when rendering lightmaps.
get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)
Gets the custom object space bounding box that is used for visibility culling of attached mesh instances.
get layers(): readonly number[]
set layers(value: readonly number[])
Gets the array of layer IDs (Layer#id) to which the mesh instances belong.
get lightmapped(): boolean
set lightmapped(value: boolean)
Gets whether the component is affected by the runtime lightmapper.
get lightmapSizeMultiplier(): number
set lightmapSizeMultiplier(value: number)
Gets the lightmap resolution multiplier.
get mapping(): Readonly<Record<string, number>>
set mapping(value: Readonly<Record<string, number>>)
Gets the dictionary that holds material overrides for each mesh instance.
get material(): Material
set material(value: Material)
Gets the Material that will be used to render the model.
get materialAsset(): number | Asset<string> | null
set materialAsset(value: number | Asset<string> | null)
Gets the material Asset that will be used to render the component.
get meshInstances(): readonly MeshInstance[] | null
set meshInstances(value: readonly MeshInstance[] | null)
Gets the array of mesh instances contained in the component's model. Use the setter to replace the array; do not mutate the returned array.
get model(): Model | null
set model(value: Model | null)
Gets the model owned by this component. In this case a model is not set or loaded, this will return null.
get receiveShadows(): boolean
set receiveShadows(value: boolean)
Gets whether shadows will be cast on attached meshes.
get type(): "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus"
set type(value: "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus")
Gets the type of the component.
hide(): void
Stop rendering model without removing it from the scene hierarchy. This method sets the MeshInstance#visible property of every MeshInstance in the model to false Note, this does not remove the model or mesh instances from the scene hierarchy or draw call list. So the model component still incurs some CPU overhead.
Example
this.timer = 0;
this.visible = true;
// ...
// blink model every 0.1 seconds
this.timer += dt;
if (this.timer > 0.1) {
if (!this.visible) {
this.entity.model.show();
this.visible = true;
} else {
this.entity.model.hide();
this.visible = false;
}
this.timer = 0;
}
show(): void
Enable rendering of the model if hidden using hide. This method sets all the MeshInstance#visible property on all mesh instances to true.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Allows an Entity to render a model or a primitive shape like a box, capsule, sphere, cylinder, cone etc.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends RefCountedObject · category: Graphics
Contains a list of MorphTargets, a combined delta AABB and some associated data.
new Morph(targets: MorphTarget[], graphicsDevice: GraphicsDevice, options?: object)
Create a new Morph instance.
Parameters
targets (MorphTarget[]): A list of morph targets.graphicsDevice (GraphicsDevice): The graphics device used to manage this morph target.options (object, optional, default {}): Object for passing optional arguments.
options.preferHighPrecision (boolean, optional, default false): True if high precision storage should be
preferred. This is faster to create and allows higher precision, but takes more memory and
might be slower to render. Defaults to false.preferHighPrecision: boolean
get targets(): MorphTarget[]
Gets the array of morph targets.
destroy(): void
Frees video memory allocated by this object.
get refCount(): numberdecRefCount(): voidincRefCount(): voidClass · category: Graphics
An instance of Morph. Contains weights to assign to every MorphTarget, manages selection of active morph targets.
new MorphInstance(morph: Morph)
Create a new MorphInstance instance.
Parameters
morph: Morph
The morph with its targets, which is being instanced.
clone(): MorphInstance
Clones a MorphInstance. The returned clone uses the same Morph and weights are set to defaults.
Returns MorphInstance: A clone of the specified MorphInstance.
destroy(): void
Frees video memory allocated by this object.
getWeight(key: string | number): number
Gets current weight of the specified morph target.
Parameters
key (string | number): An identifier for the morph target. Either the weight index or
the weight name.Returns number: Weight.
setWeight(key: string | number, weight: number): void
Sets weight of the specified morph target.
Parameters
key (string | number): An identifier for the morph target. Either the weight index or
the weight name.weight (number): Weight.update(): void
Selects active morph targets and prepares morph for rendering. Called automatically by renderer.
Class · category: Graphics
A Morph Target (also known as Blend Shape) contains deformation data to apply to existing mesh. Multiple morph targets can be blended together on a mesh. This is useful for effects that are hard to achieve with conventional animation and skinning.
new MorphTarget(options: object, ...args: any[])
Create a new MorphTarget instance.
Parameters
options (object): Object for passing optional arguments.
options.aabb (BoundingBox, optional): Bounding box. Will be automatically generated, if
undefined.options.defaultWeight (number, optional): Default blend weight to use for this morph target.options.deltaNormals (ArrayLike<number>, optional): An array of 3-dimensional vertex normal
offsets.options.deltaPositions (ArrayLike<number>): An array of 3-dimensional vertex position
offsets.options.name (string, optional): Name.options.preserveData (boolean, optional): When true, the morph target keeps its data passed using the options,
allowing the clone operation.args (any[])used: boolean = false
A used flag. A morph target can be used / owned by the Morph class only one time.
get defaultWeight(): number
Gets the default weight of the morph target.
get name(): string
Gets the name of the morph target.
clone(): MorphTarget
Returns an identical copy of the specified morph target. This can only be used if the morph target was created with options.preserveData set to true.
Returns MorphTarget: A morph target instance containing the result of the cloning.
Class · category: Graphics
The OutlineRenderer draws solid color outlines around the silhouettes of entities, for example to highlight objects that are selected or hovered in an editor. Each entity can be outlined in its own color.
The outlines are generated in three steps:
The outlines are drawn over everything the scene camera has rendered up to that layer, so they remain visible when the outlined objects are occluded by other objects. Anything rendered in that layer or after it, such as gizmos, is drawn on top of the outlines.
OutlineRenderer#frameUpdate needs to be called every frame to keep the outlines in sync with the scene camera. Only render and model components are outlined, and the outline color is applied to mesh instances using a StandardMaterial.
Relevant Engine API examples:
Example
// Create a layer used to render the outlined objects. It is added to the layer composition, but
// not to the scene camera, so that the camera does not render the outlined objects a second time.
const outlineLayer = new Layer({ name: 'OutlineLayer' });
app.scene.layers.push(outlineLayer);
// Create the outline renderer
const outlineRenderer = new OutlineRenderer(app, outlineLayer);
// Outline an entity and its descendants in red, and another entity in white
outlineRenderer.addEntity(entity1, Color.RED);
outlineRenderer.addEntity(entity2, Color.WHITE);
// Each frame, composite the outlines into the scene before the scene camera renders the opaque
// part of the 'Immediate' layer
const immediateLayer = app.scene.layers.getLayerByName('Immediate');
app.on('update', () => {
outlineRenderer.frameUpdate(cameraEntity, immediateLayer, false);
});
// Later, stop outlining the first entity
outlineRenderer.removeEntity(entity1);
new OutlineRenderer(app: AppBase, renderingLayer?: Layer, priority?: number)
Create a new OutlineRenderer.
Parameters
app (AppBase): The application.renderingLayer (Layer, optional): The layer the outlined mesh instances are added to, and
which the internal outline camera renders. It must be part of the scene's layer composition.
Defaults to the 'Immediate' layer. As the scene camera renders the 'Immediate' layer by
default, the outlined objects are then rendered by the scene camera a second time - to avoid
this, supply a dedicated layer which is not rendered by any other camera.priority (number, optional, default -1): The priority of the internal outline camera. It needs to render
before the scene camera, so it has to be smaller than the priority of the scene camera.
Defaults to -1.addEntity(entity: Entity, color: Color, recursive?: boolean): void
Add an entity to the outline renderer, to draw an outline around it. The mesh instances of
the entity's render and model components are outlined, including those of its descendants
unless recursive is false. Adding an entity that is already outlined changes its outline
color.
Render and model components that are not currently rendered, because they or their entity are disabled, are skipped - this is evaluated when the entity is added.
An entity should be outlined by a single outline renderer at a time. The outline color is stored on its mesh instances, so they cannot be outlined by more than one renderer, and removing them from one renderer would remove their outline from the other as well.
Parameters
entity (Entity): The entity to add.color (Color): The color of the outline. The alpha component is ignored.recursive (boolean, optional, default true): Whether to also add the mesh instances of the entity's
descendants. Defaults to true.Example
// outline an entity and its descendants in orange
outlineRenderer.addEntity(entity, new Color(1, 0.5, 0));
destroy(): void
Destroy the outline renderer and its resources. All entities are removed from the outline renderer first.
frameUpdate(sceneCameraEntity: Entity, blendLayer: Layer, blendLayerTransparent: boolean): void
Update the outline renderer. This needs to be called once per frame, after the scene camera
has been positioned, for example from the application's update event, which fires after
scripts have been updated. It matches the internal outline camera to the scene camera's
transform, projection, clip planes and resolution, and schedules the outlines to be
composited into the scene for this frame.
The outlines are composited just before the scene camera renders the opaque or transparent
part of blendLayer, so that part of the layer, and everything rendered after it, is drawn
on top of the outlines. The scene camera needs to render blendLayer, otherwise the
outlines are not visible.
Parameters
sceneCameraEntity (Entity): The entity with the camera component used to render the
scene.blendLayer (Layer): The layer before which the outlines are composited.blendLayerTransparent (boolean): True to composite the outlines before the
transparent part of blendLayer, false to composite them before its opaque part.Example
const immediateLayer = app.scene.layers.getLayerByName('Immediate');
app.on('update', () => {
outlineRenderer.frameUpdate(cameraEntity, immediateLayer, false);
});
removeAllEntities(): void
Remove all entities from the outline renderer, for example to clear the selection.
Example
// outline only the newly selected entity
outlineRenderer.removeAllEntities();
outlineRenderer.addEntity(selectedEntity, Color.WHITE);
removeEntity(entity: Entity, recursive?: boolean): void
Remove an entity from the outline renderer, to stop drawing its outline. This also works for an entity that has been disabled since it was added.
Parameters
entity (Entity): The entity to remove.recursive (boolean, optional, default true): Whether to also remove the mesh instances of the entity's
descendants. Defaults to true.Example
outlineRenderer.removeEntity(entity);
Class · extends Component · category: Graphics
The ParticleSystemComponent enables an Entity to simulate particles and produce a renderable particle mesh on either CPU or GPU. GPU simulation is generally much faster than its CPU counterpart, because it avoids slow CPU-GPU synchronization and takes advantage of many GPU cores. However, it requires client support for reasonable uniform counts, reading from multiple textures in a vertex shader and the OES_texture_float extension, including rendering into float textures. Most mobile devices fail to satisfy these requirements, so it's not recommended to simulate thousands of particles on them. The GPU version also can't sort particles, so enabling sorting forces CPU mode too.
Particle rotation is specified by a single angle parameter: default billboard particles rotate around the camera-facing axis, while mesh particles rotate around two different view-independent axes. Most of the simulation parameters are specified with Curve or CurveSet. Curves are interpolated based on each particle's lifetime, therefore parameters are able to change over time. Most curve parameters can also be specified by 2 minimum/maximum curves, so that each particle picks a random value in-between.
You should never need to use the ParticleSystemComponent constructor directly. To add a ParticleSystemComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('particlesystem', {
numParticles: 100,
lifetime: 2,
rate: 0.1
});
Once the ParticleSystemComponent is added to the entity, you can access it via the Entity#particlesystem property:
entity.particlesystem.loop = false; // Play the system once then stop
console.log(entity.particlesystem.loop); // Get the loop flag and print it
Relevant Engine API examples:
get alignToMotion(): boolean
set alignToMotion(arg: boolean)
Gets whether particles are oriented in their direction of motion or not.
get alphaGraph(): Curve
set alphaGraph(arg: Curve)
Gets the alpha graph.
get alphaGraph2(): Curve
set alphaGraph2(arg: Curve)
Gets the second alpha graph.
get animIndex(): number
set animIndex(arg: number)
Gets the index of the animation to play.
get animLoop(): boolean
set animLoop(arg: boolean)
Gets whether the sprite sheet animation plays once or loops continuously.
get animNumAnimations(): number
set animNumAnimations(arg: number)
Gets the number of sprite sheet animations contained within the current sprite sheet.
get animNumFrames(): number
set animNumFrames(arg: number)
Gets the number of sprite sheet frames in the current sprite sheet animation.
get animSpeed(): number
set animSpeed(arg: number)
Gets the sprite sheet animation speed.
get animStartFrame(): number
set animStartFrame(arg: number)
Gets the sprite sheet frame that the animation should begin playing from.
get animTilesX(): number
set animTilesX(arg: number)
Gets the number of horizontal tiles in the sprite sheet.
get animTilesY(): number
set animTilesY(arg: number)
Gets the number of vertical tiles in the sprite sheet.
get autoPlay(): boolean
set autoPlay(arg: boolean)
Gets whether the particle system plays automatically on creation.
get blendType(): number
set blendType(arg: number)
Gets how particles are blended when being written to the currently active render target.
get colorGraph(): CurveSet
set colorGraph(arg: CurveSet)
Gets the color graph.
get colorGraph2(): CurveSet
set colorGraph2(arg: CurveSet)
Gets the second color graph.
get colorMap(): Texture
set colorMap(arg: Texture)
Gets the color map texture to apply to all particles in the system.
get colorMapAsset(): Asset<string> | null
set colorMapAsset(arg: Asset<string> | null)
Gets the Asset used to set the colorMap.
get depthSoftening(): number
set depthSoftening(arg: number)
Gets whether depth softening is enabled.
get depthWrite(): boolean
set depthWrite(arg: boolean)
Gets whether depth writes is enabled.
get drawOrder(): number
set drawOrder(drawOrder: number)
Gets the draw order of the component.
get emitterExtents(): Vec3
set emitterExtents(arg: Vec3)
Gets the extents of a local space bounding box within which particles are spawned at random positions.
get emitterExtentsInner(): Vec3
set emitterExtentsInner(arg: Vec3)
Gets the exception of extents of a local space bounding box within which particles are not spawned.
get emitterRadius(): number
set emitterRadius(arg: number)
Gets the radius within which particles are spawned at random positions.
get emitterRadiusInner(): number
set emitterRadiusInner(arg: number)
Gets the inner radius within which particles are not spawned.
get emitterShape(): number
set emitterShape(arg: number)
Gets the shape of the emitter.
get halfLambert(): boolean
set halfLambert(arg: boolean)
Gets whether Half Lambert lighting is enabled.
get initialVelocity(): number
set initialVelocity(arg: number)
Gets the magnitude of the initial emitter velocity.
get intensity(): number
set intensity(arg: number)
Gets the color multiplier.
get layers(): readonly number[]
set layers(arg: readonly number[])
Gets the array of layer IDs (Layer#id) to which this particle system belongs.
get lifetime(): number
set lifetime(arg: number)
Gets the length of time in seconds between a particle's birth and its death.
get lighting(): boolean
set lighting(arg: boolean)
Gets whether particles will be lit by ambient and directional lights.
get localSpace(): boolean
set localSpace(arg: boolean)
Gets whether particles move with respect to the emitter's transform rather then world space.
get localVelocityGraph(): CurveSet
set localVelocityGraph(arg: CurveSet)
Gets the local space velocity graph.
get localVelocityGraph2(): CurveSet
set localVelocityGraph2(arg: CurveSet)
Gets the second velocity graph.
get loop(): boolean
set loop(arg: boolean)
Gets whether the particle system loops.
get mesh(): Mesh
set mesh(arg: Mesh)
Gets the polygonal mesh to be used as a particle.
get meshAsset(): Asset<string> | null
set meshAsset(arg: Asset<string> | null)
Gets the Asset used to set the mesh.
get normalMap(): Texture
set normalMap(arg: Texture)
Gets the normal map texture to apply to all particles in the system.
get normalMapAsset(): Asset<string> | null
set normalMapAsset(arg: Asset<string> | null)
Gets the Asset used to set the normalMap.
get numParticles(): number
set numParticles(arg: number)
Gets the maximum number of simulated particles.
get orientation(): number
set orientation(arg: number)
Gets the particle orientation mode.
get particleNormal(): Vec3
set particleNormal(arg: Vec3)
Gets the particle normal.
get preWarm(): boolean
set preWarm(arg: boolean)
Gets whether the particle system will be initialized as though it has already completed a full cycle.
get radialSpeedGraph(): Curve
set radialSpeedGraph(arg: Curve)
Gets the radial speed graph.
get radialSpeedGraph2(): Curve
set radialSpeedGraph2(arg: Curve)
Gets the second radial speed graph.
get randomizeAnimIndex(): boolean
set randomizeAnimIndex(arg: boolean)
Gets whether each particle emitted by the system will play a random animation from the
sprite sheet, up to animNumAnimations.
get rate(): number
set rate(arg: number)
Gets the minimal interval in seconds between particle births.
get rate2(): number
set rate2(arg: number)
Gets the maximal interval in seconds between particle births.
get renderAsset(): Asset<string> | null
set renderAsset(arg: Asset<string> | null)
Gets the Render Asset used to set the mesh.
get rotationSpeedGraph(): Curve
set rotationSpeedGraph(arg: Curve)
Gets the rotation speed graph.
get rotationSpeedGraph2(): Curve
set rotationSpeedGraph2(arg: Curve)
Gets the second rotation speed graph.
get scaleGraph(): Curve
set scaleGraph(arg: Curve)
Gets the scale graph.
get scaleGraph2(): Curve
set scaleGraph2(arg: Curve)
Gets the second scale graph.
get screenSpace(): boolean
set screenSpace(arg: boolean)
Gets whether particles are rendered in 2D screen space.
get sort(): number
set sort(arg: number)
Gets the particle sorting mode.
get startAngle(): number
set startAngle(arg: number)
Gets the minimal initial Euler angle of a particle.
get startAngle2(): number
set startAngle2(arg: number)
Gets the maximal initial Euler angle of a particle.
get stretch(): number
set stretch(arg: number)
Gets how much particles are stretched in their direction of motion.
get useFog(): boolean
set useFog(arg: boolean)
Gets whether the camera's fog is applied to the particles.
get useTonemap(): boolean
set useTonemap(arg: boolean)
Gets whether the camera's tonemapping and the scene exposure are applied to the particles.
get velocityGraph(): CurveSet
set velocityGraph(arg: CurveSet)
Gets the world space velocity graph.
get velocityGraph2(): CurveSet
set velocityGraph2(arg: CurveSet)
Gets the second world space velocity graph.
get wrap(): boolean
set wrap(arg: boolean)
Gets whether particles wrap based on the set wrap bounds.
get wrapBounds(): Vec3
set wrapBounds(arg: Vec3)
Gets the wrap bounds of the particle system.
isPlaying(): boolean
Checks if simulation is in progress.
Returns boolean: True if the particle system is currently playing and false otherwise.
pause(): void
Freezes the simulation.
play(): void
Enables/unfreezes the simulation.
reset(): void
Resets particle state, doesn't affect playing.
stop(): void
Disables the emission of new particles, lets existing to finish their simulation.
unpause(): void
Unfreezes the simulation.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Manages the ParticleSystemComponents of an application. Reach it through
app.systems.particlesystem; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
Picker object used to select mesh instances from screen coordinates. It can also optionally capture depth information to determine world positions of picked points.
The picker works by rendering mesh instances to an offscreen render target with unique IDs encoded as colors. When queried, it reads back the pixel data to identify which mesh instance was at the specified screen coordinates. If depth picking is enabled, it also captures depth values to compute world positions.
Main API methods:
Performance considerations: The picker resolution can be set lower than the screen resolution for better performance, though this reduces picking precision and may miss small objects.
Example
// Create a picker with depth picking enabled at quarter resolution
const picker = new Picker(app, canvas.width * 0.25, canvas.height * 0.25, true);
// In your update loop, prepare the picker
picker.resize(canvas.width * 0.25, canvas.height * 0.25);
picker.prepare(camera, scene);
// Pick mesh instances in an area
picker.getSelectionAsync(x, y, width, height).then((meshInstances) => {
meshInstances.forEach((meshInstance) => {
console.log('Picked:', meshInstance.node.name);
});
});
// Pick world position (requires depth enabled)
picker.getWorldPointAsync(x, y).then((worldPoint) => {
if (worldPoint) {
console.log(worldPoint);
}
});
See - Picker Example
new Picker(app: AppBase, width: number, height: number, depth?: boolean)
Create a new Picker instance.
Parameters
app (AppBase): The application managing this picker instance.width (number): The width of the pick buffer in pixels.height (number): The height of the pick buffer in pixels.depth (boolean, optional, default false): Whether to enable depth picking. When enabled, depth
information is captured alongside mesh IDs using MRT. Defaults to false.height: number
width: number
destroy(): void
Frees resources associated with this picker.
getSelection(x: number, y: number, width?: number, height?: number): (GSplatComponent | MeshInstance)[]
Return the list of mesh instances selected by the specified rectangle in the previously prepared pick buffer. The rectangle using top-left coordinate system.
Note: This function is not supported on WebGPU. Use getSelectionAsync instead. Note: This function is blocks the main thread while reading pixels from GPU memory. It's recommended to use getSelectionAsync instead.
Parameters
x (number): The left edge of the rectangle.y (number): The top edge of the rectangle.width (number, optional, default 1): The width of the rectangle. Defaults to 1.height (number, optional, default 1): The height of the rectangle. Defaults to 1.Returns (GSplatComponent | MeshInstance)[]: An array of mesh instances or gsplat components
that are in the selection.
Example
// Get the selection at the point (10,20)
const selection = picker.getSelection(10, 20);
Example
// Get all models in rectangle with corners at (10,20) and (20,40)
const selection = picker.getSelection(10, 20, 10, 20);
getSelectionAsync(x: number, y: number, width?: number, height?: number): Promise<(GSplatComponent | MeshInstance)[]>
Return the list of mesh instances selected by the specified rectangle in the previously prepared pick buffer. The rectangle uses top-left coordinate system.
This method is asynchronous and does not block the execution.
Parameters
x (number): The left edge of the rectangle.y (number): The top edge of the rectangle.width (number, optional, default 1): The width of the rectangle. Defaults to 1.height (number, optional, default 1): The height of the rectangle. Defaults to 1.Returns Promise<(GSplatComponent | MeshInstance)[]>: - Promise that resolves with an
array of mesh instances or gsplat components that are in the selection.
Example
// Get the mesh instances at the rectangle with start at (10,20) and size of (5,5)
picker.getSelectionAsync(10, 20, 5, 5).then((meshInstances) => {
console.log(meshInstances);
});
getWorldPointAsync(x: number, y: number): Promise<Vec3 | null>
Return the world position of the mesh instance picked at the specified screen coordinates. The position is reconstructed at the center of the pixel containing the coordinates, which is where its depth was rasterized.
Parameters
x (number): The x coordinate of the pixel to pick.y (number): The y coordinate of the pixel to pick.Returns Promise<Vec3 | null>: Promise that resolves with the world position of the picked point,
or null if no depth is available or nothing was picked.
Example
// Get the world position at screen coordinates (100, 50)
picker.getWorldPointAsync(100, 50).then((worldPoint) => {
if (worldPoint) {
console.log('World position:', worldPoint);
// Use the world position
} else {
console.log('No object at this position');
}
});
prepare(camera: CameraComponent, scene: Scene, layers?: Layer[]): void
Primes the pick buffer with a rendering of the specified models from the point of view of the supplied camera. Once the pick buffer has been prepared, getSelection can be called multiple times on the same picker object. Therefore, if the models or camera do not change in any way, prepare does not need to be called again.
Parameters
camera (CameraComponent): The camera component used to render the scene.scene (Scene): The scene containing the pickable mesh instances.layers (Layer[], optional): Layers from which objects will be picked. If not supplied, all
layers of the specified camera will be used.resize(width: number, height: number): void
Sets the resolution of the pick buffer. The pick buffer resolution does not need to match the resolution of the corresponding frame buffer use for general rendering of the 3D scene. However, the lower the resolution of the pick buffer, the less accurate the selection results returned by getSelection. On the other hand, smaller pick buffers will yield greater performance, so there is a trade off.
Parameters
width (number): The width of the pick buffer in pixels.height (number): The height of the pick buffer in pixels.Class · extends Geometry · category: Graphics
A procedural plane-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new PlaneGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new PlaneGeometry(opts?: object)
Create a new PlaneGeometry instance.
By default, the constructor creates a plane centered on the object space origin with a width and length of 1 and 5 segments in either axis (50 triangles). The normal vector of the plane is aligned along the positive Y axis. The plane is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.halfExtents (Vec2, optional): The half dimensions of the plane in the X and Z axes.
Defaults to [0.5, 0.5].opts.lengthSegments (number, optional): The number of divisions along the Z axis of the plane.
Defaults to 5.opts.widthSegments (number, optional): The number of divisions along the X axis of the plane.
Defaults to 5.Example
const geometry = new PlaneGeometry({
halfExtents: new Vec2(1, 1),
widthSegments: 10,
lengthSegments: 10
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
Base class for all post effects. Post effects take a render target as input, apply effects to it, and then render the result to an output render target or the screen if no output is specified.
new PostEffect(graphicsDevice: GraphicsDevice)
Create a new PostEffect instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device of the application.device: GraphicsDevice
The graphics device of the application.
needsDepthBuffer: boolean
The property that should to be set to true (by the custom post effect) if a depth map
is necessary (default is false).
static quadVertexShader: string
A simple vertex shader used to render a quad, which requires 'vec2 aPosition' in the vertex buffer, and generates uv coordinates vUv0 for use in the fragment shader.
drawQuad(target: RenderTarget | null, shader: Shader, rect?: Vec4): void
Draw a screen-space rectangle in a render target, using a specified shader.
Parameters
target (RenderTarget | null): The output render target.shader (Shader): The shader to be used for drawing the rectangle.rect (Vec4, optional): The normalized screen-space position (rect.x, rect.y) and size (rect.z,
rect.w) of the rectangle. Default is [0, 0, 1, 1].render(inputTarget: RenderTarget, outputTarget: RenderTarget, rect?: Vec4): void
Render the post effect using the specified inputTarget to the specified outputTarget.
Parameters
inputTarget (RenderTarget): The input render target.outputTarget (RenderTarget): The output render target. If null then this will be the
screen.rect (Vec4, optional): The rect of the current camera. If not specified, it will default to
[0, 0, 1, 1].Class · category: Graphics
Used to manage multiple post effects for a camera. This is the legacy post-processing path. For
new work use CameraFrame, which implements bloom, SSAO, depth of field, TAA, volumetric
fog and tone mapping as one HDR pipeline; playcanvas/scripts/esm/camera-frame.mjs wraps it as
an attachable script.
new PostEffectQueue(app: AppBase, camera: CameraComponent)
Create a new PostEffectQueue instance.
Parameters
app (AppBase): The application.camera (CameraComponent): The camera component.addEffect(effect: PostEffect): void
Adds a post effect to the queue. If the queue is disabled adding a post effect will automatically enable the queue.
Parameters
effect (PostEffect): The post effect to add to the queue.destroy(): void
Removes all the effects from the queue and disables it.
disable(): void
Disables the queue and all of its effects.
enable(): void
Enables the queue and all of its effects. If there are no effects then the queue will not be enabled.
removeEffect(effect: PostEffect): void
Removes a post effect from the queue. If the queue becomes empty it will be disabled automatically.
Parameters
effect (PostEffect): The post effect to remove.Class · category: Graphics
An object that renders a quad using a Shader.
Note: QuadRender does not modify render states. Before calling render, you should set up the required states using GraphicsDevice#setDrawStates, or the individual setters (GraphicsDevice#setBlendState, GraphicsDevice#setCullMode, GraphicsDevice#setFrontFace, GraphicsDevice#setDepthState, GraphicsDevice#setStencilState). Otherwise previously set states will be used.
Example:
const shader = ShaderUtils.createShader(app.graphicsDevice, {
uniqueName: 'MyShader',
attributes: { aPosition: SEMANTIC_POSITION },
vertexGLSL: '// vertex shader code',
fragmentGLSL: '// fragment shader code'
});
const quad = new QuadRender(shader);
// Set up render states before rendering (defaults are suitable for full-screen quads)
app.graphicsDevice.setDrawStates();
quad.render();
quad.destroy();
new QuadRender(shader: Shader)
Create a new QuadRender instance.
Parameters
shader (Shader): The shader to be used to render the quad.destroy(): void
Destroys the resources associated with this instance.
render(viewport?: Vec4, scissor?: Vec4, numInstances?: number): void
Renders the quad. If the viewport is provided, the original viewport and scissor is restored after the rendering.
Parameters
viewport (Vec4, optional): The viewport rectangle of the quad, in pixels. The viewport is
not changed if not provided.scissor (Vec4, optional): The scissor rectangle of the quad, in pixels. Used only if the
viewport is provided.numInstances (number, optional): Number of instances to draw. When provided, renders
multiple quads using instanced drawing. Each instance can use the instance index
(gl_InstanceID in GLSL, pcInstanceIndex in WGSL) to fetch per-quad data from
a texture or buffer, allowing each quad to be parameterized independently.Class · extends Component · category: Graphics
The RenderComponent enables an Entity to render 3D meshes. The type property can
be set to one of several predefined shapes (such as box, sphere, cone and so on).
Alternatively, the component can be configured to manage an arbitrary array of
MeshInstances. These can either be created programmatically or loaded from an
Asset.
The MeshInstances managed by this component are positioned, rotated, and scaled in world space by the world transformation matrix of the owner Entity. This world matrix is derived by combining the entity's local transformation (position, rotation, and scale) with the world transformation matrix of its parent entity in the scene hierarchy.
You should never need to use the RenderComponent constructor directly. To add a RenderComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('render', {
type: 'box'
});
Once the RenderComponent is added to the entity, you can access it via the Entity#render property:
entity.render.type = 'capsule'; // Set the render component's type
console.log(entity.render.type); // Get the render component's type and print it
Relevant Engine API examples:
isStatic: boolean = false
Mark meshes as non-movable (optimization).
get asset(): number | null
set asset(value: number | null)
Gets the render asset id for the render component.
get batchGroupId(): number
set batchGroupId(value: number)
Gets the batch group for the mesh instances in this component (see BatchGroup).
get castShadows(): boolean
set castShadows(value: boolean)
Gets whether attached meshes will cast shadows for lights that have shadow casting enabled.
get castShadowsLightmap(): boolean
set castShadowsLightmap(value: boolean)
Gets whether meshes instances will cast shadows when rendering lightmaps.
get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)
Gets the custom object space bounding box that is used for visibility culling of attached mesh instances.
get layers(): readonly number[]
set layers(value: readonly number[])
Gets the array of layer IDs (Layer#id) to which the mesh instances belong.
get lightmapped(): boolean
set lightmapped(value: boolean)
Gets whether the component is affected by the runtime lightmapper.
get lightmapSizeMultiplier(): number
set lightmapSizeMultiplier(value: number)
Gets the lightmap resolution multiplier.
get material(): Material
set material(value: Material)
Gets the material Material that will be used to render the component.
get materialAssets(): number[] | Asset<string>[]
set materialAssets(value?: number[] | Asset<string>[])
Gets the material assets that will be used to render the component.
get meshInstances(): readonly MeshInstance[]
set meshInstances(value: readonly MeshInstance[])
Gets the array of meshInstances contained in the component. Use the setter to replace the array; do not mutate the returned array.
get receiveShadows(): boolean
set receiveShadows(value: boolean)
Gets whether shadows will be cast on attached meshes.
get renderStyle(): number
set renderStyle(renderStyle: number)
Gets the render style of this component's MeshInstances.
get rootBone(): Entity | null
set rootBone(value: Entity | null)
Gets the root bone entity for the render component.
get shadowCascadeMask(): number
set shadowCascadeMask(value: number)
Gets the bitmask that controls which shadow cascades the attached meshes contribute to.
get type(): "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus"
set type(value: "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus")
Gets the type of the component.
hide(): void
Stop rendering MeshInstances without removing them from the scene hierarchy. This method sets the MeshInstance#visible property of every MeshInstance to false. Note, this does not remove the mesh instances from the scene hierarchy or draw call list. So the render component still incurs some CPU overhead.
show(): void
Enable rendering of the component's MeshInstances if hidden using hide. This method sets the MeshInstance#visible property on all mesh instances to true.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Allows an Entity to render a mesh or a primitive shape like a box, capsule, sphere, cylinder, cone etc.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
A render target is a rectangular rendering surface that can be rendered into, instead of the screen. It wraps one or more color buffer Textures and an optional depth (and stencil) buffer. Once a camera or a render pass has rendered into it, the color texture holds the result and can be used anywhere a normal texture can - applied to a material to display it in the scene, or fed into further processing. This underpins effects such as in-world screens, mirrors and portals, reflections, picking and custom multi-pass pipelines.
Create a texture to render into, wrap it in a render target and assign it to a camera. The texture must use a renderable, uncompressed format:
const texture = new Texture(device, {
width: 512,
height: 512,
format: PIXELFORMAT_SRGBA8,
mipmaps: false,
minFilter: FILTER_LINEAR,
magFilter: FILTER_LINEAR
});
const renderTarget = new RenderTarget({
colorBuffer: texture,
depth: true,
origin: RENDERTARGET_ORIGIN_TOP
});
// the camera renders into the texture instead of the screen
cameraEntity.camera.renderTarget = renderTarget;
// and the texture can be used as any other, for example by a material
material.emissiveMap = texture;
When the result is sampled as a regular texture like this, specify the origin option as
RENDERTARGET_ORIGIN_TOP, which stores the image in the same orientation on all graphics
APIs. Multiple color buffers can be attached using the colorBuffers option, to render into
all of them simultaneously from a single pass (MRT).
A live example: https://playcanvas.github.io/#/graphics/render-to-texture
Set the samples option to a value greater than 1 to render with hardware anti-aliasing. The
render target internally allocates a multisampled buffer to render into, and automatically
resolves it into the single-sampled colorBuffer at the end of a render pass - the color
texture is used the same way as in the single-sampled case.
const renderTarget = new RenderTarget({ colorBuffer: texture, depth: true, samples: 4 });
A multisampled texture (a Texture created with samples greater than 1, WebGPU only)
can be used as the color buffer directly. The render target then renders into its samples, and
the sample count is inferred from the texture. Provide a resolveBuffer to get the standard
hardware resolve, or omit it to keep the individual samples: these are then read in a shader
using textureLoad on a texture_multisampled_2d, typically by a follow-up pass implementing
a custom resolve - an operation the hardware resolve cannot express, such as a tonemapped or
min/max resolve. This is also the only way to use multisampling with formats the hardware
cannot resolve, such as integer formats.
// a multisampled texture, rendered into directly
const msColor = new Texture(device, {
width: 512,
height: 512,
format: PIXELFORMAT_RGBA16F,
samples: 4
});
// renders into the samples of msColor, which are stored (no resolve buffer),
// to be read by a custom resolve pass using textureLoad
const renderTarget = new RenderTarget({ colorBuffer: msColor, depth: true });
A live example: https://playcanvas.github.io/#/graphics-advanced/custom-msaa-resolve
new RenderTarget(options?: object)
Creates a new RenderTarget instance. A color buffer or a depth buffer must be set.
Parameters
options (object, optional, default {}): Object for passing optional arguments.
options.autoResolve (boolean, optional): If samples > 1, enables or disables automatic MSAA
resolve after rendering to this RT (see resolve). Applies to the implicit
multisampled path only - resolves of explicit multisampled attachments (a multisampled
colorBuffer with a resolveBuffer, or a multisampled depthBuffer with a
depthResolveBuffer) are controlled by the per-pass resolve flags instead. Defaults to
true.
options.colorBuffer (Texture, optional): The texture that this render target will treat as a
rendering surface. This can be a multisampled texture (a texture created with samples > 1,
WebGPU only), in which case the render target renders directly into its samples, the sample
count is inferred from the texture, and an optional resolveBuffer receives the hardware
resolve.
options.colorBuffers (Texture[], optional): The textures that this render target will treat
as a rendering surfaces. If this option is set, the colorBuffer option is ignored. All
textures must have the same sample count.
options.depth (boolean, optional): If set to true, depth buffer will be created. Defaults to
true. Ignored if depthBuffer is defined.
options.depthBuffer (Texture, optional): The texture that this render target will treat as a
depth/stencil surface. If set, the 'depth' and 'stencil' properties are ignored. The texture
must use PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTH16 or
PIXELFORMAT_DEPTHSTENCIL format. On WebGPU this can be a multisampled texture (a
texture created with samples > 1), in which case the render target renders directly into
its depth samples, which can later be read in a shader using textureLoad on a
texture_depth_multisampled_2d, or resolved into an optional depthResolveBuffer.
options.depthResolveBuffer (Texture, optional): A single-sampled PIXELFORMAT_R32F
texture that the multisampled depth buffer is resolved into at the end of a render pass,
using a shader-based resolve controlled by RenderTarget#depthResolveMode (WebGPU
only - no hardware depth resolve exists). Only valid when depthBuffer is a multisampled
texture, and must match its dimensions.
options.depthResolveMode (string, optional): How the samples of the multisampled depth
buffer are resolved into a single depth value, whenever the depth of this render target is
resolved by a shader-based resolve (WebGPU only) - the depth grab pass (sceneDepthMap), a
depth copy, or the automatic resolve into a provided depthBuffer. Can be:
Defaults to DEPTHRESOLVE_MIN. Ignored on WebGL2, where the sample selection of the depth resolve is defined by the implementation. Can also be changed at any time using the RenderTarget#depthResolveMode property.
options.face (number, optional): If the colorBuffer parameter is a cubemap, use this option
to specify the face of the cubemap to render to. Can be:
Defaults to CUBEFACE_POSX.
options.mipLevel (number, optional): If set to a number greater than 0, the render target
will render to the specified mip level of the color buffer. Defaults to 0.
options.name (string, optional): The name of the render target.
options.origin (string, optional): Controls the vertical orientation of the image stored
in the render target. Choose based on how the texture is sampled. Can be:
Takes precedence over the deprecated flipY option. Defaults to
RENDERTARGET_ORIGIN_NATIVE.
options.resolveBuffer (Texture | null, optional): A single-sampled texture that the
multisampled color buffer is hardware-resolved into at the end of a render pass. Only valid
when colorBuffer is a multisampled texture, and must match its format and dimensions. When
not provided, the multisampled samples are stored instead, to be read in a shader using
textureLoad (a custom resolve). Note that integer formats and PIXELFORMAT_R32F
cannot be hardware-resolved.
options.resolveBuffers ((Texture | null)[], optional): Per-attachment resolve textures
matching colorBuffers by index; use null for attachments that should not be
hardware-resolved. If this option is set, the resolveBuffer option must not be used.
options.samples (number, optional): Number of hardware anti-aliasing samples. Default is 1.
options.stencil (boolean, optional): If set to true, depth buffer will include stencil.
Defaults to false. Ignored if depthBuffer is defined or depth is false.
options.transientColor (boolean, optional): If set to true, the multi-sampled (MSAA) color
attachment is allocated as a transient ("memoryless") attachment, allowing tile-based GPUs to
keep its contents in on-chip memory and avoid VRAM allocation. WebGPU only, and only effective
when samples > 1 - it has no effect on single-sampled color (which is always stored). Ignored
on devices without transient attachment support. The attachment must be cleared on load and
discarded on store, so it is incompatible with a scene color grab pass (sceneColorMap).
Defaults to false.
options.transientDepth (boolean, optional): If set to true, the (engine-allocated) depth
attachment is allocated as a transient ("memoryless") attachment (see transientColor).
Applies to both single- and multi-sampled depth. WebGPU only; ignored on devices without
transient attachment support, and ignored (with a warning) when an explicit depthBuffer is
provided. Incompatible with a scene depth grab pass (sceneDepthMap), a depth prepass, or any
depth resolve, as the depth cannot be sampled or copied out. Defaults to false.
Example
// Create a 512x512x24-bit render target with a depth buffer
const colorBuffer = new Texture(graphicsDevice, {
width: 512,
height: 512,
format: PIXELFORMAT_RGB8
});
const renderTarget = new RenderTarget({
colorBuffer: colorBuffer,
depth: true
});
// Set the render target on a camera component
camera.renderTarget = renderTarget;
// Destroy render target at a later stage. Note that the color buffer needs
// to be destroyed separately.
renderTarget.colorBuffer.destroy();
renderTarget.destroy();
camera.renderTarget = null;
autoResolve: boolean
name: string
The name of the render target.
get colorBuffer(): Texture
Color buffer set up on the render target.
get colorBufferCount(): number
The number of color buffers (attachments) set up on the render target.
get depth(): boolean
True if the render target contains the depth attachment.
get depthBuffer(): Texture
Depth buffer set up on the render target. Only available, if depthBuffer was set in constructor. Not available if depth property was used instead.
get depthResolveBuffer(): Texture | null
The single-sampled texture the multisampled depth buffer is resolved into at the end of a
render pass. See the depthResolveBuffer constructor option. Null when not provided.
get depthResolveMode(): string
set depthResolveMode(value: string)
Gets how the samples of the multisampled depth buffer are resolved into a single depth value.
get face(): number
If the render target is bound to a cubemap, this property specifies which face of the cubemap is rendered to. Can be:
get height(): number
Height of the render target in pixels.
get mipLevel(): number
Mip level of the render target.
get mipmaps(): boolean
True if the mipmaps are automatically generated for the color buffer(s) if it contains a mip chain.
get origin(): string
Gets the vertical orientation of the image stored in this render target, as resolved at
construction from the origin option, or derived from the deprecated flipY option or
property. Can be RENDERTARGET_ORIGIN_TOP, RENDERTARGET_ORIGIN_BOTTOM or
RENDERTARGET_ORIGIN_NATIVE. See the origin option of the constructor for
details.
get resolveBuffer(): Texture | null
The resolve texture of the first color attachment, when the render target uses explicit
multisampled color buffers and a resolve buffer was provided. See the resolveBuffer
constructor option. Null otherwise.
get samples(): number
Number of antialiasing samples the render target uses.
get stencil(): boolean
True if the render target contains the stencil attachment.
get transientColor(): boolean
True if the multi-sampled color attachment is allocated as a transient ("memoryless")
attachment (WebGPU only). See the transientColor constructor option.
get transientDepth(): boolean
True if the depth attachment is allocated as a transient ("memoryless") attachment (WebGPU
only). See the transientDepth constructor option.
get width(): number
Width of the render target in pixels.
copy(source: RenderTarget, color?: boolean, depth?: boolean): boolean
Copies color and/or depth contents of source render target to this one. Formats, sizes and anti-aliasing samples must match.
A depth copy is supported in these cases:
depthBuffer of this render
target with an equal sample count and matching format - a full depth snapshot, including
the individual samples.Parameters
source (RenderTarget): Source render target to copy from.color (boolean, optional): If true, will copy the color buffer. Defaults to false.depth (boolean, optional): If true, will copy the depth buffer. Defaults to false.Returns boolean: True if the copy was successful, false otherwise.
destroy(): void
Frees resources associated with this render target.
getColorBuffer(index: number): Texture
Accessor for multiple render target color buffers.
Parameters
index (number): Index of the color buffer to get.Returns Texture: - Color buffer at the specified index.
getResolveBuffer(index?: number): Texture | null
Accessor for the per-attachment resolve textures. See the resolveBuffers constructor
option.
Parameters
index (number, optional, default 0): Index of the color attachment. Defaults to 0.Returns Texture | null: - The resolve texture at the specified index, or null when the
attachment has none.
resize(width: number, height: number): void
Resizes the render target to the specified width and height. Internally this resizes all the assigned texture color and depth buffers.
Parameters
width (number): The width of the render target in pixels.height (number): The height of the render target in pixels.resolve(color?: boolean, depth?: boolean): void
If samples > 1, resolves the anti-aliased render target (WebGL2 only). When you're rendering to an anti-aliased render target, pixels aren't written directly to the readable texture. Instead, they're first written to an MSAA buffer, where each sample for each pixel is stored independently. In order to read the results, you first need to 'resolve' the buffer - to average all samples and create a simple texture with one color per pixel. This function performs this averaging and updates the colorBuffer and the depthBuffer. If autoResolve is set to true, the resolve will happen after every rendering to this render target, otherwise you can do it manually, during the app update or similar.
Parameters
color (boolean, optional, default true): Resolve color buffer. Defaults to true.depth (boolean, optional): Resolve depth buffer. Defaults to true if the render target has a
depth buffer.Class · extends EventHandler · category: Graphics
Represents a single view of the scene - a region of the render target rendered from a single viewpoint. A standard camera produces one view, while in XR each eye (or screen) is a separate view. This is the base class for XrView.
get viewport(): Vec4
A Vec4 (x, y, width, height) that represents the view's viewport. For a monoscopic screen it defines the fullscreen view; for stereoscopic views (left/right eye) it defines the part of the screen the view occupies.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Graphics
A scene is a graphical representation of an environment. It manages the scene hierarchy, all graphical objects, lights, and scene-wide properties.
Each application has one at AppBase#scene. The scene owns the rendering setup that is not tied to a single entity: the layers composition that decides render order; the lighting environment through ambientLight, skybox, envAtlas and the sky and lighting parameter objects; exposure, or physicalUnits in its place, for overall brightness; the lightmapping settings; and the fog described below.
The scene fires prerender and postrender for each camera that renders it, and precull
and postcull around visibility culling. Per-frame work that needs to know the camera belongs
in those handlers.
Fog is scene-wide: fog is a read-only FogParams whose type, color, start
and end you set, and CameraComponent#fog can override it for a single camera.
Example
// Light the scene from a prefiltered environment and brighten it slightly
app.scene.envAtlas = envAtlasAsset.resource;
app.scene.skybox = skyboxAsset.resource;
app.scene.exposure = 1.2;
Example
// Run code for each camera just before it renders the scene
app.scene.on('prerender', (camera) => {
// camera is the CameraComponent about to render
});
ambientBake: boolean = false
If enabled, the ambient lighting will be baked into lightmaps. This will be either the skybox if set up, otherwise ambientLight. Defaults to false.
ambientBakeOcclusionBrightness: number = 0
If ambientBake is true, this specifies the brightness of ambient occlusion. Typical range is -1 to 1. Defaults to 0, representing no change to brightness.
ambientBakeOcclusionContrast: number = 0
If ambientBake is true, this specifies the contrast of ambient occlusion. Typical range is -1 to 1. Defaults to 0, representing no change to contrast.
ambientLight: Color
The color of the scene's ambient light, specified in sRGB color space. Defaults to black (0, 0, 0).
ambientLuminance: number = 0
The luminosity of the scene's ambient light in lux (lm/m^2). Used if physicalUnits is true. Defaults to 0.
exposure: number = 1
The exposure value tweaks the overall brightness of the scene. Ignored if physicalUnits is true. Defaults to 1.
lightmapFilterEnabled: boolean = false
Enables bilateral filter on runtime baked color lightmaps, which removes the noise and banding while preserving the edges. Defaults to false. Note that the filtering takes place in the image space of the lightmap, and it does not filter across lightmap UV space seams, often making the seams more visible. It's important to balance the strength of the filter with number of samples used for lightmap baking to limit the visible artifacts.
lightmapHDR: boolean = false
Enables HDR lightmaps. This can result in smoother lightmaps especially when many samples are used. Defaults to false.
lightmapMaxResolution: number = 2048
The maximum lightmap resolution. Defaults to 2048.
lightmapMode: number = BAKE_COLORDIR
The lightmap baking mode. Can be:
Defaults to BAKE_COLORDIR.
lightmapSizeMultiplier: number = 1
The lightmap resolution multiplier. Defaults to 1.
physicalUnits: boolean = false
Use physically based units for cameras and lights. When used, the exposure value is ignored.
root: Entity = null
The root entity of the scene, which is usually the only child to the Application root entity.
get ambientBakeNumSamples(): number
set ambientBakeNumSamples(value: number)
Gets the number of samples used to bake the ambient light into the lightmap.
get ambientBakeSpherePart(): number
set ambientBakeSpherePart(value: number)
Gets the part of the sphere which represents the source of ambient light.
get clusteredLightingEnabled(): boolean
set clusteredLightingEnabled(value: boolean)
Gets whether clustered lighting is enabled.
get envAtlas(): Texture | null
set envAtlas(value: Texture | null)
Gets the environment lighting atlas.
get fog(): FogParams
Gets the FogParams that define fog parameters.
get gsplat(): GSplatParams
Gets the GSplat parameters.
get layers(): LayerComposition
set layers(layers: LayerComposition)
Gets the LayerComposition that defines rendering order of this scene.
get lighting(): LightingParams
Gets the LightingParams that define lighting parameters.
get lightmapFilterRange(): number
set lightmapFilterRange(value: number)
Gets the range parameter of the bilateral filter.
get lightmapFilterSmoothness(): number
set lightmapFilterSmoothness(value: number)
Gets the spatial parameter of the bilateral filter.
get lightmapPixelFormat(): number
Gets the lightmap pixel format.
get prefilteredCubemaps(): Texture[]
set prefilteredCubemaps(value: Texture[])
Gets the 6 prefiltered cubemaps acting as the source of image-based lighting.
get sky(): Sky
Gets the Sky that defines sky properties.
get skybox(): Texture | null
set skybox(value: Texture | null)
Gets the base cubemap texture used as the scene's skybox when skyboxMip is 0.
get skyboxHighlightMultiplier(): number
set skyboxHighlightMultiplier(value: number)
Gets the highlight multiplied for the skybox.
get skyboxIntensity(): number
set skyboxIntensity(value: number)
Gets the multiplier for skybox intensity.
get skyboxLuminance(): number
set skyboxLuminance(value: number)
Gets the luminance (in lm/m^2) of the skybox.
get skyboxMip(): number
set skyboxMip(value: number)
Gets the mip level of the skybox to be displayed.
get skyboxRotation(): Readonly<Quat>
set skyboxRotation(value: Readonly<Quat>)
Gets the rotation of the skybox to be displayed. Use the setter to update skybox state.
setSkybox(cubemaps?: Texture[]): void
Sets the cubemap for the scene skybox.
Parameters
cubemaps (Texture[], optional): An array of cubemaps corresponding to the skybox at
different mip levels. If undefined, scene will remove skybox. Cubemap array should be of
size 7, with the first element (index 0) corresponding to the base cubemap (mip level 0)
with original resolution. Each remaining element (index 1-6) corresponds to a fixed
prefiltered resolution (128x128, 64x64, 32x32, 16x16, 8x8, 4x4).static EVENT_POSTCULL: string = 'postcull'
Fired after mesh instance visibility culling is performed for a camera; mesh instance visibility (such as MeshInstance#visibleThisFrame) is up to date when this fires. The handler is passed the CameraComponent that was culled, or null when the culling is internal (for example when culling shadow casters for a light's shadow map).
Example
app.scene.on('postcull', (camera) => {
if (camera) {
console.log(`Visibility culling was performed for camera ${camera.entity.name}`);
}
});
static EVENT_POSTRENDER: string = 'postrender'
Fired when the camera renders the scene. The handler is passed the CameraComponent that rendered the scene.
Example
app.scene.on('postrender', (camera) => {
console.log(`Camera ${camera.entity.name} rendered the scene`);
});
static EVENT_POSTRENDER_LAYER: string = 'postrender:layer'
Fired when the camera renders a layer. The handler is passed the CameraComponent, the Layer that will be rendered, and a boolean parameter set to true if the layer is transparent. This is called during rendering to a render target or a default framebuffer, and additional rendering can be performed here, for example using QuadRender#render.
Example
app.scene.on('postrender:layer', (camera, layer, transparent) => {
console.log(`Camera ${camera.entity.name} rendered the layer ${layer.name} (transparent: ${transparent})`);
});
static EVENT_PRECULL: string = 'precull'
Fired before mesh instance visibility culling is performed for a camera, just before the camera's culling frustum is refreshed (so a handler may still adjust the camera). The handler is passed the CameraComponent being culled, or null when the culling is internal (for example when culling shadow casters for a light's shadow map). Note that light visibility culling happens earlier in the frame and is not bracketed by this event.
Example
app.scene.on('precull', (camera) => {
if (camera) {
console.log(`Visibility culling will be performed for camera ${camera.entity.name}`);
}
});
static EVENT_PRERENDER: string = 'prerender'
Fired before the camera renders the scene. The handler is passed the CameraComponent that will render the scene.
Example
app.scene.on('prerender', (camera) => {
console.log(`Camera ${camera.entity.name} will render the scene`);
});
static EVENT_PRERENDER_LAYER: string = 'prerender:layer'
Fired before the camera renders a layer. The handler is passed the CameraComponent, the Layer that will be rendered, and a boolean parameter set to true if the layer is transparent. This is called during rendering to a render target or a default framebuffer, and additional rendering can be performed here, for example using QuadRender#render.
Example
app.scene.on('prerender:layer', (camera, layer, transparent) => {
console.log(`Camera ${camera.entity.name} will render the layer ${layer.name} (transparent: ${transparent})`);
});
static EVENT_SETLAYERS: string = 'set:layers'
Fired when the layer composition is set. Use this event to add callbacks or advanced properties to your layers. The handler is passed the old and the new LayerComposition.
Example
app.scene.on('set:layers', (oldComp, newComp) => {
const list = newComp.layerList;
for (let i = 0; i < list.length; i++) {
const layer = list[i];
switch (layer.name) {
case 'MyLayer':
layer.onEnable = myOnEnableFunction;
layer.onDisable = myOnDisableFunction;
break;
case 'MyOtherLayer':
layer.clearColorBuffer = true;
break;
}
}
});
static EVENT_SETSKYBOX: string = 'set:skybox'
Fired when the skybox is set. The handler is passed the Texture that is the previously used skybox cubemap texture. The new skybox cubemap texture is in the skybox property.
Example
app.scene.on('set:skybox', (oldSkybox) => {
console.log(`Skybox changed from ${oldSkybox.name} to ${app.scene.skybox.name}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
Reads the scene depth of a camera back to the CPU.
A sample is the distance from the camera to the surface at that point, in world units, measured along the camera's view direction.
Reads are asynchronous and land a frame or two later. Any number of them may be in flight at once, so a read can be issued every frame without waiting for the previous one to finish.
Note that something has to be rendering the depth for there to be anything to read: an effect which consumes it, or CameraComponent#requestSceneDepthMap.
const reader = new SceneDepthReader(camera.camera);
const rect = new Vec4(0.45, 0.45, 0.1, 0.1);
app.on('update', () => {
reader.read(rect, 8, 8)?.then((samples) => {
const hit = samples.filter(Number.isFinite);
console.log(hit.length ? Math.min(...hit) : 'nothing in view');
});
});
new SceneDepthReader(camera: CameraComponent)
Parameters
camera (CameraComponent): The camera whose depth is read.destroy(): void
Frees the resources the reader owns and stops reading for this camera. Reads which have not been rendered yet report their region as empty, and one already in flight does the same once it completes, rather than writing samples read through resources this has let go of.
read(rect: Vec4, width: number, height: number, target?: Float32Array<ArrayBufferLike>): Promise<Float32Array<ArrayBufferLike>> | null
Requests the depth of a region of the view, as width * height samples in row major order. The
region is point sampled rather than averaged - one sample per cell, taken at its centre - so
asking for more samples than the region resolves to repeats them.
Samples where nothing was rendered read as Infinity, as do the few which land within a hair of
the far clip, that being the depth an empty pixel reports.
Note that on a device which stores the scene depth at a lower precision - see
GSplatParams#sceneDepthWrite - a far clip beyond about 16384 leaves an empty pixel
reporting a large distance rather than Infinity, as the two stop being far enough apart to
tell one from the other.
Parameters
rect (Vec4): The region of the view to sample, normalized, with its origin in the bottom
left as CameraComponent#rect.width (number): The number of samples across the region. Not pixels.height (number): The number of samples down the region.target (Float32Array<ArrayBufferLike>, optional): An array to fill, at least width * height long. One is
allocated when not given. It is filled when the returned promise resolves, so an array must not
be shared between reads which overlap in time.Returns Promise<Float32Array<ArrayBufferLike>> | null: The samples, in world units, or null when the camera is
disabled or is not rendering a scene depth, leaving nothing to read.
Class · category: Graphics
Container for storing and loading of scenes. An instance of the registry is created on the AppBase object as AppBase#scenes.
new SceneRegistry(app: AppBase)
Create a new SceneRegistry instance.
Parameters
app (AppBase): The application.add(name: string, url: string): boolean
Add a new item to the scene registry.
Parameters
name (string): The name of the scene.url (string): The url of the scene file.Returns boolean: Returns true if the scene was successfully added to the registry, false otherwise.
changeScene(sceneItem: string | SceneRegistryItem, callback?: ChangeSceneCallback): void
Change to a new scene. Calling this function will load the scene data, delete all
entities and graph nodes under app.root and load the scene settings and hierarchy.
Parameters
sceneItem (string | SceneRegistryItem): The scene item (which can be found with
find, URL of the scene file (e.g."scene_id.json") or name of the scene.callback (ChangeSceneCallback, optional): The function to call after loading,
passed (err, entity) where err is null if no errors occurred.Example
app.scenes.changeScene("Scene Name", (err, entity) => {
if (!err) {
// success
} else {
// error
}
});
find(name: string): SceneRegistryItem | null
Find a Scene by name and return the SceneRegistryItem.
Parameters
name (string): The name of the scene.Returns SceneRegistryItem | null: The stored data about a scene or null if no scene with
that name exists.
findByUrl(url: string): SceneRegistryItem | null
Find a scene by the URL and return the SceneRegistryItem.
Parameters
url (string): The URL to search by.Returns SceneRegistryItem | null: The stored data about a scene or null if no scene with
that URL exists.
list(): SceneRegistryItem[]
Return the list of scene.
Returns SceneRegistryItem[]: All items in the registry.
loadScene(url: string, callback: LoadSceneCallback): void
Load the scene hierarchy and scene settings. This is an internal method used by the AppBase.
Parameters
url (string): The URL of the scene file.callback (LoadSceneCallback): The function called after the settings are
applied. Passed (err, scene) where err is null if no error occurred and scene is the
Scene.loadSceneData(sceneItem: string | SceneRegistryItem, callback: LoadSceneDataCallback): void
Loads and stores the scene data to reduce the number of the network requests when the same scenes are loaded multiple times. Can also be used to load data before calling loadSceneHierarchy and loadSceneSettings to make scene loading quicker for the user.
Parameters
sceneItem (string | SceneRegistryItem): The scene item (which can be found with
find, URL of the scene file (e.g."scene_id.json") or name of the scene.callback (LoadSceneDataCallback): The function to call after loading,
passed (err, sceneItem) where err is null if no errors occurred.Example
const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneData(sceneItem, (err, sceneItem) => {
if (err) {
// error
}
});
loadSceneHierarchy(sceneItem: string | SceneRegistryItem, callback: LoadHierarchyCallback): void
Load a scene file, create and initialize the Entity hierarchy and add the hierarchy to the application root Entity.
Parameters
sceneItem (string | SceneRegistryItem): The scene item (which can be found with
find, URL of the scene file (e.g."scene_id.json") or name of the scene.callback (LoadHierarchyCallback): The function to call after loading,
passed (err, entity) where err is null if no errors occurred.Example
const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneHierarchy(sceneItem, (err, entity) => {
if (!err) {
const e = app.root.find("My New Entity");
} else {
// error
}
});
loadSceneSettings(sceneItem: string | SceneRegistryItem, callback: LoadSettingsCallback): void
Load a scene file and apply the scene settings to the current scene.
Parameters
sceneItem (string | SceneRegistryItem): The scene item (which can be found with
find, URL of the scene file (e.g."scene_id.json") or name of the scene.callback (LoadSettingsCallback): The function called after the settings
are applied. Passed (err) where err is null if no error occurred.Example
const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneSettings(sceneItem, (err) => {
if (!err) {
// success
} else {
// error
}
});
remove(name: string): void
Remove an item from the scene registry.
Parameters
name (string): The name of the scene.unloadSceneData(sceneItem: string | SceneRegistryItem): void
Unloads scene data that has been loaded previously using loadSceneData.
Parameters
sceneItem (string | SceneRegistryItem): The scene item (which can be found with
find or URL of the scene file. Usually this will be "scene_id.json".Example
const sceneItem = app.scenes.find("Scene Name");
app.scenes.unloadSceneData(sceneItem);
Class · category: Graphics
Item to be stored in the SceneRegistry.
new SceneRegistryItem(name: string, url: string)
Creates a new SceneRegistryItem instance.
Parameters
name (string): The name of the scene.url (string): The url of the scene file.name: string
The name of the scene.
url: string
The url of the scene file.
get loaded(): boolean
Returns true if the scene data has loaded.
get loading(): boolean
Returns true if the scene data is still being loaded.
Class · category: Graphics
The scope for a variable.
new ScopeId(name: string)
Create a new ScopeId instance.
Parameters
name (string): The variable name.name: string
The variable name.
getValue(): any
Get variable value.
Returns any: The value.
setValue(value: any): void
Set variable value.
Parameters
value (any): The value.Class · category: Graphics
The scope for variables.
new ScopeSpace(name: string)
Create a new ScopeSpace instance.
Parameters
name (string): The scope name.name: string
The scope name.
resolve(name: string): ScopeId
Get (or create, if it doesn't already exist) a variable in the scope.
Parameters
name (string): The variable name.Returns ScopeId: The variable instance.
Class · category: Graphics
A shader is a program that is responsible for rendering graphical primitives on a device's graphics processor. The shader is generated from a shader definition. This shader definition specifies the code for processing vertices and fragments processed by the GPU. The language of the code is GLSL (or more specifically ESSL, the OpenGL ES Shading Language). The shader definition also describes how the PlayCanvas engine should map vertex buffer elements onto the attributes specified in the vertex shader code.
new Shader(graphicsDevice: GraphicsDevice, definition: object)
Creates a new Shader instance.
Consider ShaderUtils.createShader as a simpler and more powerful way to create a shader.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this shader.definition (object): The shader definition from which to build the shader.
definition.attributes ({}, optional): Object detailing the mapping of
vertex shader attribute names to semantics SEMANTIC_*. This enables the engine to match
vertex buffer data as inputs to the shader. When not specified, rendering without vertex
buffer is assumed.definition.cdefines (Map<string, string>, optional): A map containing key-value pairs of
define names and their values. These are used for resolving defines in the compute shader.definition.cincludes (Map<string, string>, optional): A map containing key-value pairs
of include names and their content. These are used for resolving #include directives in the
compute shader source.definition.computeBindGroupFormat (BindGroupFormat, optional): The bind group format for
caller-provided compute resources in group 0. Only used on WebGPU.definition.computeEntryPoint (string, optional): The entry point function name for the compute
shader. Defaults to 'main'.definition.computeUniformBufferFormats ({}, optional): The
uniform buffer formats keyed by bind group entry name. Requires computeBindGroupFormat.definition.cshader (string, optional): Compute shader source (WGSL code). Only supported on
WebGPU platform.definition.feedbackVaryings (string[], optional): A list of shader output variable
names that will be captured when using transform feedback. This setting is only effective
if the useTransformFeedback property is enabled.definition.feedbackVaryingsMode (number, optional): Specifies how transform feedback varyings
are written into GPU buffers. Use TRANSFORM_FEEDBACK_INTERLEAVED to pack all captured
varyings into a single buffer, or TRANSFORM_FEEDBACK_SEPARATE to store each varying
in its own buffer. This setting is only effective when useTransformFeedback property is enabled.
Defaults to TRANSFORM_FEEDBACK_INTERLEAVED.definition.fincludes (Map<string, string>, optional): A map containing key-value pairs
of include names and their content. These are used for resolving #include directives in the
fragment shader source.definition.fragmentOutputTypes (string | string[], optional): Fragment shader output types,
which default to vec4. Passing a string will set the output type for all color attachments.
Passing an array will set the output type for each color attachment.definition.fshader (string, optional): Fragment shader source (GLSL code). Optional when
useTransformFeedback or compute shader is specified.definition.name (string, optional): The name of the shader.definition.shaderLanguage (string, optional): Specifies the shader language of vertex and
fragment shaders. Defaults to SHADERLANGUAGE_GLSL.definition.useDualSourceBlending (boolean, optional): Whether the fragment shader outputs a
secondary color for dual-source blending. Defaults to false.definition.useTransformFeedback (boolean, optional): Specifies that this shader outputs
post-VS data to a buffer.definition.vincludes (Map<string, string>, optional): A map containing key-value pairs of
include names and their content. These are used for resolving #include directives in the
vertex shader source.definition.vshader (string, optional): Vertex shader source (GLSL code). Optional when
compute shader is specified.Example
// Create a shader that renders primitives with a solid red color
// Vertex shader
const vshader = `
attribute vec3 aPosition;
void main(void) {
gl_Position = vec4(aPosition, 1.0);
}
`;
// Fragment shader
const fshader = `
precision ${graphicsDevice.precision} float;
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;
const shaderDefinition = {
attributes: {
aPosition: SEMANTIC_POSITION
},
vshader,
fshader
};
const shader = new Shader(graphicsDevice, shaderDefinition);
destroy(): void
Frees resources associated with this shader.
Class · extends Map · category: Graphics
A collection of shader chunks, used by ShaderChunks. This is a map of shader chunk names
to their code. As this class extends Map, it can be used as a Map as well in addition to
custom functionality it provides.
add(object: any, override?: boolean): ShaderChunkMap
Adds multiple shader chunks to the Map. This method accepts an object where the keys are the names of the shader chunks and the values are the shader source code. If an element with the same name already exists, the element will be updated.
Parameters
object (any): Object containing shader chunks.override (boolean, optional, default true): Whether to override existing shader chunks. Defaults to true.Returns ShaderChunkMap: The ShaderChunkMap instance.
clear(): void
Removes all shader chunks from the Map.
delete(name: string): boolean
Removes a shader chunk by name from the Map. If the element does not exist, no action is taken.
Parameters
name (string): The name of the shader chunk to remove.Returns boolean: True if an element in the Map existed and has been removed, or false if the
element does not exist.
set(name: string, code: string): ShaderChunkMap
Adds a new shader chunk with a specified name and shader source code to the Map. If an element with the same name already exists, the element will be updated.
Parameters
name (string): The name of the shader chunk.code (string): The shader source code.Returns ShaderChunkMap: The ShaderChunkMap instance.
Class · category: Graphics
A collection of GLSL and WGSL shader chunks, used to generate shaders.
version: string = ''
Specifies the API version of the shader chunks.
This should be a string containing the current engine major and minor version (e.g., '2.8' for engine v2.8.1) and ensures compatibility with the current engine version. When providing custom shader chunks, set this to the latest supported version. If a future engine release no longer supports the specified version, a warning will be issued. In that case, update your shader chunks to match the new format and set this to the latest version accordingly.
static get(device: GraphicsDevice, shaderLanguage?: string): ShaderChunkMap
Returns a shader chunks map for the given device and shader language.
Parameters
device (GraphicsDevice): The graphics device.shaderLanguage (string, optional, default SHADERLANGUAGE_GLSL): The shader language to use (GLSL or WGSL).Returns ShaderChunkMap: The shader chunks for the specified language.
Class · extends Material · category: Graphics
A ShaderMaterial is a type of material that utilizes a specified shader for rendering purposes.
Use it when a surface cannot be expressed with StandardMaterial properties or shader
chunk overrides. The shader is described by a ShaderDesc: a uniqueName, vertex and
fragment source in GLSL for WebGL, in WGSL for WebGPU, or both, and an attributes map from
shader inputs to SEMANTIC_* values so the engine can bind vertex data. Provide both languages
when the application must run on both backends. The engine supplies the standard uniforms a
shader declares by name, such as matrix_viewProjection; your own uniforms are set with
Material#setParameter. Render state such as Material#blendType,
Material#cull and Material#depthWrite comes from Material. Lighting, fog
and shadows are not generated for you; the shader draws exactly what it is written to draw.
A simple example which creates a material with custom vertex and fragment shaders specified in GLSL format:
const material = new ShaderMaterial({
uniqueName: 'MyShader',
attributes: { aPosition: SEMANTIC_POSITION },
vertexGLSL: `
attribute vec3 aPosition;
uniform mat4 matrix_viewProjection;
void main(void)
{
gl_Position = matrix_viewProjection * pos;
}`,
fragmentGLSL: `
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}`
});
new ShaderMaterial(shaderDesc?: ShaderDesc)
Create a new ShaderMaterial instance.
Parameters
shaderDesc (ShaderDesc, optional): The description of the shader to be used by the material.get shaderDesc(): ShaderDesc | undefined
set shaderDesc(value: ShaderDesc | undefined)
Gets the shader description.
copy(source: ShaderMaterial): ShaderMaterial
Copy a ShaderMaterial.
Parameters
source (ShaderMaterial): The material to copy from.Returns ShaderMaterial: The destination material.
alphaToCoverage: boolean = falsecull: number = CULLFACE_BACKfrontFace: number = FRONTFACE_CCWname: string = 'Untitled'stencilBack: StencilParameters | null = nullstencilFront: StencilParameters | null = nulluserId: string = ''get alphaTest(): number · set alphaTest(value: number)get alphaWrite(): boolean · set alphaWrite(value: boolean)get blendState(): Readonly<BlendState> · set blendState(value: Readonly<BlendState>)get blendType(): number · set blendType(type: number)get blueWrite(): boolean · set blueWrite(value: boolean)get depthBias(): number · set depthBias(value: number)get depthFunc(): number · set depthFunc(value: number)get depthState(): DepthState · set depthState(value: DepthState)get depthTest(): boolean · set depthTest(value: boolean)get depthWrite(): boolean · set depthWrite(value: boolean)get flatShading(): boolean · set flatShading(value: boolean)get greenWrite(): boolean · set greenWrite(value: boolean)get redWrite(): boolean · set redWrite(value: boolean)get shaderChunksVersion(): string · set shaderChunksVersion(value: string)get slopeDepthBias(): number · set slopeDepthBias(value: number)protected _markLayoutDirty(): voidprotected _markPropertyModified(property: MaterialProperty): voidprotected _markPropertyMutable(property: MaterialProperty, value: any): voidclone(): ShaderMaterialdeleteParameter(name: string): voiddestroy(): voidgetDefine(name: string): booleangetParameter(name: string): anygetShaderChunks(shaderLanguage?: string): ShaderChunkMapsetDefine(name: string, value: string | boolean | undefined): voidsetParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): voidupdate(): voidClass · category: Graphics
Utility class for creating shaders. Provides a higher-level API over the Shader constructor, handling cross-API concerns such as GLSL/WGSL selection and translation, shader caching, include and define resolution, and attaching commonly used extensions and precision qualifiers.
static createShader(device: GraphicsDevice, options: object): Shader
Creates a shader. When the active graphics device is WebGL, the provided GLSL vertex and
fragment source code is used. For WebGPU, if WGSL vertex and fragment source code is
supplied, it is used directly; otherwise, the system automatically translates the provided
GLSL code into WGSL. In the case of GLSL shaders, additional blocks are appended to both the
vertex and fragment source code to support extended features and maintain compatibility.
These additions include the shader version declaration, precision qualifiers, and commonly
used extensions, and therefore should be excluded from the user-supplied GLSL source.
Note: The shader has access to all registered shader chunks via the #include directive.
Any provided includes will be applied as overrides on top of those.
Parameters
device (GraphicsDevice): The graphics device.options (object): Object for passing optional arguments.
options.attributes ({}): Object detailing the mapping of vertex
shader attribute names to semantics SEMANTIC_*. This enables the engine to match vertex
buffer data to the shader attributes.options.fragmentChunk (string, optional): The name of the fragment shader chunk to use.options.fragmentDefines (Map<string, string>, optional): A map containing key-value pairs of
define names and their values. These are used for resolving #ifdef style of directives in the
fragment code.options.fragmentGLSL (string, optional): The fragment shader code in GLSL. Ignored if
fragmentChunk is provided.options.fragmentIncludes (Map<string, string>, optional): A map containing key-value pairs
of include names and their content. These are used for resolving #include directives in the
fragment shader source.options.fragmentOutputTypes (string | string[], optional): Fragment shader output types,
which default to vec4. Passing a string will set the output type for all color attachments.
Passing an array will set the output type for each color attachment.options.fragmentWGSL (string, optional): The fragment shader code in WGSL. Ignored if
fragmentChunk is provided.options.uniqueName (string): Unique name for the shader. If a shader with this name
already exists, it will be returned instead of a new shader instance.options.useDualSourceBlending (boolean, optional): Whether the fragment shader outputs a
secondary color for dual-source blending. Defaults to false.options.useTransformFeedback (boolean, optional): Whether to use transform feedback. Defaults
to false. Only supported by WebGL.options.vertexChunk (string, optional): The name of the vertex shader chunk to use.options.vertexDefines (Map<string, string>, optional): A map containing key-value pairs of
define names and their values. These are used for resolving #ifdef style of directives in the
vertex code.options.vertexGLSL (string, optional): The vertex shader code in GLSL. Ignored if vertexChunk
is provided.options.vertexIncludes (Map<string, string>, optional): A map containing key-value pairs of
include names and their content. These are used for resolving #include directives in the
vertex shader source.options.vertexWGSL (string, optional): The vertex shader code in WGSL. Ignored if vertexChunk
is provided.Returns Shader: The newly created shader.
Class · category: Graphics
A skin contains data about the bones in a hierarchy that drive a skinned mesh animation. Specifically, the skin stores the bone name and inverse bind matrix and for each bone. Inverse bind matrices are instrumental in the mathematics of vertex skinning.
new Skin(graphicsDevice: GraphicsDevice, ibp: Mat4[], boneNames: string[])
Create a new Skin instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this skin.ibp (Mat4[]): The array of inverse bind matrices.boneNames (string[]): The array of bone names for the bones referenced by this skin.Class · category: Graphics
A skin instance is responsible for generating the matrix palette that is used to skin vertices from object space to world space.
new SkinInstance(skin: Skin)
Create a new SkinInstance instance.
Parameters
skin (Skin): The skin that will provide the inverse bind pose
matrices to generate the final matrix palette.bones: GraphNode[]
An array of nodes representing each bone in this skin instance.
initSkin(skin: Skin): void
Parameters
skin (Skin): The skin.Class · category: Graphics
Implementation of the sky.
readonly node: GraphNode
A graph node with a transform used to render the sky mesh. Adjust the position, rotation and scale of this node to orient the sky mesh. Ignored for SKYTYPE_INFINITE.
get center(): Vec3
set center(value: Vec3)
Gets the center of the sky.
get depthWrite(): boolean
set depthWrite(value: boolean)
Gets whether depth writing is enabled for the sky.
get fisheye(): number
set fisheye(value: number)
Gets the fisheye projection strength for the sky.
get type(): string
set type(value: string)
Gets the type of the sky.
Class · extends Geometry · category: Graphics
A procedural sphere-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new SphereGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new SphereGeometry(opts?: object)
Create a new SphereGeometry instance.
By default, the constructor creates a sphere centered on the object space origin with a radius of 0.5 and 16 segments in both longitude and latitude. The sphere is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.latitudeBands (number, optional): The number of divisions along the latitudinal axis of
the sphere. Defaults to 16.opts.longitudeBands (number, optional): The number of divisions along the longitudinal axis of
the sphere. Defaults to 16.opts.radius (number, optional): The radius of the sphere. Defaults to 0.5.Example
const geometry = new SphereGeometry({
radius: 1,
latitudeBands: 32,
longitudeBands: 32
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · extends EventHandler · category: Graphics
A Sprite contains references to one or more frames of a TextureAtlas. It can be used by the SpriteComponent or the ElementComponent to render a single frame or a sprite animation.
new Sprite(device: GraphicsDevice, options?: object)
Create a new Sprite instance.
Parameters
device (GraphicsDevice): The graphics device of the application.options (object, optional): Options for creating the Sprite.
options.atlas (TextureAtlas, optional): The texture atlas. Defaults to null.
options.frameKeys (string[], optional): The keys of the frames in the sprite atlas that this
sprite is using. Defaults to null.
options.pixelsPerUnit (number, optional): The number of pixels that map to one PlayCanvas
unit. Defaults to 1.
options.renderMode (number, optional): The rendering mode of the sprite. Can be:
Defaults to SPRITE_RENDERMODE_SIMPLE.
get atlas(): TextureAtlas
set atlas(value: TextureAtlas)
Gets the texture atlas.
get frameKeys(): string[]
set frameKeys(value: string[])
Gets the keys of the frames in the sprite atlas that this sprite is using.
get meshes(): Mesh[]
An array that contains a mesh for each frame.
get pixelsPerUnit(): number
set pixelsPerUnit(value: number)
Gets the number of pixels that map to one PlayCanvas unit.
get renderMode(): number
set renderMode(value: number)
Sets the rendering mode of the sprite.
destroy(): void
Free up the meshes created by the sprite.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Graphics
Handles playing of sprite animations and loading of relevant sprite assets.
new SpriteAnimationClip(component: SpriteComponent, data: object)
Create a new SpriteAnimationClip instance.
Parameters
component (SpriteComponent): The sprite component managing this clip.data (object): Data for the new animation clip.
data.fps (number, optional): Frames per second for the animation clip.data.loop (boolean, optional): Whether to loop the animation clip.data.name (string, optional): The name of the new animation clip.data.spriteAsset (number, optional): The id of the sprite asset that this clip will play.fps: number = 0
Frames per second for this animation clip. A negative value plays the animation backwards.
loop: boolean = false
Whether to loop the animation clip when it reaches the end.
name: string | undefined
The name of this animation clip.
get duration(): number
Gets the total duration of the animation in seconds.
get frame(): number
set frame(value: number)
Gets the index of the frame of the Sprite currently being rendered.
get isPaused(): boolean
Sets whether the animation is currently paused.
get isPlaying(): boolean
Sets whether the animation is currently playing.
get sprite(): Sprite
set sprite(value: Sprite)
Gets the current sprite used to play the animation.
get spriteAsset(): number
set spriteAsset(value: number)
Gets the id of the sprite asset used to play the animation.
get time(): number
set time(value: number)
Gets the current time of the animation in seconds.
pause(): void
Pauses the animation.
play(): void
Plays the animation. If it's already playing then this does nothing.
resume(): void
Resumes the paused animation.
stop(): void
Stops the animation and resets the animation to the first frame.
static EVENT_END: string = 'end'
Fired when the clip stops playing because it reached its end.
Example
clip.on('end', () => {
console.log('Clip ended');
});
static EVENT_LOOP: string = 'loop'
Fired when the clip reached the end of its current loop.
Example
clip.on('loop', () => {
console.log('Clip looped');
});
static EVENT_PAUSE: string = 'pause'
Fired when the clip is paused.
Example
clip.on('pause', () => {
console.log('Clip paused');
});
static EVENT_PLAY: string = 'play'
Fired when the clip starts playing.
Example
clip.on('play', () => {
console.log('Clip started playing');
});
static EVENT_RESUME: string = 'resume'
Fired when the clip is resumed.
Example
clip.on('resume', () => {
console.log('Clip resumed');
});
static EVENT_STOP: string = 'stop'
Fired when the clip is stopped.
Example
clip.on('stop', () => {
console.log('Clip stopped');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: Graphics
The SpriteComponent enables an Entity to render a simple static sprite or sprite animations. The type property can be set to either SPRITETYPE_SIMPLE to render a single frame from a sprite asset, or SPRITETYPE_ANIMATED to play one or more SpriteAnimationClips.
You should never need to use the SpriteComponent constructor directly. To add a SpriteComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('sprite', {
spriteAsset: spriteAsset
});
Once the SpriteComponent is added to the entity, you can access it via the Entity#sprite property:
entity.sprite.color = Color.RED; // Tint the sprite red
console.log(entity.sprite.color); // Get the sprite tint and print it
Relevant Engine API examples:
get autoPlayClip(): string
set autoPlayClip(value: string)
Gets the name of the clip to play automatically when the component is enabled.
get batchGroupId(): number
set batchGroupId(value: number)
Gets the batch group for the sprite.
get clips(): {}
set clips(value: {})
Gets the dictionary that contains SpriteAnimationClips.
get color(): Readonly<Color>
set color(value: Readonly<Color>)
Gets the color tint of the sprite in sRGB color space. Use the setter to update the tint.
get currentClip(): SpriteAnimationClip
Gets the current clip being played.
get drawOrder(): number
set drawOrder(value: number)
Gets the draw order of the component.
get flipX(): boolean
set flipX(value: boolean)
Gets whether to flip the X axis when rendering a sprite.
get flipY(): boolean
set flipY(value: boolean)
Gets whether to flip the Y axis when rendering a sprite.
get frame(): number
set frame(value: number)
Gets which frame from the current sprite asset to render.
get height(): number
set height(value: number)
Gets the height of the sprite when rendering using 9-Slicing.
get layers(): readonly number[]
set layers(value: readonly number[])
Gets the array of layer IDs (Layer#id) to which this sprite belongs.
get opacity(): number
set opacity(value: number)
Gets the opacity of the sprite.
get speed(): number
set speed(value: number)
Gets the global speed modifier used when playing sprite animation clips.
get sprite(): Sprite
set sprite(value: Sprite)
Gets the current sprite.
get spriteAsset(): number | Asset<string>
set spriteAsset(value: number | Asset<string>)
Gets the asset id or the Asset of the sprite to render.
get type(): string
set type(value: string)
Gets the type of the SpriteComponent.
get width(): number
set width(value: number)
Gets the width of the sprite when rendering using 9-Slicing.
addClip(data: object): SpriteAnimationClip
Creates and adds a new SpriteAnimationClip to the component's clips.
Parameters
data (object): Data for the new animation clip.
data.fps (number, optional): Frames per second for the animation clip.data.loop (boolean, optional): Whether to loop the animation clip.data.name (string, optional): The name of the new animation clip.data.spriteAsset (number | Asset<string>, optional): The asset id or
the Asset of the sprite that this clip will play.Returns SpriteAnimationClip: The new clip that was added.
clip(name: string): SpriteAnimationClip
Get an animation clip by name.
Parameters
name (string): The name of the clip.Returns SpriteAnimationClip: The clip.
pause(): void
Pauses the current animation clip.
play(name: string): SpriteAnimationClip
Plays a sprite animation clip by name. If the animation clip is already playing then this will do nothing.
Parameters
name (string): The name of the clip to play.Returns SpriteAnimationClip: The clip that started playing.
removeClip(name: string): void
Removes a clip by name.
Parameters
name (string): The name of the animation clip to remove.resume(): void
Resumes the current paused animation clip.
stop(): void
Stops the current animation clip and resets it to the first frame.
static EVENT_END: string = 'end'
Fired when an animation clip stops playing because it reached its end. The handler is passed the SpriteAnimationClip that ended.
Example
entity.sprite.on('end', (clip) => {
console.log(`Animation clip ${clip.name} ended.`);
});
static EVENT_LOOP: string = 'loop'
Fired when an animation clip reached the end of its current loop. The handler is passed the SpriteAnimationClip that looped.
Example
entity.sprite.on('loop', (clip) => {
console.log(`Animation clip ${clip.name} looped.`);
});
static EVENT_PAUSE: string = 'pause'
Fired when an animation clip is paused. The handler is passed the SpriteAnimationClip that was paused.
Example
entity.sprite.on('pause', (clip) => {
console.log(`Animation clip ${clip.name} paused.`);
});
static EVENT_PLAY: string = 'play'
Fired when an animation clip starts playing. The handler is passed the SpriteAnimationClip that started playing.
Example
entity.sprite.on('play', (clip) => {
console.log(`Animation clip ${clip.name} started playing.`);
});
static EVENT_RESUME: string = 'resume'
Fired when an animation clip is resumed. The handler is passed the SpriteAnimationClip that was resumed.
Example
entity.sprite.on('resume', (clip) => {
console.log(`Animation clip ${clip.name} resumed.`);
});
static EVENT_STOP: string = 'stop'
Fired when an animation clip is stopped. The handler is passed the SpriteAnimationClip that was stopped.
Example
entity.sprite.on('stop', (clip) => {
console.log(`Animation clip ${clip.name} stopped.`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Graphics
Manages the SpriteComponents of an application. Reach it through app.systems.sprite;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Material · category: Graphics
A standard material is the main, general purpose material that is most often used for rendering. It can approximate a wide variety of surface types and can simulate dynamic reflected light. Most maps can use 3 types of input values in any combination: constant (Color or number), mesh vertex colors and a Texture. All enabled inputs are multiplied together. A texture samples one of the mesh's UV sets, selected by the map's UV channel property (0 to 7), and is ignored when the mesh does not provide that set. UV sets 6 and 7 share their vertex attribute locations with the default hardware instancing format, so an instanced mesh sampling them needs a custom instancing vertex format, see MeshInstance#setInstancing.
A property assignment only reaches the GPU once Material#update is called: a diffuse
or emissive change made after the material's first frame is not applied until
material.update() runs. The debug build reports unapplied changes to the properties stored in
the material uniform buffer, such as diffuse.
Properties come in families that share a naming pattern. A family such as diffuse has a
constant (diffuse), a texture (diffuseMap) with its diffuseMapUv, diffuseMapTiling,
diffuseMapOffset, diffuseMapRotation and diffuseMapChannel, and a vertex color switch
(diffuseVertexColor). The main families are diffuse; specular, or metalness when
useMetalness is set; gloss; normalMap with bumpiness; emissive; opacity together
with Material#blendType; ao; lightMap; and the advanced layers clearCoat, sheen,
iridescence and refraction. Lighting can be turned off entirely with useLighting.
To go beyond the properties, replace individual shader chunks with Material#getShaderChunks. When the surface is not a lit material at all, use ShaderMaterial instead.
Example
const material = new StandardMaterial();
material.diffuse.set(0.8, 0.2, 0.2);
material.diffuseMap = brickAsset.resource;
material.useMetalness = true;
material.metalness = 0.1;
material.gloss = 0.6;
material.update();
entity.render.material = material;
new StandardMaterial()
Create a new StandardMaterial instance.
Example
// Create a new Standard material
const material = new StandardMaterial();
// Update the material's diffuse and specular properties
material.diffuse.set(1, 0, 0);
material.specular.set(1, 1, 1);
// Notify the material that it has been modified
material.update();
Example
// Create a new Standard material
const material = new StandardMaterial();
// Assign a texture to the diffuse slot
material.diffuseMap = texture;
// Use the alpha channel of the texture for alpha testing with a reference value of 0.5
material.opacityMap = texture;
material.alphaTest = 0.5;
// Notify the material that it has been modified
material.update();
anisotropyMap: Texture | null
The anisotropy map of the material (default is null).
anisotropyMapOffset: Vec2
Controls the 2D offset of the anisotropy map. Each component is between 0 and 1.
anisotropyMapRotation: number
Controls the 2D rotation (in degrees) of the anisotropy map.
anisotropyMapTiling: Vec2
Controls the 2D tiling of the anisotropy map.
anisotropyMapUv: number
Anisotropy map UV channel. Valid values are 0 to 7.
aoDetailMap: Texture | null
The detail (secondary) baked ambient occlusion (AO) map of the material (default is null). Will only be used if main (primary) ao map is non-null.
aoDetailMapChannel: string
Color channels of the detail (secondary) AO map to use. Can be "r", "g", "b" or "a" (default is "g").
aoDetailMapOffset: Vec2
Controls the 2D offset of the detail (secondary) AO map. Each component is between 0 and 1.
aoDetailMapRotation: number
Controls the 2D rotation (in degrees) of the detail (secondary) AO map.
aoDetailMapTiling: Vec2
Controls the 2D tiling of the detail (secondary) AO map.
aoDetailMapUv: number
Detail (secondary) AO map UV channel. Valid values are 0 to 7.
aoDetailMode: string
Determines how the main (primary) and detail (secondary) AO maps are blended together. Can be:
Defaults to DETAILMODE_MUL.
aoMap: Texture | null
The main (primary) baked ambient occlusion (AO) map (default is null). Modulates ambient color.
aoMapChannel: string
Color channel of the main (primary) AO map to use. Can be "r", "g", "b" or "a".
aoMapOffset: Vec2
Controls the 2D offset of the main (primary) AO map. Each component is between 0 and 1.
aoMapRotation: number
Controls the 2D rotation (in degrees) of the main (primary) AO map.
aoMapTiling: Vec2
Controls the 2D tiling of the main (primary) AO map.
aoMapUv: number
Main (primary) AO map UV channel. Valid values are 0 to 7.
aoVertexColor: boolean
Use mesh vertex colors for AO. If aoMap is set, it'll be multiplied by vertex colors.
aoVertexColorChannel: string
Vertex color channels to use for AO. Can be "r", "g", "b" or "a".
clearCoatGlossInvert: boolean
Invert the clearcoat gloss component (default is false). Enabling this flag results in material treating the clear coat gloss members as roughness.
clearCoatGlossMap: Texture | null
Monochrome clearcoat glossiness map (default is null). If specified, will be multiplied by normalized 'clearCoatGloss' value and/or vertex colors.
clearCoatGlossMapChannel: string
Color channel of the clearcoat gloss map to use. Can be "r", "g", "b" or "a".
clearCoatGlossMapOffset: Vec2
Controls the 2D offset of the clearcoat gloss map. Each component is between 0 and 1.
clearCoatGlossMapRotation: number
Controls the 2D rotation (in degrees) of the clear coat gloss map.
clearCoatGlossMapTiling: Vec2
Controls the 2D tiling of the clearcoat gloss map.
clearCoatGlossMapUv: number
Clearcoat gloss map UV channel. Valid values are 0 to 7.
clearCoatGlossVertexColor: boolean
Use mesh vertex colors for clearcoat glossiness. If clearCoatGlossMap is set, it'll be multiplied by vertex colors.
clearCoatGlossVertexColorChannel: string
Vertex color channel to use for clearcoat glossiness. Can be "r", "g", "b" or "a".
clearCoatMap: Texture | null
Monochrome clearcoat intensity map (default is null). If specified, will be multiplied by normalized 'clearCoat' value and/or vertex colors.
clearCoatMapChannel: string
Color channel of the clearcoat intensity map to use. Can be "r", "g", "b" or "a".
clearCoatMapOffset: Vec2
Controls the 2D offset of the clearcoat intensity map. Each component is between 0 and 1.
clearCoatMapRotation: number
Controls the 2D rotation (in degrees) of the clearcoat intensity map.
clearCoatMapTiling: Vec2
Controls the 2D tiling of the clearcoat intensity map.
clearCoatMapUv: number
Clearcoat intensity map UV channel. Valid values are 0 to 7.
clearCoatNormalMap: Texture | null
The clearcoat normal map of the material (default is null). The texture must contains normalized, tangent space normals.
clearCoatNormalMapOffset: Vec2
Controls the 2D offset of the main clearcoat normal map. Each component is between 0 and 1.
clearCoatNormalMapRotation: number
Controls the 2D rotation (in degrees) of the main clearcoat map.
clearCoatNormalMapTiling: Vec2
Controls the 2D tiling of the main clearcoat normal map.
clearCoatNormalMapUv: number
Clearcoat normal map UV channel. Valid values are 0 to 7.
clearCoatVertexColor: boolean
Use mesh vertex colors for clearcoat intensity. If clearCoatMap is set, it'll be multiplied by vertex colors.
clearCoatVertexColorChannel: string
Vertex color channel to use for clearcoat intensity. Can be "r", "g", "b" or "a".
cubeMap: Texture | null
The cubic environment map of the material (default is null). This setting overrides sphereMap and will replace the scene lighting environment.
cubeMapProjection: number
The type of projection applied to the cubeMap property:
diffuseDetailMap: Texture | null
The detail (secondary) diffuse map of the material (default is null). Will only be used if main (primary) diffuse map is non-null.
diffuseDetailMapChannel: string
Color channels of the detail (secondary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
diffuseDetailMapOffset: Vec2
Controls the 2D offset of the detail (secondary) diffuse map. Each component is between 0 and 1.
diffuseDetailMapRotation: number
Controls the 2D rotation (in degrees) of the detail (secondary) diffuse map.
diffuseDetailMapTiling: Vec2
Controls the 2D tiling of the detail (secondary) diffuse map.
diffuseDetailMapUv: number
Detail (secondary) diffuse map UV channel. Valid values are 0 to 7.
diffuseDetailMode: string
Determines how the main (primary) and detail (secondary) diffuse maps are blended together. Can be:
Defaults to DETAILMODE_MUL.
diffuseMap: Texture | null
The main (primary) diffuse map of the material (default is null).
diffuseMapChannel: string
Color channels of the main (primary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
diffuseMapOffset: Vec2
Controls the 2D offset of the main (primary) diffuse map. Each component is between 0 and 1.
diffuseMapRotation: number
Controls the 2D rotation (in degrees) of the main (primary) diffuse map.
diffuseMapTiling: Vec2
Controls the 2D tiling of the main (primary) diffuse map.
diffuseMapUv: number
Main (primary) diffuse map UV channel. Valid values are 0 to 7.
diffuseVertexColor: boolean
Multiply diffuse by the mesh vertex colors.
diffuseVertexColorChannel: string
Vertex color channels to use for diffuse. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
emissiveMap: Texture | null
The emissive map of the material (default is null). Can be HDR. When the emissive map is applied, the emissive color is multiplied by the texel color in the map. Since the emissive color is black by default, the emissive map won't be visible unless the emissive color is changed.
emissiveMapChannel: string
Color channels of the emissive map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
emissiveMapOffset: Vec2
Controls the 2D offset of the emissive map. Each component is between 0 and 1.
emissiveMapRotation: number
Controls the 2D rotation (in degrees) of the emissive map.
emissiveMapTiling: Vec2
Controls the 2D tiling of the emissive map.
emissiveMapUv: number
Emissive map UV channel. Valid values are 0 to 7.
emissiveVertexColor: boolean
Use mesh vertex colors for emission. If emissiveMap or emissive are set, they'll be multiplied by vertex colors.
emissiveVertexColorChannel: string
Vertex color channels to use for emission. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
enableGGXSpecular: boolean
Enables GGX specular. Also enables anisotropyIntensity parameter to set material anisotropy.
envAtlas: Texture | null
The prefiltered environment lighting atlas (default is null). This setting overrides cubeMap and sphereMap and will replace the scene lighting environment.
fresnelModel: number
Defines the formula used for Fresnel effect. As a side-effect, enabling any Fresnel model changes the way diffuse and reflection components are combined. When Fresnel is off, legacy non energy-conserving combining is used. When it is on, combining behavior is energy-conserving.
glossInvert: boolean
Invert the gloss component (default is false). Enabling this flag results in material treating the gloss members as roughness.
glossMap: Texture | null
Gloss map (default is null). If specified, will be multiplied by normalized gloss value and/or vertex colors.
glossMapChannel: string
Color channel of the gloss map to use. Can be "r", "g", "b" or "a".
glossMapOffset: Vec2
Controls the 2D offset of the gloss map. Each component is between 0 and 1.
glossMapRotation: number
Controls the 2D rotation (in degrees) of the gloss map.
glossMapTiling: Vec2
Controls the 2D tiling of the gloss map.
glossMapUv: number
Gloss map UV channel. Valid values are 0 to 7.
glossVertexColor: boolean
Use mesh vertex colors for glossiness. If glossMap is set, it'll be multiplied by vertex colors.
glossVertexColorChannel: string
Vertex color channel to use for glossiness. Can be "r", "g", "b" or "a".
heightMap: Texture | null
The height map of the material (default is null). Used for a view-dependent parallax effect. The texture must represent the height of the surface where darker pixels are lower and lighter pixels are higher, with heightMapBase selecting the value that sits at the level of the original geometry. It is recommended to use it together with a normal map. Note that the parallax offset is applied to all other maps of the material, so the height map should use the same tiling and offset as those maps.
heightMapChannel: string
Color channel of the height map to use. Can be "r", "g", "b" or "a".
heightMapOffset: Vec2
Controls the 2D offset of the height map. Each component is between 0 and 1.
heightMapRotation: number
Controls the 2D rotation (in degrees) of the height map.
heightMapTiling: Vec2
Controls the 2D tiling of the height map.
heightMapUv: number
Height map UV channel. Valid values are 0 to 7.
iridescenceMap: Texture | null
The per-pixel iridescence intensity. Only used when useIridescence is enabled.
iridescenceMapChannel: string
Color channels of the iridescence map to use. Can be "r", "g", "b" or "a".
iridescenceMapOffset: Vec2
Controls the 2D offset of the iridescence map. Each component is between 0 and 1.
iridescenceMapRotation: number
Controls the 2D rotation (in degrees) of the iridescence map.
iridescenceMapTiling: Vec2
Controls the 2D tiling of the iridescence map.
iridescenceMapUv: number
Iridescence map UV channel. Valid values are 0 to 7.
iridescenceThicknessMap: Texture | null
The per-pixel iridescence thickness. Defines a gradient weight between iridescenceThicknessMin and iridescenceThicknessMax. Only used when useIridescence is enabled.
iridescenceThicknessMapChannel: string
Color channels of the iridescence thickness map to use. Can be "r", "g", "b" or "a".
iridescenceThicknessMapOffset: Vec2
Controls the 2D offset of the iridescence thickness map. Each component is between 0 and 1.
iridescenceThicknessMapRotation: number
Controls the 2D rotation (in degrees) of the iridescence thickness map.
iridescenceThicknessMapTiling: Vec2
Controls the 2D tiling of the iridescence thickness map.
iridescenceThicknessMapUv: number
Iridescence thickness map UV channel. Valid values are 0 to 7.
lightMap: Texture | null
A custom lightmap of the material (default is null). Lightmaps are textures that contain pre-rendered lighting. Can be HDR. When a mesh instance rendered with this material has a lightmap of its own, baked by the Lightmapper, that lightmap is used instead of this one.
lightMapChannel: string
Color channels of the lightmap to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
lightMapOffset: Vec2
Controls the 2D offset of the lightmap. Each component is between 0 and 1.
lightMapRotation: number
Controls the 2D rotation (in degrees) of the lightmap.
lightMapTiling: Vec2
Controls the 2D tiling of the lightmap.
lightMapUv: number
Lightmap UV channel. Valid values are 0 to 7.
lightVertexColor: boolean
Use baked vertex lighting. If lightMap is set, it'll be multiplied by vertex colors.
lightVertexColorChannel: string
Vertex color channels to use for baked lighting. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
metalnessMap: Texture | null
Monochrome metalness map (default is null).
metalnessMapChannel: string
Color channel of the metalness map to use. Can be "r", "g", "b" or "a".
metalnessMapOffset: Vec2
Controls the 2D offset of the metalness map. Each component is between 0 and 1.
metalnessMapRotation: number
Controls the 2D rotation (in degrees) of the metalness map.
metalnessMapTiling: Vec2
Controls the 2D tiling of the metalness map.
metalnessMapUv: number
Metalness map UV channel. Valid values are 0 to 7.
metalnessVertexColor: boolean
Use mesh vertex colors for metalness. If metalnessMap is set, it'll be multiplied by vertex colors.
metalnessVertexColorChannel: string
Vertex color channel to use for metalness. Can be "r", "g", "b" or "a".
normalDetailMap: Texture | null
The detail (secondary) normal map of the material (default is null). Will only be used if main (primary) normal map is non-null.
normalDetailMapOffset: Vec2
Controls the 2D offset of the detail (secondary) normal map. Each component is between 0 and 1.
normalDetailMapRotation: number
Controls the 2D rotation (in degrees) of the detail (secondary) normal map.
normalDetailMapTiling: Vec2
Controls the 2D tiling of the detail (secondary) normal map.
normalDetailMapUv: number
Detail (secondary) normal map UV channel. Valid values are 0 to 7.
normalMap: Texture | null
The main (primary) normal map of the material (default is null). The texture must contains normalized, tangent space normals.
normalMapOffset: Vec2
Controls the 2D offset of the main (primary) normal map. Each component is between 0 and 1.
normalMapRotation: number
Controls the 2D rotation (in degrees) of the main (primary) normal map.
normalMapTiling: Vec2
Controls the 2D tiling of the main (primary) normal map.
normalMapUv: number
Main (primary) normal map UV channel. Valid values are 0 to 7.
occludeDirect: boolean
Tells if AO should darken directional lighting. Defaults to false.
occludeSpecular: number
Uses ambient occlusion to darken specular/reflection. It's a hack, because real specular occlusion is view-dependent. However, it can be better than nothing.
onUpdateShader: UpdateShaderCallback | undefined
A custom function that will be called after all shader generator properties are collected and before shader code is generated. This function will receive an object with shader generator settings (based on current material and scene properties), that you can change and then return. Returned value will be used instead. This is mostly useful when rendering the same set of objects, but with different shader variations based on the same material. For example, you may wish to render a depth or normal pass using textures assigned to the material, a reflection pass with simpler shaders and so on. These properties are split into two sections, generic standard material options and lit options. Properties of the standard material options are StandardMaterialOptions and the options for the lit options are LitShaderOptions.
opacityDither: string
Used to specify whether opacity is dithered, which allows transparency without alpha blending. Can be:
Defaults to DITHER_NONE.
opacityFadesSpecular: boolean
Used to specify whether specular and reflections are faded out using opacity. Default is true. When set to false use alphaFade to fade out materials.
opacityMap: Texture | null
The opacity map of the material (default is null).
opacityMapChannel: string
Color channel of the opacity map to use. Can be "r", "g", "b" or "a".
opacityMapOffset: Vec2
Controls the 2D offset of the opacity map. Each component is between 0 and 1.
opacityMapRotation: number
Controls the 2D rotation (in degrees) of the opacity map.
opacityMapTiling: Vec2
Controls the 2D tiling of the opacity map.
opacityMapUv: number
Opacity map UV channel. Valid values are 0 to 7.
opacityShadowDither: string
Used to specify whether shadow opacity is dithered, which allows shadow transparency without alpha blending. Can be:
Defaults to DITHER_NONE.
opacityVertexColor: boolean
Use mesh vertex colors for opacity. If opacityMap is set, it'll be multiplied by vertex colors.
opacityVertexColorChannel: string
Vertex color channels to use for opacity. Can be "r", "g", "b" or "a".
parallaxMode: string
Selects how the height map is used to offset the UV of the other maps of the material. Can be:
Defaults to PARALLAX_OFFSET.
pixelSnap: boolean
Align vertices to pixel coordinates when rendering. Useful for pixel perfect 2D graphics.
refractionMap: Texture | null
The map of the refraction visibility.
refractionMapChannel: string
Color channels of the refraction map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
refractionMapOffset: Vec2
Controls the 2D offset of the refraction map. Each component is between 0 and 1.
refractionMapRotation: number
Controls the 2D rotation (in degrees) of the refraction map.
refractionMapTiling: Vec2
Controls the 2D tiling of the refraction map.
refractionMapUv: number
Refraction map UV channel. Valid values are 0 to 7.
refractionVertexColor: boolean
Use mesh vertex colors for refraction. If refraction map is set, it will be multiplied by vertex colors.
refractionVertexColorChannel: string
Vertex color channel to use for refraction. Can be "r", "g", "b" or "a".
shadowCatcher: boolean
When enabled, the material will output accumulated directional shadow value in linear space as the color.
sheenGlossInvert: boolean
Invert the sheen gloss component (default is false). Enabling this flag results in material treating the sheen gloss members as roughness.
sheenGlossMap: Texture | null
The sheen glossiness microstructure color map of the material (default is null).
sheenGlossMapChannel: string
Color channels of the sheen glossiness map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
sheenGlossMapOffset: Vec2
Controls the 2D offset of the sheen glossiness map. Each component is between 0 and 1.
sheenGlossMapRotation: number
Controls the 2D rotation (in degrees) of the sheen glossiness map.
sheenGlossMapTiling: Vec2
Controls the 2D tiling of the sheen glossiness map.
sheenGlossMapUv: number
Sheen glossiness map UV channel. Valid values are 0 to 7.
sheenGlossVertexColor: boolean
Use mesh vertex colors for sheen glossiness. If sheen glossiness map or sheen glossiness tint are set, they'll be multiplied by vertex colors.
sheenGlossVertexColorChannel: string
Vertex color channels to use for sheen glossiness. Can be "r", "g", "b" or "a".
sheenMap: Texture | null
The sheen microstructure color map of the material (default is null).
sheenMapChannel: string
Color channels of the sheen map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
sheenMapOffset: Vec2
Controls the 2D offset of the sheen map. Each component is between 0 and 1.
sheenMapRotation: number
Controls the 2D rotation (in degrees) of the sheen map.
sheenMapTiling: Vec2
Controls the 2D tiling of the sheen map.
sheenMapUv: number
Sheen map UV channel. Valid values are 0 to 7.
sheenVertexColor: boolean
Use mesh vertex colors for sheen. If sheen map or sheen tint are set, they'll be multiplied by vertex colors.
sheenVertexColorChannel: string
Vertex color channels to use for sheen. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
specularityFactorMap: Texture | null
The factor of specularity as a texture (default is null).
specularityFactorMapChannel: string
The channel used by the specularity factor texture to sample from (default is 'a').
specularityFactorMapOffset: Vec2
Controls the 2D offset of the specularity factor map. Each component is between 0 and 1.
specularityFactorMapRotation: number
Controls the 2D rotation (in degrees) of the specularity factor map.
specularityFactorMapTiling: Vec2
Controls the 2D tiling of the specularity factor map.
specularityFactorMapUv: number
Specularity factor map UV channel. Valid values are 0 to 7.
specularityFactorTint: boolean
Force inclusion of the constant specularityFactor
when compositing with specularityFactorMap and/or specularity factor vertex colors. Defaults
to false. Setting this to true is rarely needed - the constant is automatically applied
whenever specularityFactor differs from 1. Provided as an explicit override.
specularityFactorVertexColor: boolean
Use mesh vertex colors for specularity factor. If specularityFactorMap or are specularityFactorTint are set, they'll be multiplied by vertex colors.
specularityFactorVertexColorChannel: string
Vertex color channels to use for specularity factor. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
specularMap: Texture | null
The specular map of the material (default is null).
specularMapChannel: string
Color channels of the specular map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
specularMapOffset: Vec2
Controls the 2D offset of the specular map. Each component is between 0 and 1.
specularMapRotation: number
Controls the 2D rotation (in degrees) of the specular map.
specularMapTiling: Vec2
Controls the 2D tiling of the specular map.
specularMapUv: number
Specular map UV channel. Valid values are 0 to 7.
specularVertexColor: boolean
Multiply specular by the mesh vertex colors.
specularVertexColorChannel: string
Vertex color channels to use for specular. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.
sphereMap: Texture | null
The spherical environment map of the material (default is null). This will replace the scene lighting environment.
thicknessMap: Texture | null
The per-pixel thickness of the medium, only used when useDynamicRefraction is enabled.
thicknessMapChannel: string
Color channels of the thickness map to use. Can be "r", "g", "b" or "a".
thicknessMapOffset: Vec2
Controls the 2D offset of the thickness map. Each component is between 0 and 1.
thicknessMapRotation: number
Controls the 2D rotation (in degrees) of the thickness map.
thicknessMapTiling: Vec2
Controls the 2D tiling of the thickness map.
thicknessMapUv: number
Thickness map UV channel. Valid values are 0 to 7.
thicknessVertexColor: boolean
Use mesh vertex colors for thickness. If thickness map is set, it will be multiplied by vertex colors.
thicknessVertexColorChannel: string
Vertex color channel to use for thickness. Can be "r", "g", "b" or "a".
twoSidedLighting: boolean
Calculate proper normals (and therefore lighting) on backfaces.
useDynamicRefraction: boolean
Enables higher quality refractions using the grab pass instead of pre-computed cube maps for refractions.
useFog: boolean
Apply fogging (as configured in scene settings)
useIridescence: boolean
Enable thin-film iridescence.
useLighting: boolean
Apply lighting
useMetalness: boolean
Use metalness properties instead of specular. When enabled, diffuse colors also affect specular instead of the dedicated specular map. This can be used as alternative to specular color to save space. With metalness == 0, the pixel is assumed to be dielectric, and diffuse color is used as normal. With metalness == 1, the pixel is fully metallic, and diffuse color is used as specular color instead.
useMetalnessSpecularColor: boolean
When metalness is enabled, use the specular map to apply color tint to specular reflections.
useSheen: boolean
Toggle sheen specular effect on/off.
useSkybox: boolean
Apply scene skybox as prefiltered environment map
useTonemap: boolean
Apply tonemapping (as configured via CameraComponent#toneMapping). Defaults to true.
vertexColorGamma: boolean
When set to true, the vertex shader converts vertex colors from gamma to linear space to ensure correct interpolation in the fragment shader. This flag is provided for backwards compatibility, allowing users to mark their materials to handle vertex colors in gamma space. Defaults to false, which indicates that vertex colors are stored in linear space.
get alphaDither(): number
set alphaDither(value: number)
Gets the dither alpha of the material.
get alphaFade(): number
set alphaFade(value: number)
Gets the alpha fade of the material.
get alphaTest(): number
set alphaTest(value: number)
Gets the alpha test reference value.
get ambient(): Color
set ambient(value: Color)
Gets the ambient color of the material.
get anisotropyIntensity(): number
set anisotropyIntensity(value: number)
Gets the anisotropy intensity of the material.
get anisotropyRotation(): number
set anisotropyRotation(value: number)
Gets the anisotropy rotation of the material.
get aoIntensity(): number
set aoIntensity(value: number)
Gets the ambient occlusion intensity of the material.
get attenuation(): Color
set attenuation(value: Color)
Gets the attenuation color of the material.
get attenuationDistance(): number
set attenuationDistance(value: number)
Gets the attenuation distance of the material.
get bumpiness(): number
set bumpiness(value: number)
Gets the bumpiness of the material.
get clearCoat(): number
set clearCoat(value: number)
Gets the clearcoat intensity of the material.
get clearCoatBumpiness(): number
set clearCoatBumpiness(value: number)
Gets the clearcoat bumpiness of the material.
get clearCoatGloss(): number
set clearCoatGloss(value: number)
Gets the clearcoat glossiness of the material.
get cubeMapProjectionBox(): BoundingBox | null
set cubeMapProjectionBox(value: BoundingBox | null)
Gets the world space axis-aligned bounding box of the box-projection, or null. A change of its center or half extents is applied by StandardMaterial#update.
get diffuse(): Color
set diffuse(value: Color)
Gets the diffuse color of the material.
get dispersion(): number
set dispersion(value: number)
Gets the dispersion of the material.
get emissive(): Color
set emissive(value: Color)
Gets the emissive color of the material.
get emissiveIntensity(): number
set emissiveIntensity(value: number)
Gets the emissive color multiplier.
get gloss(): number
set gloss(value: number)
Gets the glossiness of the material.
get heightMapBase(): number
set heightMapBase(value: number)
Gets the height map base level of the material.
get heightMapFactor(): number
set heightMapFactor(value: number)
Gets the height map factor of the material.
get iridescence(): number
set iridescence(value: number)
Gets the iridescence intensity of the material.
get iridescenceRefractionIndex(): number
set iridescenceRefractionIndex(value: number)
Gets the index of refraction of the iridescent thin-film of the material.
get iridescenceThicknessMax(): number
set iridescenceThicknessMax(value: number)
Gets the maximum iridescence thickness of the material.
get iridescenceThicknessMin(): number
set iridescenceThicknessMin(value: number)
Gets the minimum iridescence thickness of the material.
get metalness(): number
set metalness(value: number)
Gets the metalness of the material.
get normalDetailMapBumpiness(): number
set normalDetailMapBumpiness(value: number)
Gets the detail normal map bumpiness of the material.
get occludeSpecularIntensity(): number
set occludeSpecularIntensity(value: number)
Gets the specular occlusion intensity of the material.
get opacity(): number
set opacity(value: number)
Gets the opacity of the material.
get parallaxSamples(): number
set parallaxSamples(value: number)
Gets the maximum number of height map taps of parallax occlusion mapping of the material.
get parallaxShadowSamples(): number
set parallaxShadowSamples(value: number)
Gets the maximum number of height map taps of the parallax self shadowing of the material.
get reflectivity(): number
set reflectivity(value: number)
Gets the environment map intensity of the material.
get refraction(): number
set refraction(value: number)
Gets the refraction of the material.
get refractionIndex(): number
set refractionIndex(value: number)
Gets the index of refraction of the material.
get sheen(): Color
set sheen(value: Color)
Gets the sheen color of the material.
get sheenGloss(): number
set sheenGloss(value: number)
Gets the sheen glossiness of the material.
get specular(): Color
set specular(value: Color)
Gets the specular color of the material.
get specularityFactor(): number
set specularityFactor(value: number)
Gets the specularity factor of the material.
get thickness(): number
set thickness(value: number)
Gets the thickness of the medium of the material.
copy(source: StandardMaterial): StandardMaterial
Copy a StandardMaterial.
Parameters
source (StandardMaterial): The material to copy from.Returns StandardMaterial: The destination material.
destroy(): void
Removes this material from the scene and possibly frees up memory from its shaders (if there are no other materials using it).
setAttribute(name: string, semantic: string): void
Sets a vertex shader attribute on a material.
Parameters
name (string): The name of the parameter to set.semantic (string): Semantic to map the vertex data. Must match with the semantic set
on vertex stream of the mesh.Example
mesh.setVertexStream(SEMANTIC_ATTR15, offset, 3);
material.setAttribute('offset', SEMANTIC_ATTR15);
update(): void
alphaToCoverage: boolean = falsecull: number = CULLFACE_BACKfrontFace: number = FRONTFACE_CCWname: string = 'Untitled'stencilBack: StencilParameters | null = nullstencilFront: StencilParameters | null = nulluserId: string = ''get alphaWrite(): boolean · set alphaWrite(value: boolean)get blendState(): Readonly<BlendState> · set blendState(value: Readonly<BlendState>)get blendType(): number · set blendType(type: number)get blueWrite(): boolean · set blueWrite(value: boolean)get depthBias(): number · set depthBias(value: number)get depthFunc(): number · set depthFunc(value: number)get depthState(): DepthState · set depthState(value: DepthState)get depthTest(): boolean · set depthTest(value: boolean)get depthWrite(): boolean · set depthWrite(value: boolean)get flatShading(): boolean · set flatShading(value: boolean)get greenWrite(): boolean · set greenWrite(value: boolean)get redWrite(): boolean · set redWrite(value: boolean)get shaderChunksVersion(): string · set shaderChunksVersion(value: string)get slopeDepthBias(): number · set slopeDepthBias(value: number)protected _markLayoutDirty(): voidprotected _markPropertyModified(property: MaterialProperty): voidprotected _markPropertyMutable(property: MaterialProperty, value: any): voidclone(): StandardMaterialdeleteParameter(name: string): voidgetDefine(name: string): booleangetParameter(name: string): anygetShaderChunks(shaderLanguage?: string): ShaderChunkMapsetDefine(name: string, value: string | boolean | undefined): voidsetParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): voidClass · category: Graphics
The standard material options define a set of options used to control the shader frontend shader generation, such as textures, tints and multipliers.
clearCoatGlossInvert: boolean = false
Invert the clearcoat gloss channel.
clearCoatPackedNormal: boolean = false
If normal clear coat map contains X in RGB, Y in Alpha, and Z must be reconstructed.
defines: Map<string, string>
The set of defines used to generate the shader.
forceUv1: boolean = false
If UV1 (second set of texture coordinates) is required in the shader. Will be declared as "vUv1" and passed to the fragment shader.
glossInvert: boolean = false
Invert the gloss channel.
glossTint: boolean = false
Defines if StandardMaterial#gloss constant should affect glossiness value.
litOptions: LitShaderOptions
Storage for the options for lit the shader and material.
metalnessTint: boolean = false
Defines if StandardMaterial#metalness constant should affect metalness value.
normalDetailPackedNormal: boolean = false
If normal detail map contains X in RGB, Y in Alpha, and Z must be reconstructed.
packedNormal: boolean = false
If normal map contains X in RGB, Y in Alpha, and Z must be reconstructed.
sheenGlossInvert: boolean = false
Invert the sheen gloss channel.
useAO: boolean = false
True to include AO variables even if AO is not used, which allows SSAO to be used in the lit shader.
useInstanceLightMap: boolean = false
True if the lightmap comes from the mesh instance rather than from the material, and so is sampled from the mesh instance's own texture slot. See Lightmapper.
Class · category: Graphics
Holds stencil test settings.
new StencilParameters(options?: any)
Create a new StencilParameters instance.
Parameters
options (any, optional, default {}): Options object to configure the stencil parameters.static readonly DEFAULT: StencilParameters
A default stencil state.
get fail(): number
set fail(value: number)
Gets the operation to perform if stencil test is failed.
get func(): number
set func(value: number)
Sets the comparison function that decides if the pixel should be written.
get readMask(): number
set readMask(value: number)
Gets the mask applied to stencil buffer value and reference value before comparison.
get ref(): number
set ref(value: number)
Gets the stencil test reference value used in comparisons.
get writeMask(): number
set writeMask(value: number)
Gets the bit mask applied to the stencil value when written.
get zfail(): number
set zfail(value: number)
Gets the operation to perform if depth test is failed.
get zpass(): number
set zpass(value: number)
Gets the operation to perform if both stencil and depth test are passed.
clone(): StencilParameters
Clone the stencil parameters.
Returns StencilParameters: A cloned StencilParameters object.
copy(rhs: StencilParameters): StencilParameters
Copies the contents of a source stencil parameters to this stencil parameters.
Parameters
rhs (StencilParameters): A stencil parameters to copy from.Returns StencilParameters: Self for chaining.
Class · category: Graphics
A storage buffer represents a memory which both the CPU and the GPU can access. Typically it is used to provide data for compute shader, and to store the result of the computation. Note that this class is only supported on the WebGPU platform.
After a graphics device is lost and restored, the GPU backing for a storage buffer is recreated at the same byte size but its contents are undefined until you write to it again or repopulate it via compute.
For debug identification in buffer memory listings (when the TRACEID_BUFFERS trace
channel is enabled), call sites may assign the instance's name property to a descriptive
string.
new StorageBuffer(graphicsDevice: GraphicsDevice, byteSize: number, bufferUsage?: number, addStorageUsage?: boolean)
Create a new StorageBuffer instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this storage buffer.byteSize (number): The size of the storage buffer in bytes.bufferUsage (number, optional, default 0): The usage type of the storage buffer. Can be a combination
of BUFFERUSAGE_READ, BUFFERUSAGE_WRITE, BUFFERUSAGE_COPY_SRC and
BUFFERUSAGE_COPY_DST flags. This parameter can be omitted if no special usage is
required.addStorageUsage (boolean, optional, default true): If true, automatically adds BUFFERUSAGE_STORAGE flag.
Set to false for staging buffers that use BUFFERUSAGE_WRITE. Defaults to true.clear(offset?: number, size?: number): void
Clear the content of a storage buffer to 0.
Parameters
offset (number, optional, default 0): The byte offset of data to clear. Defaults to 0.size (number, optional): The byte size of data to clear. Defaults to the full size of the
buffer minus the offset.copy(srcBuffer: StorageBuffer, srcOffset?: number, dstOffset?: number, size?: number): void
Copy data from another storage buffer into this storage buffer.
Parameters
srcBuffer (StorageBuffer): The source storage buffer to copy from.srcOffset (number, optional, default 0): The byte offset in the source buffer. Defaults to 0.dstOffset (number, optional, default 0): The byte offset in this buffer. Defaults to 0.size (number, optional): The byte size of data to copy. Defaults to the full size of the
source buffer minus the source offset.destroy(): void
Frees resources associated with this storage buffer.
read(offset?: number, size?: number, data?: ArrayBufferView<ArrayBufferLike> | null, immediate?: boolean): Promise<ArrayBufferView<ArrayBufferLike>>
Read the contents of a storage buffer.
Parameters
offset (number, optional, default 0): The byte offset of data to read. Defaults to 0.size (number, optional): The byte size of data to read. Defaults to the full size of the
buffer minus the offset.data (ArrayBufferView<ArrayBufferLike> | null, optional, default null): Typed array to populate with the data read from the
storage buffer. When typed array is supplied, enough space needs to be reserved, otherwise
only partial data is copied. If not specified, the data is returned in an Uint8Array.
Defaults to null.immediate (boolean, optional, default false): If true, the read operation will be executed as soon as
possible. This has a performance impact, so it should be used only when necessary. Defaults
to false.Returns Promise<ArrayBufferView<ArrayBufferLike>>: A promise that resolves with the data read from the
storage buffer. Rejects with an AbortError if the read is cancelled, for example by device
loss. Other read failures also reject the promise.
write(bufferOffset?: number, data: ArrayBuffer | ArrayBufferView<ArrayBufferLike>, dataOffset?: number, size?: number): void
Issues a write operation of the provided data into a storage buffer.
Parameters
bufferOffset (number, optional, default 0): The offset in bytes to start writing to the storage buffer.data (ArrayBuffer | ArrayBufferView<ArrayBufferLike>): The data to write to the storage buffer.dataOffset (number, optional, default 0): Offset in data to begin writing from. Given in elements if
data is a TypedArray and bytes otherwise. Defaults to 0.size (number, optional): Size of content to write from data to buffer. Given in elements if
data is a TypedArray and bytes otherwise. Defaults to the remaining size of the data.Class · category: Graphics
Represents a texture, which is typically an image composed of pixels (texels). Textures are fundamental resources for rendering graphical objects. They are commonly used by Materials and sampled in Shaders (usually fragment shaders) to define the visual appearance of a 3D model's surface. Beyond storing color images, textures can hold various data types like normal maps, environment maps (cubemaps), or custom data for shader computations. Key properties control how the texture data is sampled, including filtering modes and coordinate wrapping.
Note on HDR texture format support:
As textures:
As renderable textures that can be used as color buffers in a RenderTarget:
new Texture(graphicsDevice: GraphicsDevice, options?: object)
Create a new Texture instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this texture.options (object, optional, default {}): Object for passing optional arguments.
options.addressU (number, optional): The repeat mode to use in the U direction. Defaults to
ADDRESS_REPEAT.
options.addressV (number, optional): The repeat mode to use in the V direction. Defaults to
ADDRESS_REPEAT.
options.addressW (number, optional): The repeat mode to use in the W direction. Defaults to
ADDRESS_REPEAT.
options.anisotropy (number, optional): The level of anisotropic filtering to use. Defaults
to 1.
options.arrayLength (number, optional): Specifies whether the texture is to be a 2D texture array.
When passed in as undefined or < 1, this is not an array texture. If >= 1, this is an array texture.
Defaults to undefined.
options.compareFunc (number, optional): Comparison function when compareOnRead is enabled.
Can be:
Defaults to FUNC_LESS.
options.compareOnRead (boolean, optional): When enabled, and if texture format is
PIXELFORMAT_DEPTH or PIXELFORMAT_DEPTHSTENCIL, hardware PCF is enabled for
this texture, and you can get filtered results of comparison using texture() in your shader.
Defaults to false.
options.cubemap (boolean, optional): Specifies whether the texture is to be a cubemap.
Defaults to false.
options.depth (number, optional): The number of depth slices in a 3D texture.
options.flipY (boolean, optional): Specifies whether the texture should be flipped in the
Y-direction. Only affects textures with a source that is an image, canvas or video element.
Does not affect cubemaps, compressed textures or textures set from raw pixel data. Defaults
to false.
options.format (number, optional): The pixel format of the texture. Can be:
Defaults to PIXELFORMAT_RGBA8.
options.height (number, optional): The height of the texture in pixels. Defaults to 4.
options.levels (Uint8Array<ArrayBufferLike>[] | Uint8ClampedArray<ArrayBufferLike>[] | Uint16Array<ArrayBufferLike>[] | Uint32Array<ArrayBufferLike>[] | Float32Array<ArrayBufferLike>[] | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | Uint8Array<ArrayBufferLike>[][], optional): Array of Uint8Array or other supported browser interface; or a two-dimensional array
of Uint8Array if options.arrayLength is defined and greater than zero.
options.magFilter (number, optional): The magnification filter type to use. Defaults to
FILTER_LINEAR.
options.minFilter (number, optional): The minification filter type to use. Defaults to
FILTER_LINEAR_MIPMAP_LINEAR.
options.mipmaps (boolean, optional): When enabled try to generate or use mipmaps for this
texture. Default is true.
options.name (string, optional): The name of the texture. Defaults to null.
options.numLevels (number, optional): Specifies the number of mip levels to generate. If not
specified, the number is calculated based on the texture size. When this property is set,
the mipmaps property is ignored.
options.premultiplyAlpha (boolean, optional): If true, the alpha channel of the texture (if
present) is multiplied into the color channels. Defaults to false.
options.projection (string, optional): The projection type of the texture, used when the
texture represents an environment. Can be:
Defaults to TEXTUREPROJECTION_CUBE if options.cubemap is true, otherwise TEXTUREPROJECTION_NONE.
options.samples (number, optional): The number of MSAA samples. A value greater than 1
creates a multisampled texture (WebGPU only, ignored with a warning on other devices, and
rounded up to the device's supported sample count). A multisampled texture can only be
rendered into, and its individual samples read in a shader using textureLoad - it cannot
be sampled with a sampler, uploaded to or read back. It must be a 2D non-array
texture with a format that supports multisampling, cannot be a storage texture, and has no
mipmaps (the mipmaps option is ignored). Defaults to 1.
options.srgb (boolean, optional): When true, the texture is created in the sRGB variant of
the requested format, if one exists, and is automatically converted to linear space when
sampled. When the format has no sRGB variant, this option is ignored. Defaults to false.
options.storage (boolean, optional): Defines if texture can be used as a storage texture by
a compute shader. Defaults to false.
options.type (string, optional): Specifies the texture type. Can be:
Defaults to TEXTURETYPE_DEFAULT.
options.volume (boolean, optional): Specifies whether the texture is to be a 3D volume.
Defaults to false.
options.width (number, optional): The width of the texture in pixels. Defaults to 4.
Example
// Create a 8x8x24-bit texture
const texture = new Texture(graphicsDevice, {
width: 8,
height: 8,
format: PIXELFORMAT_RGB8
});
// Fill the texture with a gradient
const pixels = texture.lock();
const count = 0;
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
pixels[count++] = i * 32;
pixels[count++] = j * 32;
pixels[count++] = 255;
}
}
texture.unlock();
protected _invalid: boolean = false
protected _lockedLevel: number = -1
protected _lockedMode: number = TEXTURELOCK_NONE
protected _numLevels: number = 0
protected _numLevelsRequested: number | undefined
protected _samples: number = 1
The number of MSAA samples of the texture, 1 if not multisampled.
protected _storage: boolean = false
protected id: number
name: string
The name of the texture.
get addressU(): number
set addressU(v: number)
Gets the addressing mode to be applied to the texture horizontally.
get addressV(): number
set addressV(v: number)
Gets the addressing mode to be applied to the texture vertically.
get addressW(): number
set addressW(addressW: number)
Gets the addressing mode to be applied to the 3D texture depth.
get anisotropy(): number
set anisotropy(v: number)
Gets the integer value specifying the level of anisotropy to apply to the texture.
get array(): boolean
Returns true if this texture is a 2D texture array and false otherwise.
get arrayLength(): number
Returns the number of textures inside this texture if this is a 2D array texture or 0 otherwise.
get compareFunc(): number
set compareFunc(v: number)
Gets the comparison function when compareOnRead is enabled.
get compareOnRead(): boolean
set compareOnRead(v: boolean)
Gets whether you can get filtered results of comparison using texture() in your shader.
get cubemap(): boolean
Returns true if this texture is a cube map and false otherwise.
get depth(): number
The number of depth slices in a 3D texture.
get flipY(): boolean
set flipY(flipY: boolean)
Gets whether the texture should be flipped in the Y-direction.
get format(): number
The pixel format of the texture. Can be:
get height(): number
The height of the texture in pixels.
get magFilter(): number
set magFilter(v: number)
Gets the magnification filter to be applied to the texture.
get minFilter(): number
set minFilter(v: number)
Gets the minification filter to be applied to the texture.
get mipmaps(): boolean
set mipmaps(v: boolean)
Gets whether the texture should generate/upload mipmaps.
get numLevels(): number
Gets the number of mip levels.
get pot(): boolean
Returns true if all dimensions of the texture are power of two, and false otherwise.
get samples(): number
The number of MSAA samples of the texture, 1 if the texture is not multisampled. Specified
via the samples constructor option (WebGPU only). A multisampled texture can only be
rendered into, and its individual samples read in a shader using textureLoad.
get srgb(): boolean
Returns true if the texture is stored in an sRGB format, meaning it will be converted to linear space when sampled. Returns false if the texture is stored in a linear format.
get storage(): boolean
Defines if texture can be used as a storage texture by a compute shader.
get volume(): boolean
Returns true if this texture is a 3D volume and false otherwise.
get width(): number
The width of the texture in pixels.
copy(source: Texture, options?: object): boolean
Copies a region of a source texture into this texture. Both textures must have the same pixel format. The copied region sizes must match (no scaling), and must lie within the chosen mip levels of both textures. Multisampled textures can be copied to other multisampled textures with the same sample count (WebGPU only), but only as a full-texture copy - no offsets or partial regions, and no copies between different sample counts (use a resolve instead).
Parameters
source (Texture): The source texture to copy from.options (object, optional, default {}): Optional arguments.
options.destMipLevel (number, optional): The destination mip level to copy to. Defaults to 0.options.destX (number, optional): The left edge of the destination region. Defaults to 0.options.destY (number, optional): The top edge of the destination region. Defaults to 0.options.face (number, optional): The cubemap face or array layer to copy (applies to both
source and destination). Defaults to 0.options.height (number, optional): The height of the copied region. Defaults to the full
height of the source mip level (minus sourceY).options.sourceMipLevel (number, optional): The source mip level to copy from. Defaults to 0.options.sourceRenderTarget (RenderTarget, optional): A render target wrapping the source
texture as its color buffer, at the matching face / mip level. Provide as an optimization to
avoid allocating a temporary one when copying with high frequency (per frame). Note that this
is only utilized on the WebGL platform, and ignored on WebGPU.options.sourceX (number, optional): The left edge of the source region. Defaults to 0.options.sourceY (number, optional): The top edge of the source region. Defaults to 0.options.width (number, optional): The width of the copied region. Defaults to the full width
of the source mip level (minus sourceX).Returns boolean: True if the copy was successful, false otherwise.
destroy(): void
Frees resources associated with this texture.
getSource(mipLevel?: number): HTMLImageElement
Get the pixel data of the texture. If this is a cubemap then an array of 6 images will be returned otherwise a single image.
Parameters
mipLevel (number, optional, default 0): A non-negative integer specifying the image level of detail.
Defaults to 0, which represents the base image source. A level value of N, that is greater
than 0, represents the image source for the Nth mipmap reduction level.Returns HTMLImageElement: The source image of this texture. Can be null if source not
assigned for specific image level.
getView(baseMipLevel?: number, mipLevelCount?: number, baseArrayLayer?: number, arrayLayerCount?: number): TextureView
Creates a TextureView for this texture, specifying a subset of mip levels and array layers. TextureViews can be used with compute shaders to access specific portions of a texture.
Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound.
Parameters
baseMipLevel (number, optional, default 0): The first mip level accessible to the view. Defaults to 0.mipLevelCount (number, optional, default 1): The number of mip levels accessible to the view. Defaults
to 1.baseArrayLayer (number, optional, default 0): The first array layer accessible to the view. Defaults to
0.arrayLayerCount (number, optional, default 1): The number of array layers accessible to the view.
Defaults to 1.Returns TextureView: A new TextureView for this texture.
Example
// Create a view for mip level 1
const mip1View = texture.getView(1);
// Use with compute shader
compute.setParameter('outputTexture', mip1View);
lock(options?: object): Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>
Locks a miplevel of the texture, returning a typed array to be filled with pixel data.
Parameters
options (object, optional, default {}): Optional options object. Valid properties are as follows:
options.face (number, optional): If the texture is a cubemap, this is the index of the face
to lock.options.level (number, optional): The mip level to lock with 0 being the top level. Defaults
to 0.options.mode (number, optional): The lock mode. Can be:
Returns Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>: A typed array containing the pixel data of
the locked mip level.
read(x: number, y: number, width: number, height: number, options?: object): Promise<Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>>
Download the textures data from the graphics memory to the local memory.
Parameters
x (number): The left edge of the rectangle.y (number): The top edge of the rectangle.width (number): The width of the rectangle.height (number): The height of the rectangle.options (object, optional, default {}): Object for passing optional arguments.
options.data (Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>, optional): The data buffer to
write the pixel data to. If not provided, a new buffer will be created. The type of the buffer
must match the texture's format.options.face (number, optional): The face to download. Defaults to 0.options.frequent (boolean, optional): Set this when the read is one of many, issued every
frame or every few frames. Such a read is given the treatment which costs it a frame of
latency and keeps it from stalling the frame it is issued in, which is the trade a one-off
read would not want. Only utilized on the WebGL platform, where a readback has a blocking
step; ignored on WebGPU, whose readback does not block. Defaults to false.options.immediate (boolean, optional): If true, the read operation will be executed as soon as
possible. This has a performance impact, so it should be used only when necessary. Defaults
to false.options.mipLevel (number, optional): The mip level to download. Defaults to 0.options.renderTarget (RenderTarget, optional): The render target using the texture as a color
buffer. Provide as an optimization to avoid creating a new render target. Important especially
when this function is called with high frequency (per frame). Note that this is only utilized
on the WebGL platform, and ignored on WebGPU.Returns Promise<Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>>: A promise that resolves
with the pixel data of the texture.
setSource(source: HTMLElement | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | HTMLElement[], mipLevel?: number): void
Set the pixel data of the texture from a canvas, image, video, or HTML DOM element. If the texture is a cubemap, the supplied source must be an array of 6 canvases, images or videos.
Note: using an HTML element (e.g. <div>) as a source requires
GraphicsDevice#supportsHtmlTextures to be true.
Parameters
source (HTMLElement | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | HTMLElement[]): A
canvas, image, video, or HTML element, or an array of 6 canvas, image, video, or HTML
elements.mipLevel (number, optional, default 0): A non-negative integer specifying the image level of detail.
Defaults to 0, which represents the base image source. A level value of N, that is greater
than 0, represents the image source for the Nth mipmap reduction level.unlock(): void
Unlocks the currently locked mip level and uploads it to VRAM.
upload(): void
Forces a reupload of the texture's pixel data to graphics memory. Ordinarily, this function is called internally by setSource and unlock. However, it still needs to be called explicitly in the case where an HTMLVideoElement is set as the source of the texture. Normally, this is done once every frame before video textured geometry is rendered.
Class · extends EventHandler · category: Graphics
A TextureAtlas contains a number of frames from a texture. Each frame defines a region in a texture. The TextureAtlas is referenced by Sprites.
new TextureAtlas()
Create a new TextureAtlas instance.
Example
const atlas = new TextureAtlas();
atlas.frames = {
'0': {
// rect has u, v, width and height in pixels
rect: new Vec4(0, 0, 256, 256),
// pivot has x, y values between 0-1 which define the point
// within the frame around which rotation and scale is calculated
pivot: new Vec2(0.5, 0.5),
// border has left, bottom, right and top in pixels defining regions for 9-slicing
border: new Vec4(5, 5, 5, 5)
},
'1': {
rect: new Vec4(256, 0, 256, 256),
pivot: new Vec2(0.5, 0.5),
border: new Vec4(5, 5, 5, 5)
}
};
get frames(): any
set frames(value: any)
Gets the frames which define portions of the texture atlas.
get texture(): Texture
set texture(value: Texture)
Gets the texture used by the atlas.
destroy(): void
Free up the underlying texture owned by the atlas.
removeFrame(key: string): void
Removes a frame from the texture atlas.
Parameters
key (string): The key of the frame.Example
atlas.removeFrame('1');
setFrame(key: string, data: object): void
Set a new frame in the texture atlas.
Parameters
key (string): The key of the frame.data (object): The properties of the frame.
Example
atlas.setFrame('1', {
rect: new Vec4(0, 0, 128, 128),
pivot: new Vec2(0.5, 0.5),
border: new Vec4(5, 5, 5, 5)
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Graphics
Interface to a texture parser. Implementations of this interface handle the loading and opening of texture assets.
load(url: object, callback: ResourceHandlerCallback, asset?: Asset<string>): void
Load the texture from the remote URL. When loaded (or failed), use the callback to return an the raw resource data (or error).
Parameters
url (object): The URL of the resource to load.
url.load (string): The URL to use for loading the resource.url.original (string): The original URL useful for identifying the resource type.callback (ResourceHandlerCallback): The callback used when the resource is loaded or
an error occurs.asset (Asset<string>, optional): Optional asset that is passed by ResourceLoader.open(url: string, data: any, device: GraphicsDevice): Texture
Convert raw resource data into a Texture.
Parameters
url (string): The URL of the resource to open.data (any): The raw resource data passed by callback from ResourceHandler#load.device (GraphicsDevice): The graphics device.Returns Texture: The parsed resource data.
Class · category: Graphics
Displays textures for a single frame, for debugging. Call draw or sceneDepth during update or prerender on every frame the preview should be visible. Positions specify the top-left corner in normalized camera-viewport coordinates: (0, 0) is top-left and (1, 1) is bottom-right. Width and height are fractions of the viewport; a rectangle of (0, 0, 1, 1) fills it. Signed sizes can flip a preview, and rectangles can extend outside the viewport.
Supports 2D color textures in normalized, floating-point and device-supported compressed formats. Linear and sRGB color, and RGBM, RGBE and RGBP encoded HDR color, are detected automatically with the default channels selection, and single-channel formats such as PIXELFORMAT_R8 display their channel as grayscale. Other selections display stored channel values, including alpha, as opaque previews.
Depth textures using PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTH16 or PIXELFORMAT_DEPTHSTENCIL are displayed as raw grayscale values. Use sceneDepth to display the rendering camera's scene depth, linearized and normalized by its far clip distance. The camera must have scene depth capture enabled.
Cube, volume, array, integer and multisampled textures are not supported. On WebGL2, raw depth textures must have comparison sampling disabled, and both raw depth and non-filterable float textures require nearest minification and magnification filters. WebGPU supports these textures regardless of their filtering and comparison sampler settings.
Resources are released automatically when the application is destroyed, or earlier by calling destroy. Supplied textures are never destroyed by this helper.
Previews produce fully opaque pixels but are drawn as alpha-blended instances, so they render in layers that only draw their transparent sub-layer, such as the default UI layer, which is also where they escape a camera frame's post-processing. They do not write or test depth and do not cast shadows. Ordering against other transparent geometry follows the destination layer's transparent sort mode.
Every camera rendering the destination layer draws the previews, including cameras rendering into a texture. Set camera to limit them to a single camera, typically the one rendering to the screen. A render pass whose target has the previewed texture among its attachments never draws that preview: sampling a texture while rendering into it is undefined on WebGL and an error on WebGPU. Both rules are applied as each layer is rendered, against the target the pass really renders into, so they hold for camera frames and custom render passes and do not depend on frustum culling.
Example
const textures = new TextureRenderer(app);
app.on('update', () => {
textures.draw(texture, 0.7, 0.7, 0.25, 0.25);
});
Example
// camera is an entity with a camera component.
camera.camera.requestSceneDepthMap(true);
const textures = new TextureRenderer(app);
app.on('update', () => {
textures.sceneDepth(0.7, 0.7, 0.25, 0.25);
});
new TextureRenderer(app: AppBase)
Creates a debug texture renderer.
Parameters
app (AppBase): The application to render into and bind resource lifetime to.camera: CameraComponent | null = null
The only camera that draws the previews, or null to let every camera rendering the destination layer draw them. Defaults to null.
layer: Layer | null = null
The layer used by subsequent draw calls, or null to use the application's default debug drawing layer (normally Immediate). Defaults to null.
set channels(value: string)
Channels displayed by subsequent draw calls. Must be exactly three characters from 'r', 'g', 'b' and 'a'. Defaults to 'rgb', which displays automatically decoded color, or the stored channel as grayscale for single-channel formats. Other selections display stored channel values without color decoding: for example, 'rrr' displays red as grayscale, 'aaa' displays alpha, and 'bgr' swaps red and blue. Values from 0 to 1 map directly from black to white. Output is always opaque. Ignored for depth textures and sceneDepth. Invalid values leave the previous selection unchanged.
Example
textures.channels = 'aaa';
textures.draw(texture, 0, 0, 0.25, 0.25);
destroy(): void
Removes all previews and releases the renderer's resources. Does not destroy supplied textures. Safe to call repeatedly; subsequent draw calls are ignored.
draw(texture: Texture, x: number, y: number, width: number, height: number): void
Displays a 2D color or depth texture for this frame. Color encoding and supported filtering are detected automatically when channels is 'rgb'. Other selections display stored channel values. Raw depth is shown as grayscale without projection-dependent linearization; use sceneDepth for camera depth. Texture row 0 is displayed at the top. For rendered textures, use RENDERTARGET_ORIGIN_TOP on their render target for consistent orientation across backends.
Cube, volume, array, integer and multisampled textures are not supported. On WebGL2, depth textures must have comparison sampling disabled. Raw depth and non-filterable float textures must use nearest minification and magnification filters on WebGL2. WebGPU samples these textures independently of their filtering and comparison sampler settings.
Parameters
texture (Texture): The caller-owned texture to display.x (number): Left edge as a fraction of the camera viewport width.y (number): Top edge as a fraction of the camera viewport height.width (number): Width as a fraction of the camera viewport width.height (number): Height as a fraction of the camera viewport height.sceneDepth(x: number, y: number, width: number, height: number): void
Displays the rendering camera's scene depth for this frame, linearized and normalized by its far clip distance. The camera must already supply a scene depth map, for example using CameraComponent#requestSceneDepthMap, and this layer must render after depth capture.
Parameters
x (number): Left edge as a fraction of the camera viewport width.y (number): Top edge as a fraction of the camera viewport height.width (number): Width as a fraction of the camera viewport width.height (number): Height as a fraction of the camera viewport height.Class · category: Graphics
A TextureView specifies a texture and a subset of its mip levels and array layers. It is used when binding textures to compute shaders to specify which portion of the texture should be accessed. Create a TextureView using Texture#getView.
Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound and this class has no effect.
readonly arrayLayerCount: number
The number of array layers accessible to the view.
readonly baseArrayLayer: number
The first array layer accessible to the view.
readonly baseMipLevel: number
The first mip level accessible to the view.
readonly mipLevelCount: number
The number of mip levels accessible to the view.
readonly texture: Texture
The texture this view references.
Class · extends Geometry · category: Graphics
A procedural torus-shaped geometry.
Typically, you would:
// Create a mesh instance
const geometry = new TorusGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);
// Create an entity
const entity = new Entity();
entity.addComponent('render', {
meshInstances: [meshInstance]
});
// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);
new TorusGeometry(opts?: object)
Create a new TorusGeometry instance.
By default, the constructor creates a torus in the XZ-plane with a tube radius of 0.2, a ring radius of 0.3, 30 segments and 20 sides. The torus is created with UVs in the range of 0 to 1.
Parameters
opts (object, optional, default {}): Options object.
opts.calculateTangents (boolean, optional): Generate tangent information. Defaults to false.opts.ringRadius (number, optional): The radius from the centre of the torus to the centre of the
tube. Defaults to 0.3.opts.sectorAngle (number, optional): The sector angle in degrees of the ring of the torus.
Defaults to 2 * Math.PI.opts.segments (number, optional): The number of radial divisions forming cross-sections of the
torus ring. Defaults to 20.opts.sides (number, optional): The number of divisions around the tubular body of the torus ring.
Defaults to 30.opts.tubeRadius (number, optional): The radius of the tube forming the body of the torus.
Defaults to 0.2.Example
const geometry = new TorusGeometry({
tubeRadius: 1,
ringRadius: 2,
sectorAngle: 360,
segments: 30,
sides: 20
});
blendIndices: ArrayLike<number> | undefinedblendWeights: ArrayLike<number> | undefinedcolors: ArrayLike<number> | undefinedtangents: ArrayLike<number> | undefinedcalculateNormals(): voidcalculateTangents(): voidClass · category: Graphics
This object allows you to configure and use the transform feedback feature (WebGL2 only). How to use:
out vec3 out_vertex_position,
note that there must be out_ in the name. You can then simply assign values to these outputs in
VS. The order and size of shader outputs must match the output buffer layout.TransformFeedback.createShader(device, vsCode, yourShaderName).const tf = new TransformFeedback(inputBuffer). This
object will internally create an output buffer.tf.process(shader). Shader will take the input buffer, process it and write
to the output buffer, then the input/output buffers will be automatically swapped, so you'll
immediately see the result.// *** shader asset ***
attribute vec3 vertex_position;
attribute vec3 vertex_normal;
attribute vec2 vertex_texCoord0;
out vec3 out_vertex_position;
out vec3 out_vertex_normal;
out vec2 out_vertex_texCoord0;
void main(void) {
// read position and normal, write new position (push away)
out_vertex_position = vertex_position + vertex_normal * 0.01;
// pass other attributes unchanged
out_vertex_normal = vertex_normal;
out_vertex_texCoord0 = vertex_texCoord0;
}
// *** script asset ***
var TransformExample = createScript('transformExample');
// attribute that references shader asset and material
TransformExample.attributes.add('shaderCode', { type: 'asset', assetType: 'shader' });
TransformExample.attributes.add('material', { type: 'asset', assetType: 'material' });
TransformExample.prototype.initialize = function() {
const device = this.app.graphicsDevice;
const mesh = Mesh.fromGeometry(app.graphicsDevice, new TorusGeometry({ tubeRadius: 0.01, ringRadius: 3 }));
const meshInstance = new MeshInstance(mesh, this.material.resource);
const entity = new Entity();
entity.addComponent('render', {
type: 'asset',
meshInstances: [meshInstance]
});
app.root.addChild(entity);
// if webgl2 is not supported, transform-feedback is not available
if (!device.isWebGL2) return;
const inputBuffer = mesh.vertexBuffer;
this.tf = new TransformFeedback(inputBuffer);
this.shader = TransformFeedback.createShader(device, this.shaderCode.resource, "tfMoveUp");
};
TransformExample.prototype.update = function(dt) {
if (!this.app.graphicsDevice.isWebGL2) return;
this.tf.process(this.shader);
};
new TransformFeedback(inputBuffer: VertexBuffer | TransformFeedbackStream[], outputBuffer?: VertexBuffer, usage?: number)
Create a new TransformFeedback instance.
Parameters
inputBuffer (VertexBuffer | TransformFeedbackStream[]): The input vertex buffer, or an
array of buffer descriptors when more than one buffer takes part. Each descriptor gives a
buffer one of three roles:
{ input, output } - read by the shader and written by transform feedback. The pair is
swapped after each step, so input always holds the freshest data.{ input } - read by the shader only. Suitable for per-item data which never changes, and
which would otherwise have to be copied through transform feedback every step.{ output } - written by transform feedback only. Suitable for data which only a later
pass consumes, such as a stream feeding instanced rendering.Descriptors with an output are assigned transform feedback buffer indices in the order they
appear, skipping those without one, and so must match the order of the captured varyings.
outputBuffer (VertexBuffer, optional): The optional output buffer, when a single input buffer
is specified. If omitted, a buffer with parameters matching the input buffer is created.
usage (number, optional, default BUFFER_GPUDYNAMIC): The optional usage type of the created output vertex buffer. Can be:
Defaults to BUFFER_GPUDYNAMIC (which is recommended for continuous update).
Example
// a simulation writing its state back to itself, plus a stream consumed by instancing
const tf = new TransformFeedback([
{ input: positions, output: positionsOut }, // read and written, swapped each step
{ input: constants }, // read only, never modified
{ output: instances } // written only, for the render pass
]);
get inputBuffer(): VertexBuffer
The current input buffer. When multiple input buffers are used, this is the first one - see TransformFeedback#inputBuffers.
get inputBuffers(): VertexBuffer[]
The buffers read by the shader, in the order they were supplied.
get outputBuffer(): VertexBuffer
The current output buffer. When multiple output buffers are used, this is the first one - see TransformFeedback#outputBuffers.
get outputBuffers(): VertexBuffer[]
The buffers written by transform feedback, in the order of the captured varyings.
destroy(): void
Destroys the transform feedback helper object.
process(shader: Shader, swap?: boolean): void
Runs the specified shader on the input buffer, writes results into the new buffer, then optionally swaps input/output.
Parameters
shader (Shader): A vertex shader to run. Should be created with
TransformFeedback.createShader.swap (boolean, optional, default true): Swap input/output buffer data. Useful for continuous buffer
processing. Default is true.static createShader(graphicsDevice: GraphicsDevice, vertexCode: string, name: string, feedbackVaryings?: string[], feedbackVaryingsMode?: number): Shader
Creates a transform feedback ready vertex shader from code.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used by the renderer.vertexCode (string): Vertex shader code. Should contain output variables starting with "out_" or feedbackVaryings.name (string): Unique name for caching the shader.feedbackVaryings (string[], optional): A list of shader output variable names that will be captured.feedbackVaryingsMode (number, optional, default TRANSFORM_FEEDBACK_INTERLEAVED): Specifies how transform feedback varyings
are written into GPU buffers. Use TRANSFORM_FEEDBACK_INTERLEAVED to pack all captured
varyings into a single buffer, or TRANSFORM_FEEDBACK_SEPARATE to store each varying
in its own buffer. This setting is only effective when useTransformFeedback property is enabled.
Defaults to TRANSFORM_FEEDBACK_INTERLEAVED.Returns Shader: A shader to use in the process() function.
Class · category: Graphics
A descriptor that defines the layout of data inside the uniform buffer.
new UniformBufferFormat(graphicsDevice: GraphicsDevice, uniforms: UniformFormat[], options?: object)
Create a new UniformBufferFormat instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device.uniforms (UniformFormat[]): An array of uniforms to be stored in the buffer.options (object, optional, default {}): Options.
options.pack (boolean, optional): Reorder the uniforms to minimize the padding of the std140
layout: uniforms occupying whole 16-byte rows first (vec4, matrices and arrays), then each
vec3 followed by a scalar, then vec2s and the remaining scalars. The uniforms of the format
are then in layout order rather than in the order of the array. Only use it when the shader
declaration of the buffer is generated from this format, and never against a hand-written
declaration, whose member order has to match the array. Defaults to false.uniforms: UniformFormat[]
get(name: string): UniformFormat | undefined
Returns format of a uniform with specified name. Returns undefined if the uniform is not found.
Parameters
name (string): The name of the uniform.Returns UniformFormat | undefined: - The format of the uniform.
Class · category: Graphics
A class storing description of an individual uniform, stored inside a uniform buffer.
new UniformFormat(name: string, type: number, count?: number)
Create a new UniformFormat instance.
Parameters
name (string): The name of the uniform.type (number): The type of the uniform. One of the UNIFORMTYPE_*** constants.count (number, optional, default 0): The number of elements in the array. Defaults to 0, which represents
a single element (not an array).get isArrayType(): boolean
True if this is an array of elements (i.e. count > 0)
Class · category: Graphics
A vertex buffer is the mechanism via which the application specifies vertex data to the graphics hardware.
new VertexBuffer(graphicsDevice: GraphicsDevice, format: VertexFormat, numVertices: number, options?: object, ...args: any[])
Create a new VertexBuffer instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this vertex
buffer.format (VertexFormat): The vertex format of this vertex buffer.numVertices (number): The number of vertices that this vertex buffer will hold.options (object, optional): Object for passing optional arguments.
options.data (ArrayBuffer | ArrayBufferView<ArrayBufferLike>, optional): Initial data. Can be an
ArrayBuffer or a typed array (for example a Float32Array). The data is
stored by reference and is not copied, so a typed array that is a view into a larger buffer
is kept as-is. If left unspecified, the vertex buffer will be initialized to zeros.options.storage (boolean, optional): Defines if the vertex buffer can be used as a storage
buffer by a compute shader. Defaults to false. Only supported on WebGPU.options.usage (number, optional): The usage type of the vertex buffer (see BUFFER_*).
Defaults to BUFFER_STATIC.args (any[])destroy(): void
Frees resources associated with this vertex buffer.
getFormat(): VertexFormat
Returns the data format of the specified vertex buffer.
Returns VertexFormat: The data format of the specified vertex buffer.
getNumVertices(): number
Returns the number of vertices stored in the specified vertex buffer.
Returns number: The number of vertices stored in the vertex buffer.
getUsage(): number
Returns the usage type of the specified vertex buffer. This indicates whether the buffer can be modified once and used many times BUFFER_STATIC, modified repeatedly and used many times BUFFER_DYNAMIC or modified once and used at most a few times BUFFER_STREAM.
Returns number: The usage type of the vertex buffer (see BUFFER_*).
lock(): ArrayBuffer | ArrayBufferView<ArrayBufferLike>
Returns a mapped memory block representing the content of the vertex buffer.
Returns ArrayBuffer | ArrayBufferView<ArrayBufferLike>: The memory that stores the buffer's vertices. This
matches whatever was supplied as the initial data: an ArrayBuffer when none was
provided, otherwise the ArrayBuffer or typed array that was passed in. Use
ArrayBufferConstructor.isView to distinguish the two before accessing it.
setData(data?: ArrayBuffer | ArrayBufferView<ArrayBufferLike>): boolean
Sets the data of the vertex buffer and uploads it to the GPU.
Parameters
data (ArrayBuffer | ArrayBufferView<ArrayBufferLike>, optional): Source data. Can be an ArrayBuffer or
a typed array. Stored by reference, not copied.Returns boolean: True if function finished successfully, false otherwise.
unlock(byteOffset?: number, byteLength?: number): void
Uploads the client side copy of the vertex buffer to the GPU. When called without arguments, uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. The first upload always initializes the entire GPU buffer, regardless of the requested range. A zero byte length does nothing, including before the first upload.
Partial uploads do not resize the buffer or change its CPU storage. The caller must upload every modified range before expecting those changes on the GPU. Context restoration uploads the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion in debug builds.
Parameters
byteOffset (number, optional): Offset in bytes from the start of the buffer's storage.
Defaults to 0. Must be a non-negative integer and a multiple of 4 on all graphics backends.byteLength (number, optional): Number of bytes to upload. Defaults to the remaining bytes
after byteOffset. The length must be a non-negative integer and the range must fit within
the buffer. Partial ranges require a length that is a multiple of 4. Full-buffer uploads
support any byte length, whether the range is explicit or the arguments are omitted.Example
// After modifying bytes 16 through 31 of the CPU storage:
vertexBuffer.unlock(16, 16);
Class · category: Graphics
A vertex format is a descriptor that defines the layout of vertex data inside a VertexBuffer.
new VertexFormat(graphicsDevice: GraphicsDevice, description: AttributeDescription[], vertexCount?: number)
Create a new VertexFormat instance.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to manage this vertex
format.description (AttributeDescription[]): An array of vertex attribute descriptions.vertexCount (number, optional): When specified, vertex format will be set up for
non-interleaved format with a specified number of vertices. (example: PPPPNNNNCCCC), where
arrays of individual attributes will be stored one right after the other (subject to
alignment requirements). Note that in this case, the format depends on the number of
vertices, and needs to change when the number of vertices changes. When not specified,
vertex format will be interleaved. (example: PNCPNCPNCPNC).Example
// Specify 3-component positions (x, y, z)
const vertexFormat = new VertexFormat(graphicsDevice, [
{ semantic: SEMANTIC_POSITION, components: 3, type: TYPE_FLOAT32 }
]);
Example
// Specify 2-component positions (x, y), a texture coordinate (u, v) and a vertex color (r, g, b, a)
const vertexFormat = new VertexFormat(graphicsDevice, [
{ semantic: SEMANTIC_POSITION, components: 2, type: TYPE_FLOAT32 },
{ semantic: SEMANTIC_TEXCOORD0, components: 2, type: TYPE_FLOAT32 },
{ semantic: SEMANTIC_COLOR, components: 4, type: TYPE_UINT8, normalize: true }
]);
hasUv(index: number): boolean
Returns true if the format contains the texture coordinate set with the specified index.
Parameters
index (number): The index of the texture coordinate set, from 0 for
SEMANTIC_TEXCOORD0 to 7 for SEMANTIC_TEXCOORD7.Returns boolean: True if the format contains the texture coordinate set.
static getDefaultInstancingFormat(graphicsDevice: GraphicsDevice): VertexFormat
The VertexFormat used to store matrices of type Mat4 for hardware instancing. The matrix rows use SEMANTIC_ATTR11, SEMANTIC_ATTR12, SEMANTIC_ATTR14 and SEMANTIC_ATTR15. The first two share their attribute locations with SEMANTIC_TEXCOORD6 and SEMANTIC_TEXCOORD7, so a shader reading those texture coordinate sets needs a custom instancing format on other attributes.
Parameters
graphicsDevice (GraphicsDevice): The graphics device used to create this vertex
format.Returns VertexFormat: The default instancing vertex format.
Class · category: Graphics
A vertex iterator simplifies the process of writing vertex data to a vertex buffer.
new VertexIterator(vertexBuffer: VertexBuffer)
Create a new VertexIterator instance.
Parameters
vertexBuffer (VertexBuffer): The vertex buffer to be iterated.element: {}
The vertex buffer elements.
end(): void
Notifies the vertex buffer being iterated that writes are complete. Internally the vertex buffer is unlocked and vertex data is uploaded to video memory.
Example
const iterator = new VertexIterator(vertexBuffer);
iterator.element[SEMANTIC_POSITION].set(-0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(255, 0, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 255, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.0, 0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 0, 255, 255);
iterator.end();
next(count?: number): void
Moves the vertex iterator on to the next vertex.
Parameters
count (number, optional, default 1): Number of steps to move on when calling next. Defaults to 1.Example
const iterator = new VertexIterator(vertexBuffer);
iterator.element[SEMANTIC_POSITION].set(-0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(255, 0, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 255, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.0, 0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 0, 255, 255);
iterator.end();
Class · extends GraphicsDevice · category: Graphics
WebglGraphicsDevice extends the base GraphicsDevice to provide rendering capabilities utilizing the WebGL 2.0 specification.
new WebglGraphicsDevice(canvas: HTMLCanvasElement, options?: object)
Creates a new WebglGraphicsDevice instance.
Parameters
canvas (HTMLCanvasElement): The canvas to which the graphics device will render.options (object, optional, default {}): Options passed when creating the WebGL context.
options.alpha (boolean, optional): Boolean that indicates if the canvas contains an
alpha buffer. Defaults to true.
options.antialias (boolean, optional): Boolean that indicates whether or not to perform
anti-aliasing if possible. Defaults to true.
options.depth (boolean, optional): Boolean that indicates that the drawing buffer is
requested to have a depth buffer of at least 16 bits. Defaults to true.
options.desynchronized (boolean, optional): Boolean that hints the user agent to reduce the
latency by desynchronizing the canvas paint cycle from the event loop. Defaults to false.
options.failIfMajorPerformanceCaveat (boolean, optional): Boolean that indicates if a
context will be created if the system performance is low or if no hardware GPU is available.
Defaults to false.
options.gl (WebGL2RenderingContext, optional): The rendering context
to use. If not specified, a new context will be created.
options.powerPreference ("default" | "high-performance" | "low-power", optional): A hint to the
user agent indicating what configuration of GPU is suitable for the WebGL context. Possible
values are:
Defaults to 'default'.
options.premultipliedAlpha (boolean, optional): Boolean that indicates that the page
compositor will assume the drawing buffer contains colors with pre-multiplied alpha.
Defaults to true.
options.preserveDrawingBuffer (boolean, optional): If the value is true the buffers will not
be cleared and will preserve their values until cleared or overwritten by the author.
Defaults to false.
options.stencil (boolean, optional): Boolean that indicates that the drawing buffer is
requested to have a stencil buffer of at least 8 bits. Defaults to true.
options.xrCompatible (boolean, optional): Boolean that hints to the user agent to use a
compatible graphics adapter for an immersive XR device.
transformFeedbackBuffers: VertexBuffer[] | null | undefined
get fullscreen(): boolean
set fullscreen(fullscreen: boolean)
Gets whether the device is currently in fullscreen mode.
clear(options?: object): void
Clears the frame buffer of the currently set render target.
Parameters
options (object, optional): Optional options object that controls the behavior of the clear
operation defined as follows:
options.color (number[], optional): The color to clear the color buffer to in the range 0 to
1 for each component.
options.depth (number, optional): The depth value to clear the depth buffer to in the
range 0 to 1. Defaults to 1.
options.flags (number, optional): The buffers to clear (the types being color, depth and
stencil). Can be any bitwise combination of:
options.stencil (number, optional): The stencil value to clear the stencil buffer to.
Defaults to 0.
Example
// Clear color buffer to black and depth buffer to 1
device.clear();
// Clear just the color buffer to red
device.clear({
color: [1, 0, 0, 1],
flags: CLEARFLAG_COLOR
});
// Clear color buffer to yellow and depth to 1.0
device.clear({
color: [1, 1, 0, 1],
depth: 1,
flags: CLEARFLAG_COLOR | CLEARFLAG_DEPTH
});
copyRenderTarget(source?: RenderTarget, dest?: RenderTarget, color?: boolean, depth?: boolean): boolean
Copies source render target into destination render target. Mostly used by post-effects.
Parameters
source (RenderTarget, optional): The source render target. Defaults to frame buffer.dest (RenderTarget, optional): The destination render target. Defaults to frame buffer.color (boolean, optional): If true, will copy the color buffer. Defaults to false.depth (boolean, optional): If true, will copy the depth buffer. Defaults to false.Returns boolean: True if the copy was successful, false otherwise.
destroy(): void
Destroy the graphics device.
postInit(): void
Function that executes after the device has been created.
setBindGroup(index: number, bindGroup: BindGroup, offsets?: Uint32Array<ArrayBufferLike>): void
Parameters
index (number): Index of the bind group slotbindGroup (BindGroup): Bind group to attachoffsets (Uint32Array<ArrayBufferLike>, optional): Byte offsets for all uniform buffers in the bind group. Unused
on WebGL: every uniform buffer is bound as a whole buffer from offset zero (see below).setBlendState(blendState: any): void
Sets the specified blend state.
Parameters
blendState (any): New blend state.setCullMode(cullMode: any): void
Controls how triangles are culled based on their face direction. The default cull mode is CULLFACE_BACK.
Parameters
cullMode (any): The cull mode to set. Can be:
setDepthState(depthState: any): void
Sets the specified depth state.
Parameters
depthState (any): New depth state.setFrontFace(frontFace: any): void
Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is FRONTFACE_CCW.
Parameters
frontFace (any): The front face to set. Can be:
setScissor(x: number, y: number, w: number, h: number): void
Set the active scissor rectangle on the specified device.
Parameters
x (number): The pixel space x-coordinate of the bottom left corner of the scissor rectangle.y (number): The pixel space y-coordinate of the bottom left corner of the scissor rectangle.w (number): The width of the scissor rectangle in pixels.h (number): The height of the scissor rectangle in pixels.setShader(shader: Shader, asyncCompile?: boolean): void
Sets the active shader to be used during subsequent draw calls.
Parameters
shader (Shader): The shader to assign to the device.asyncCompile (boolean, optional, default false): If true, rendering will be skipped until the shader is
compiled, otherwise the rendering will wait for the shader compilation to finish. Defaults
to false.setStencilState(stencilFront: any, stencilBack: any): void
Sets the specified stencil state. If both stencilFront and stencilBack are null, stencil operation is disabled.
Parameters
stencilFront (any): The front stencil parameters. Defaults to
StencilParameters.DEFAULT if not specified.stencilBack (any): The back stencil parameters. Defaults to
StencilParameters.DEFAULT if not specified.setViewport(x: number, y: number, w: number, h: number): void
Set the active rectangle for rendering on the specified device.
Parameters
x (number): The pixel space x-coordinate of the bottom left corner of the viewport.y (number): The pixel space y-coordinate of the bottom left corner of the viewport.w (number): The width of the viewport in pixels.h (number): The height of the viewport in pixels.readonly canvas: HTMLCanvasElementgpuProfiler: GpuProfilerinsideRenderPass: boolean = falseisHdr: boolean = falsereadonly isNull: boolean = falsereadonly isWebGPU: boolean = falsereadonly maxAnisotropy: numberreadonly maxColorAttachments: number = 1readonly maxCubeMapSize: numbermaxIndirectDispatchCount: number = 256maxIndirectDrawCount: number = 1024readonly maxSamples: number = 1readonly maxSubgroupSize: number = 0readonly maxTextureSize: numberreadonly maxVolumeSize: numberreadonly minSubgroupSize: number = 0readonly precision: stringreadonly samples: numberreadonly scope: ScopeSpacesupportsClipDistances: boolean = falsereadonly supportsCompute: boolean = falsereadonly supportsDualSourceBlending: boolean = falsereadonly supportsHtmlTextures: boolean = falsereadonly supportsIndependentBlending: boolean = falsereadonly supportsIndirectDraw: boolean = falsereadonly supportsLinearIndexing: boolean = falsesupportsMultiDraw: boolean = truereadonly supportsPacked4x8IntegerDotProduct: boolean = falsereadonly supportsPointerCompositeAccess: boolean = falsereadonly supportsPrimitiveIndex: boolean = falsereadonly supportsShaderF16: boolean = falsereadonly supportsStorageTextureRead: boolean = falsereadonly supportsSubgroupId: boolean = falsereadonly supportsSubgroups: boolean = falsereadonly supportsSubgroupSizeControl: boolean = falsereadonly supportsSubgroupUniformity: boolean = falsereadonly supportsTextureAndSamplerLet: boolean = falsereadonly supportsTextureFormatsTier1: boolean = falsereadonly supportsTextureFormatsTier2: boolean = falsereadonly supportsTransientAttachments: boolean = falsereadonly supportsUnrestrictedPointerParameters: boolean = falsereadonly textureFloatBlendable: boolean = falsereadonly textureFloatFilterable: boolean = falsereadonly textureFloatRenderable: booleanreadonly textureHalfFloatRenderable: booleanreadonly textureRG11B10Renderable: boolean = falseget deviceType(): "webgl2" | "webgpu"get height(): numberget indirectDispatchBuffer(): StorageBuffer | nullget indirectDrawBuffer(): StorageBuffer | nullget maxPixelRatio(): number · set maxPixelRatio(ratio: number)get width(): numbercomputeDispatch(computes: Compute[], name?: string): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlergetIndirectDispatchSlot(count?: number): numbergetIndirectDrawSlot(count?: number): numbergetRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefinedgetRenderTarget(): RenderTargethasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlesetDrawStates(blendState?: BlendState, depthState?: DepthState, cullMode?: number, frontFace?: number, stencilFront?: StencilParameters, stencilBack?: StencilParameters): voidsetRenderTarget(renderTarget: RenderTarget | null): voidprotected validateAttributes(shader: Shader, vertexBuffers: (VertexBuffer | null | undefined)[]): voidClass · category: Graphics
A connected, variable-width line rendered by a WideLineRenderer. Point data is supplied using packed numeric arrays to avoid allocating an object for each point.
A WideLine can belong to at most one WideLineRenderer. Removing it from the renderer leaves the WideLine intact, allowing it to be added to another renderer later.
get cap(): number
set cap(value: number)
Gets the cap style.
get closed(): boolean
set closed(value: boolean)
Gets whether the last point connects back to the first point.
get dashLength(): number
set dashLength(value: number)
Gets the length of each visible dash in world units.
get dashOffset(): number
set dashOffset(value: number)
Gets the offset of the dash pattern in world units.
get gapLength(): number
set gapLength(value: number)
Gets the length of each gap in world units.
get join(): number
set join(value: number)
Gets the join style.
get pointCount(): number
The number of points in the line. This is zero until WideLine#set is called.
get renderer(): WideLineRenderer | null
The renderer that owns this line, or null when the line is not being rendered.
set(positions: ArrayLike<number>, colors?: ArrayLike<number> | Color, widths?: number | ArrayLike<number>): WideLine
Atomically replaces all point data. This is the only operation that can change the number of points. The colors and widths can each be supplied either per point or as a single uniform value.
Parameters
positions (ArrayLike<number>): Packed xyz coordinates. The length must be a multiple
of three and contain at least two points.colors (ArrayLike<number> | Color, optional, default Color.WHITE): Packed rgb values with one color per point, or a
single color used by every point. The alpha component of a Color is ignored.widths (number | ArrayLike<number>, optional, default 1): One width per point, or a single width used by
every point. Width units are selected by the owning WideLineRenderer and values must
be non-negative.Returns WideLine: This line.
setColors(colors: ArrayLike<number> | Color): WideLine
Replaces colors without changing the number of points.
Parameters
colors (ArrayLike<number> | Color): Packed rgb values containing exactly
pointCount * 3 values, or a single color used by every point. The alpha component of a
Color is ignored.Returns WideLine: This line.
setPositions(positions: ArrayLike<number>): WideLine
Replaces positions without changing the number of points.
Parameters
positions (ArrayLike<number>): Packed xyz coordinates containing exactly
pointCount * 3 values.Returns WideLine: This line.
setWidths(widths: number | ArrayLike<number>): WideLine
Replaces widths without changing the number of points.
Parameters
widths (number | ArrayLike<number>): An array containing exactly pointCount values,
or a single width used by every point. Width units are selected by the owning
WideLineRenderer and values must be non-negative.Returns WideLine: This line.
Class · category: Graphics
Renders a collection of WideLine objects using a single instanced draw call per camera/layer pass. Lines can use different widths, colors, caps, joins and dash patterns while remaining in the same batch, as these properties are stored in per-segment instance data.
Each WideLine describes a connected polyline in world space. Its width can vary per point and is interpreted as screen pixels or world units according to WideLineRenderer#widthUnits. A line can belong to only one WideLineRenderer at a time. Use WideLineRenderer#add and WideLineRenderer#remove to transfer ownership without changing the line data.
The following example creates a three-point line with a color gradient, variable width and rounded ends and joins:
const renderer = new WideLineRenderer(app);
const line = new WideLine();
line.set(
new Float32Array([
-2, 0, 0,
0, 1, 0,
2, 0, 0
]),
new Float32Array([
1, 0, 0,
1, 1, 0,
0, 1, 1
]),
new Float32Array([4, 12, 4])
);
line.cap = LINECAP_ROUND;
line.join = LINEJOIN_ROUND;
renderer.add(line);
// Release GPU resources and detach all lines when no longer needed.
app.on('destroy', () => renderer.destroy());
Point data can be updated using WideLine#setPositions, WideLine#setColors and WideLine#setWidths. These methods preserve the point count and reuse the line's existing storage. Use WideLine#set when the point count needs to change.
Each line segment is rendered as one GPU instance. All segments owned by this renderer are submitted together, so adding more WideLine objects does not add draw calls. A renderer with visible segments issues one draw call for each camera that renders its layer. Multiple renderers therefore provide useful update isolation, but each adds another draw call per camera/layer pass.
Changing any owned line marks the renderer dirty. Before the next render, instance data for all of its lines is rebuilt and uploaded. For mixed workloads, place lines that rarely change in one renderer and frequently updated lines in another. There is no static or dynamic mode; the separation is achieved using two renderer instances. This prevents dynamic updates from repeatedly rebuilding the static segment data:
const staticLines = new WideLineRenderer(app);
const dynamicLines = new WideLineRenderer(app);
staticLines.add(roadNetwork); // Built and uploaded once.
dynamicLines.add(projectilePath); // Updated frequently.
Buffer WideLineRenderer#capacity is measured in segments and grows automatically as needed. Setting it in advance can avoid GPU buffer reallocations when the expected maximum segment count is known. WideLineRenderer#clear removes the lines but retains this capacity for reuse.
See the following examples for interactive styling and update demonstrations:
new WideLineRenderer(app: AppBase)
Creates a new wide line renderer.
Parameters
app (AppBase): The application.get capacity(): number
set capacity(value: number)
Gets the allocated instance capacity, measured in generated line segments.
get depthTest(): boolean
set depthTest(value: boolean)
Gets whether lines are tested against the depth buffer.
get depthWrite(): boolean
set depthWrite(value: boolean)
Gets whether lines write to the depth buffer.
get enabled(): boolean
set enabled(value: boolean)
Gets whether this renderer is visible.
get layer(): Layer
set layer(value: Layer)
Gets the layer containing the renderer's mesh instance.
get widthUnits(): number
set widthUnits(value: number)
Gets the units used to interpret line widths.
add(line: WideLine): void
Adds a line to this renderer. A line can belong to only one renderer at a time.
Parameters
line (WideLine): The line to add.clear(): void
Removes all lines. Allocated instance capacity is retained for reuse.
destroy(): void
Releases all renderer-owned resources. Lines previously owned by this renderer remain usable and can be added to another renderer.
remove(line: WideLine): boolean
Removes a line from this renderer without modifying its point data or style.
Parameters
line (WideLine): The line to remove.Returns boolean: True if the line was owned by this renderer and was removed.
Class · category: Graphics
Renders wireframe shapes for a single frame, for debugging and visualization. Shapes are submitted as line segments to the layer given by WireRenderer#layer, which defaults to the LAYERID_IMMEDIATE layer, and are discarded once the frame has been rendered, so they must be issued again on every frame they should be visible.
The renderer holds the state used by the shapes it draws - WireRenderer#color, WireRenderer#layer, WireRenderer#depthTest, WireRenderer#segments and WireRenderer#transform. Fields can be assigned between calls, and drawing many shapes with the same state allocates nothing:
const wire = new WireRenderer(app);
wire.color = Color.RED;
app.on('update', () => {
for (const item of items) {
wire.sphere(item.position, item.radius);
}
});
A second set of state is simply a second instance. Instances hold no GPU resources, and those sharing a layer and depth test mode submit into the same batch, so using several has no additional rendering cost:
const xray = new WireRenderer(app);
xray.depthTest = false;
These are thin lines, one pixel wide. For thick lines with caps, joins and dashes, intended as part of the rendered scene rather than as a debugging aid, see WideLineRenderer instead.
new WireRenderer(app: AppBase)
Creates a new WireRenderer instance.
Parameters
app (AppBase): The application.Example
const wire = new WireRenderer(app);
color: Color
The color used by shapes, specified in sRGB color space. The alpha component is respected. Defaults to white.
depthTest: boolean = true
Whether shapes are depth tested against the depth buffer. Defaults to true.
layer: Layer | null = null
The layer shapes are rendered into, or null to use the LAYERID_IMMEDIATE layer. Defaults to null.
segments: number = 20
The number of line segments used to approximate a full circle. Defaults to 20.
transform: Mat4 | null = null
A matrix applied to every point of every shape, or null for no transform. Assign this to draw a group of shapes in the local space of a node. Defaults to null.
arrow(from: Vec3, to: Vec3): void
Renders an arrow, as a shaft with four barbs at its tip.
Parameters
Example
wire.arrow(position, position.clone().add(velocity));
axes(matrix: Mat4, size: number): void
Renders the three axes of a matrix, colored red, green and blue for x, y and z respectively. This function ignores WireRenderer#color.
Parameters
matrix (Mat4): The transform whose axes are rendered.size (number): The length of each axis.Example
wire.axes(entity.getWorldTransform(), 1);
box(box: BoundingBox | OrientedBox): void
Renders the edges of a bounding box. An OrientedBox is rendered in its own orientation, composed with WireRenderer#transform.
Parameters
box (BoundingBox | OrientedBox): The box to render.Example
wire.box(meshInstance.aabb);
boxMinMax(min: Vec3, max: Vec3): void
Renders the edges of a box specified by its min and max corners.
Parameters
Example
wire.boxMinMax(new Vec3(-1, -1, -1), new Vec3(1, 1, 1));
capsule(start: Vec3, end: Vec3, radius: number): void
Renders a capsule as a ring and hemispherical cap at each end, joined by four side lines.
Parameters
start (Vec3): The center of the start cap sphere.end (Vec3): The center of the end cap sphere.radius (number): The radius of the capsule.Example
wire.capsule(feet, head, 0.4);
circle(center: Vec3, normal: Vec3, radius: number): void
Renders a circle lying in the plane described by a normal.
Parameters
center (Vec3): The center of the circle.normal (Vec3): The normal of the plane containing the circle. Need not be
normalized.radius (number): The radius of the circle.Example
wire.circle(Vec3.ZERO, Vec3.UP, 5);
cone(apex: Vec3, direction: Vec3, angle: number, length: number): void
Renders a cone as a base ring joined to its apex by four side lines. The parameters match those describing a spot light, so a light's cone can be visualized directly.
Parameters
apex (Vec3): The tip of the cone.direction (Vec3): The direction the cone opens along. Need not be normalized.angle (number): The half-angle of the cone, in degrees, measured from direction to
the cone edge.length (number): The distance from the apex to the base.Example
wire.cone(position, direction, 30, 10);
cylinder(start: Vec3, end: Vec3, radius: number): void
Renders a cylinder as a ring at each end joined by four side lines.
Parameters
start (Vec3): The center of the start cap.end (Vec3): The center of the end cap.radius (number): The radius of the cylinder.Example
wire.cylinder(base, tip, 0.5);
frustum(source: CameraComponent | Mat4): void
Renders the edges of a view frustum. The camera does not need to be enabled or rendering, so the view volume of an inactive camera can be visualized.
Parameters
source (CameraComponent | Mat4): A camera, or a view-projection matrix.Example
wire.frustum(otherCamera.camera);
light(light: LightComponent, size?: number): void
Renders the shape and extent of a light, using the light's own color. An omni light is drawn as a sphere of its range, a spot light as its cone, and a directional light as an arrow showing the direction it shines in. A light shines along the negative y-axis of its entity, so the shape follows that axis rather than the entity's forward direction.
Parameters
light (LightComponent): The light to render.size (number, optional, default 1): The length of the arrow used for a directional light, which has no
inherent extent. Defaults to 1.Example
wire.light(entity.light);
line(start: Vec3, end: Vec3): void
Renders a single line segment.
Parameters
start (Vec3): The start of the line, in world space.end (Vec3): The end of the line, in world space.Example
wire.line(new Vec3(0, 0, 0), new Vec3(0, 1, 0));
lines(positions: Vec3[], colors?: Color[]): void
Renders discrete line segments, formed by consecutive pairs of points.
Parameters
positions (Vec3[]): The points to draw lines between. The length must be a multiple
of two.colors (Color[], optional): One color per point, or undefined to use
WireRenderer#color. The color of each segment is interpolated between its ends.Example
wire.lines([start, end], [Color.RED, Color.WHITE]);
linesPacked(positions: number[] | Float32Array<ArrayBufferLike>, colors?: number[] | Float32Array<ArrayBufferLike>): void
Renders discrete line segments from packed arrays of numbers. This is the fastest of the line functions, as it avoids reading individual Vec3 and Color instances.
Parameters
positions (number[] | Float32Array<ArrayBufferLike>): Packed xyz coordinates, forming pairs of points.colors (number[] | Float32Array<ArrayBufferLike>, optional): Packed rgba values, one color per point, or
undefined to use WireRenderer#color.Example
wire.linesPacked([0, 0, 0, 0, 1, 0]);
loop(positions: Vec3[], colors?: Color[]): void
Renders a closed strip of connected line segments, joining the last point back to the first.
Parameters
positions (Vec3[]): The points of the loop, in order.colors (Color[], optional): One color per point, or undefined to use
WireRenderer#color.Example
wire.loop(outline);
plane(center: Vec3, normal: Vec3, size: number): void
Renders a square section of a plane, with a short stub along its normal.
The rotation of the square within its plane is derived from the normal, and no such derivation is continuous over all directions. An animated normal will therefore make the square appear to jump as it passes the direction where the derivation switches. To rotate a square smoothly, pass a fixed normal and drive WireRenderer#transform instead.
Parameters
center (Vec3): The center of the square.normal (Vec3): The normal of the plane. Need not be normalized.size (number): The side length of the square.Example
wire.plane(Vec3.ZERO, Vec3.UP, 10);
point(position: Vec3, size: number): void
Renders a small axis-aligned cross marking a position.
Parameters
position (Vec3): The position to mark.size (number): The overall length of each arm of the cross.Example
wire.point(hit.point, 0.2);
polyline(positions: Vec3[], colors?: Color[]): void
Renders an open strip of connected line segments.
Parameters
positions (Vec3[]): The points of the strip, in order.colors (Color[], optional): One color per point, or undefined to use
WireRenderer#color.Example
wire.polyline(trajectory);
sphere(center: Vec3, radius: number): void
Renders a sphere as three great circles, one in each of the primary planes.
Parameters
center (Vec3): The center of the sphere.radius (number): The radius of the sphere.Example
wire.sphere(new Vec3(0, 1, 0), 0.5);
Function · category: Graphics
calculateNormals(positions: ArrayLike<number>, indices: ArrayLike<number>): number[]
Generates normal information from the specified positions and triangle indices.
Parameters
positions (ArrayLike<number>): An array of 3-dimensional vertex positions.indices (ArrayLike<number>): An array of triangle indices.Returns number[]: An array of 3-dimensional vertex normals.
Example
const normals = calculateNormals(positions, indices);
Function · category: Graphics
calculateTangents(positions: ArrayLike<number>, normals: ArrayLike<number>, uvs: ArrayLike<number>, indices: ArrayLike<number>): number[]
Generates tangent information from the specified positions, normals, texture coordinates and triangle indices.
Parameters
positions (ArrayLike<number>): An array of 3-dimensional vertex positions.normals (ArrayLike<number>): An array of 3-dimensional vertex normals.uvs (ArrayLike<number>): An array of 2-dimensional vertex texture coordinates.indices (ArrayLike<number>): An array of triangle indices.Returns number[]: An array of 3-dimensional vertex tangents.
Example
const tangents = calculateTangents(positions, normals, uvs, indices);
Function · category: Graphics
createGraphicsDevice(canvas: HTMLCanvasElement, options?: object): Promise<GraphicsDevice>
Creates a graphics device.
Parameters
canvas (HTMLCanvasElement): The canvas element.options (object, optional, default {}): Graphics device options.
options.alpha (boolean, optional): Boolean that indicates whether the canvas composites with
the page behind it. Defaults to true. This is a compositing option rather than a memory one -
neither backend has an alpha-less backbuffer format that saves any space. The backends
implement it differently:
alpha context attribute, so the browser
decides whether the drawing buffer actually has an alpha channel. When it does not, the device's
backBufferFormat becomes PIXELFORMAT_RGB8 rather than PIXELFORMAT_RGBA8, which
also changes the format of the scene color grab pass.backBufferFormat is unaffected and
'opaque' simply tells the compositor to ignore the alpha that is already there.Compositing is premultiplied on both backends, so a transparent canvas needs a camera CameraComponent#clearColor with both its alpha and its RGB set to zero. A non-zero color with zero alpha is not valid premultiplied data and composites inconsistently across browsers.
Note that this default applies to this function. The legacy Application constructor
instead defaults alpha to false.
options.antialias (boolean, optional): Boolean that indicates whether or not to perform
anti-aliasing if possible. Defaults to true.
options.depth (boolean, optional): Boolean that indicates that the drawing buffer is
requested to have a depth buffer of at least 16 bits. Defaults to true.
options.deviceTypes (string[], optional): An array of DEVICETYPE_*** constants, defining the
order in which the devices are attempted to get created. Defaults to an empty array. If the
specified array does not contain DEVICETYPE_WEBGL2, it is internally added to its end.
A DEVICETYPE_NULL device, which renders nothing, is only created if it is specified.
Typically, you'd only specify DEVICETYPE_WEBGPU, or leave it empty. Use
DEVICETYPE_WEBGPU_BARE or DEVICETYPE_WEBGL2_BARE to create a device without
optional features and with the limits of the least capable devices, useful for testing on
constrained devices.
options.displayFormat (string, optional): The display format of the canvas. Defaults to
DISPLAYFORMAT_LDR. Can be:
options.glslangUrl (string, optional): The URL to the glslang script. Required only if
user-defined shaders or shader chunk overrides are specified in GLSL and need to be transpiled to
WGSL for use with the DEVICETYPE_WEBGPU device type. This is not required if only the
engine's built-in shaders are used, as those are provided directly in WGSL. Not used for
DEVICETYPE_WEBGL2 device type creation.
options.powerPreference ("default" | "high-performance" | "low-power", optional): A hint indicating
what configuration of GPU would be selected. Possible values are:
Defaults to 'default'.
options.stencil (boolean, optional): Boolean that indicates that the drawing buffer is
requested to have a stencil buffer of at least 8 bits. Defaults to true.
options.transientColor (boolean, optional): Boolean that requests the multi-sampled (MSAA)
color attachment of the back-buffer to be allocated as a transient ("memoryless") attachment,
allowing tile-based GPUs to keep its contents in on-chip memory and avoid VRAM allocation.
WebGPU only, and only effective when anti-aliasing (MSAA) is enabled - it has no effect on
single-sampled color, which is always presented. Ignored on devices without transient attachment
support. Incompatible with a scene color grab pass (sceneColorMap): the attachment must be
cleared on load and discarded on store. Defaults to false.
options.transientDepth (boolean, optional): Boolean that requests the back-buffer depth
attachment to be allocated as a transient ("memoryless") attachment (see transientColor).
Applies to both single- and multi-sampled depth. WebGPU only; ignored on devices without
transient attachment support. Incompatible with a scene depth grab pass (sceneDepthMap), a
depth prepass, or any depth resolve, as the depth cannot be sampled or copied out. Defaults to
false.
options.twgslUrl (string, optional): An url to twgsl script, required if glslangUrl was specified.
options.xrCompatible (boolean, optional): Boolean that hints to the user agent to use a
compatible graphics adapter for an immersive XR device. When omitted in a browser, defaults to
true if navigator.xr is present, otherwise false (see GraphicsDevice constructor).
Returns Promise<GraphicsDevice>: - Promise object representing the created graphics device.
It is rejected if none of the device types can be created, with an AggregateError whose
errors contain the error of each device type that failed.
Function · category: Graphics
drawQuadWithShader(device: GraphicsDevice, target: RenderTarget | null, shader: Shader, rect?: Vec4, scissorRect?: Vec4, name?: string): void
Draws a screen-space quad using a specific shader.
Parameters
device (GraphicsDevice): The graphics device used to draw the quad.target (RenderTarget | null): The destination render target. If undefined, target is the
frame buffer.shader (Shader): The shader used for rendering the quad. Vertex shader should contain
attribute vec2 vertex_position.rect (Vec4, optional): The viewport rectangle of the quad, in pixels. Defaults to fullscreen:
[0, 0, target.width, target.height].scissorRect (Vec4, optional): The scissor rectangle of the quad, in pixels. Defaults to fullscreen:
[0, 0, target.width, target.height].name (string, optional): The render pass name used for GPU profiling and debugging in debug
builds. Defaults to 'RenderPassQuad'.Function · category: Graphics
reprojectTexture(source: Texture, target: Texture, options?: object): boolean
This function reprojects textures between cubemap, equirectangular and octahedral formats. The function can read and write textures with pixel data in RGBE, RGBM, linear and sRGB formats. When specularPower is specified it will perform a phong-weighted convolution of the source (for generating a gloss maps).
Parameters
source (Texture): The source texture.target (Texture): The target texture.options (object, optional, default {}): The options object.
options.distribution (string, optional): Specify convolution distribution - 'none', 'lambert',
'phong', 'ggx'. Default depends on specularPower.options.face (number, optional): Optional cubemap face to update (default is update all faces).options.numSamples (number, optional): Optional number of samples (default is 1024).options.rect (Vec4, optional): Optional viewport rectangle.options.seamPixels (number, optional): Optional number of seam pixels to renderoptions.specularPower (number, optional): Optional specular power. When specular power is
specified, the source is convolved by a phong-weighted kernel raised to the specified power.
Otherwise the function performs a standard resample.Returns boolean: True if the reprojection was applied and false otherwise (e.g. if rect is empty)
Variable · category: Graphics
ATC compressed format with alpha channel in blocks of 4x4.
const PIXELFORMAT_ASTC_4x4: 28 = 28
Variable · category: Graphics
Format equivalent to PIXELFORMAT_ASTC_4x4 but sampled in linear color space.
const PIXELFORMAT_ASTC_4x4_SRGB: 63 = 63
Class · extends InputSource · category: Input
Dual gesture input source. Two virtual controls for a touch screen, one on the left of the
element and one on the right, producing leftInput and rightInput deltas as [x, y] and a
doubleTap delta. The layout chooses a joystick or a plain touch area for each side,
for example joystick-touch, and the joysticks are exposed as leftJoystick and
rightJoystick.
new DualGestureSource(layout?: "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch")
Parameters
layout ("joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch", optional): The layout of the dual
gesture source.get layout(): "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch"
set layout(value: "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch")
get leftJoystick(): VirtualJoystick
get rightJoystick(): VirtualJoystick
attach(element: HTMLElement): void
Parameters
element (HTMLElement): The element.destroy(): void
detach(): void
read(): { doubleTap: number[]; leftInput: number[]; rightInput: number[] }
Returns { doubleTap: number[]; leftInput: number[]; rightInput: number[] }
protected _element: HTMLElement | null = nulldeltas: { doubleTap: InputDelta; leftInput: InputDelta; rightInput: InputDelta }fire(event: string, ...args: any[]): voidoff(event: string, callback: HandleEventCallback): voidon(event: string, callback: HandleEventCallback): voidClass · extends InputController · category: Input
The fly controller. Free flight: rotate deltas turn the pose about yaw and pitch, limited by
yawRange and pitchRange, and move deltas translate it along its own right, up
and forward axes, so movement follows where the camera looks. Motion is smoothed with
rotateDamping and moveDamping.
moveDamping: number = 0.98
The movement damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.
rotateDamping: number = 0.98
The rotation damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.
get pitchRange(): Vec2
set pitchRange(value: Vec2)
get yawRange(): Vec2
set yawRange(value: Vec2)
attach(pose: Pose, smooth?: boolean): void
Parameters
pose (Pose): The initial pose of the controller.smooth (boolean, optional, default true): Whether to smooth the transition.destroy(): void
detach(): void
update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose
Parameters
frame (InputFrame<{ move: number[]; rotate: number[] }>): The input frame.dt (number): The delta time.Returns Pose: - The controller pose.
new FlyController()protected _pose: PoseClass · extends InputController · category: Input
The focus controller. It ignores the input frame and instead eases the pose from where it was towards the pose given to attach, smoothed by focusDamping. Use it to animate a camera onto a new target and then hand over to another controller; complete reports when the target has been reached.
focusDamping: number = 0.98
The focus damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.
attach(pose: Pose, smooth?: boolean): void
Parameters
pose (Pose): The initial pose of the controller.smooth (boolean, optional, default true): Whether to smooth the transition.complete(): boolean
Returns boolean
destroy(): void
detach(): void
update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose
Parameters
frame (InputFrame<{ move: number[]; rotate: number[] }>): The input frame.dt (number): The delta time.Returns Pose: - The controller pose.
new FocusController()protected _pose: PoseClass · extends InputSource · category: Input
Game pad input source class. Each read polls the connected gamepads and yields
buttons deltas for the buttons listed in buttonCode, and leftStick and
rightStick deltas as [x, y].
new GamepadSource()
static readonly buttonCode: { A: 0; B: 1; LB: 4; LEFT_STICK: 10; LT: 6; RB: 5; RIGHT_STICK: 11; RT: 7; SELECT: 8; START: 9; X: 2; Y: 3 } = BUTTON_CODES
The button codes (based on Xbox controller layout).
Properties
A (0, optional, default 0)B (1, optional, default 1)LB (4, optional, default 4)LEFT_STICK (10, optional, default 10)LT (6, optional, default 6)RB (5, optional, default 5)RIGHT_STICK (11, optional, default 11)RT (7, optional, default 7)SELECT (8, optional, default 8)START (9, optional, default 9)X (2, optional, default 2)Y (3, optional, default 3)read(): { buttons: number[]; leftStick: number[]; rightStick: number[] }
Returns { buttons: number[]; leftStick: number[]; rightStick: number[] }
protected _element: HTMLElement | null = nulldeltas: { buttons: InputDelta; leftStick: InputDelta; rightStick: InputDelta }attach(element: HTMLElement): voiddestroy(): voiddetach(): voidfire(event: string, ...args: any[]): voidoff(event: string, callback: HandleEventCallback): voidon(event: string, callback: HandleEventCallback): voidClass · category: Input
The base class for all input consumers, which are used to process input frames. A consumer implements update, receiving an InputFrame and the frame time, and does whatever that input means for it. InputController is the consumer that turns input into a Pose.
new InputConsumer()
update(frame: InputFrame<any>, dt: number): void
Parameters
frame (InputFrame<any>): The input frame.dt (number): The delta time.Class · extends InputConsumer · category: Input
The base class for all input controllers. A controller consumes an InputFrame carrying
move and rotate deltas and produces a Pose: attach sets the pose it starts
from, update applies a frame and returns the current pose, and detach releases
it. The application applies the returned pose to an entity. FlyController,
OrbitController and FocusController implement three ways of doing this.
Example
controller.attach(pose.look(cameraPosition, target));
// each frame, after filling the frame's move and rotate deltas from your sources
const result = controller.update(frame, dt);
camera.setPosition(result.position);
camera.setEulerAngles(result.angles);
protected _pose: Pose
attach(pose: Pose, smooth?: boolean): void
Parameters
pose (Pose): The initial pose of the controller.smooth (boolean, optional, default true): Whether to smooth the transition.destroy(): void
detach(): void
update(frame: InputFrame<any>, dt: number): Pose
Parameters
frame (InputFrame<any>): The input frame.dt (number): The delta time.Returns Pose: - The controller pose.
new InputController()Class · category: Input
Represents an input delta: a fixed-length array of numbers that accumulates input between reads. Sources append raw values to it as events arrive, and read returns the total and resets it to zero, so each read yields the change since the previous one. An InputFrame groups named deltas together.
new InputDelta(arg: number | number[])
Parameters
arg (number | number[]): The size of the delta or an array of initial values.add(other: InputDelta): InputDelta
Adds another InputDelta instance to this one.
Parameters
other (InputDelta): The other InputDelta instance to add.Returns InputDelta: Self for chaining.
append(offsets: number[]): InputDelta
Appends offsets to the current delta values.
Parameters
offsets (number[]): The offsets.Returns InputDelta: Self for chaining.
copy(other: InputDelta): InputDelta
Copies the values from another InputDelta instance to this one.
Parameters
other (InputDelta): The other InputDelta instance to copy from.Returns InputDelta: Self for chaining.
length(): number
The magnitude of the delta, calculated as the square root of the sum of squares of the values.
Returns number: - The magnitude of the delta.
read(): number[]
Returns the current value of the delta and resets it to zero.
Returns number[]: - The current value of the delta.
Class · category: Input
Represents an input frame, which contains a map of input deltas. The keys and lengths are fixed
by the object passed to the constructor, for example { move: [0, 0, 0], rotate: [0, 0, 0] },
and read flushes every delta at once. A frame is the unit of exchange in this input
system: InputSources are frames that fill themselves from a device, and an application
combines their values into a frame with the shape an InputController expects.
template The shape of the input frame.
new InputFrame<T extends Record<string, number[]>>(data: T)
Parameters
data (T): The input frame data, where each key corresponds to an input delta.deltas: { [K in string | number | symbol]: InputDelta }
read(): { [K in string | number | symbol]: number[] }
Returns the current frame state and resets the deltas to zero.
Returns { [K in string | number | symbol]: number[] }: - The flushed input frame with current deltas.
Class · extends InputFrame · category: Input
The base class for all input devices. An input source is an InputFrame that fills its own deltas from DOM events or device polling once attach is given an element, and stops on detach. Call InputFrame#read once per frame to take the accumulated deltas. The built-in sources are KeyboardMouseSource, GamepadSource, MultiTouchSource, SingleGestureSource and DualGestureSource; subclass this to add another device.
template The shape of the input source.
protected _element: HTMLElement | null = null
attach(element: HTMLElement): void
Parameters
element (HTMLElement): The element.destroy(): void
detach(): void
fire(event: string, ...args: any[]): void
Fires an event with the given name and arguments.
Parameters
event (string): The event name to fire.args (any[]): The arguments to pass to the event listeners.off(event: string, callback: HandleEventCallback): void
Removes an event listener for the specified event.
Parameters
event (string): The event name to stop listening for.callback (HandleEventCallback): The callback function to remove.on(event: string, callback: HandleEventCallback): void
Adds an event listener for the specified event.
Parameters
event (string): The event name to listen for.callback (HandleEventCallback): The callback function to execute when the event is
triggered.new InputSource<T extends Record<string, number[]>>(data: T)deltas: { [K in string | number | symbol]: InputDelta }read(): { [K in string | number | symbol]: number[] }Class · extends InputSource · category: Input
Keyboard and mouse input source class. Attached to an element, it accumulates key deltas for
the keys listed in keyCode, button deltas for the mouse buttons, mouse deltas for
pointer movement and wheel deltas for the scroll wheel. Pass pointerLock: true to use
pointer lock for mouse movement.
new KeyboardMouseSource(options?: object)
Parameters
options (object, optional, default {}): The options.
options.pointerLock (boolean, optional, default false): Whether to enable pointer lock._button: number[]
static readonly keyCode: { 0: 26; 1: 27; 2: 28; 3: 29; 4: 30; 5: 31; 6: 32; 7: 33; 8: 34; 9: 35; A: 0; B: 1; C: 2; CTRL: 42; D: 3; DOWN: 37; E: 4; F: 5; G: 6; H: 7; I: 8; J: 9; K: 10; L: 11; LEFT: 38; M: 12; N: 13; O: 14; P: 15; Q: 16; R: 17; RIGHT: 39; S: 18; SHIFT: 41; SPACE: 40; T: 19; U: 20; UP: 36; V: 21; W: 22; X: 23; Y: 24; Z: 25 } = KEY_CODES
The key codes for the keyboard keys.
Properties
0 (26, optional, default 26)1 (27, optional, default 27)2 (28, optional, default 28)3 (29, optional, default 29)4 (30, optional, default 30)5 (31, optional, default 31)6 (32, optional, default 32)7 (33, optional, default 33)8 (34, optional, default 34)9 (35, optional, default 35)A (0, optional, default 0)B (1, optional, default 1)C (2, optional, default 2)CTRL (42, optional, default 42)D (3, optional, default 3)DOWN (37, optional, default 37)E (4, optional, default 4)F (5, optional, default 5)G (6, optional, default 6)H (7, optional, default 7)I (8, optional, default 8)J (9, optional, default 9)K (10, optional, default 10)L (11, optional, default 11)LEFT (38, optional, default 38)M (12, optional, default 12)N (13, optional, default 13)O (14, optional, default 14)P (15, optional, default 15)Q (16, optional, default 16)R (17, optional, default 17)RIGHT (39, optional, default 39)S (18, optional, default 18)SHIFT (41, optional, default 41)SPACE (40, optional, default 40)T (19, optional, default 19)U (20, optional, default 20)UP (36, optional, default 36)V (21, optional, default 21)W (22, optional, default 22)X (23, optional, default 23)Y (24, optional, default 24)Z (25, optional, default 25)attach(element: HTMLElement): void
Parameters
element (HTMLElement): The element.detach(): void
read(): { button: number[]; key: number[]; mouse: number[]; wheel: number[] }
Returns { button: number[]; key: number[]; mouse: number[]; wheel: number[] }
protected _element: HTMLElement | null = nulldeltas: { button: InputDelta; key: InputDelta; mouse: InputDelta; wheel: InputDelta }destroy(): voidfire(event: string, ...args: any[]): voidoff(event: string, callback: HandleEventCallback): voidon(event: string, callback: HandleEventCallback): voidClass · extends InputSource · category: Input
Multi-touch input source class. Attached to an element, it accumulates touch deltas for the
movement of the touch points, count deltas for changes in the number of touches, and pinch
deltas for the change in distance between two touches, which is what an orbiting camera needs
on a touch screen.
new MultiTouchSource()
attach(element: HTMLElement): void
Parameters
element (HTMLElement): The element.detach(): void
protected _element: HTMLElement | null = nulldeltas: { count: InputDelta; pinch: InputDelta; touch: InputDelta }destroy(): voidfire(event: string, ...args: any[]): voidoff(event: string, callback: HandleEventCallback): voidon(event: string, callback: HandleEventCallback): voidread(): { count: number[]; pinch: number[]; touch: number[] }Class · extends InputController · category: Input
The orbit controller. The pose orbits a focus point at a distance: rotate deltas turn the
view around the focus within yawRange and pitchRange, the first two move
components pan the focus point, and the third scales the distance within zoomRange.
Motion is smoothed with rotateDamping, moveDamping and zoomDamping.
moveDamping: number = 0.98
The movement damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.
rotateDamping: number = 0.98
The rotation damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.
zoomDamping: number = 0.98
The zoom damping. A higher value means more damping. A value of 0 means no damping.
get pitchRange(): Vec2
set pitchRange(range: Vec2)
get yawRange(): Vec2
set yawRange(range: Vec2)
get zoomRange(): Vec2
set zoomRange(range: Vec2)
attach(pose: Pose, smooth?: boolean): void
Parameters
pose (Pose): The initial pose of the controller.smooth (boolean, optional, default true): Whether to smooth the transition.destroy(): void
detach(): void
update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose
Parameters
frame (InputFrame<{ move: number[]; rotate: number[] }>): The input frame.dt (number): The delta time.Returns Pose: - The controller pose.
new OrbitController()protected _pose: PoseClass · category: Input
Represents a pose in 3D space, including position and rotation. It is what an InputController produces: a position, Euler angles in degrees and, for controllers that orbit, the distance to the focus point. Optional ranges such as pitchRange and yRange clamp the result of rotate and move.
new Pose(position?: Vec3, angles?: Vec3, distance?: number)
Creates a new Pose instance.
Parameters
position (Vec3, optional, default Vec3.ZERO): The position of the pose.angles (Vec3, optional, default Vec3.ZERO): The angles of the pose in degrees.distance (number, optional, default 0): The focus distance from the position to the pose.angles: Vec3
The angles of the pose in degrees calculated from the forward vector.
distance: number = 0
The focus distance from the position to the pose.
pitchRange: Vec2
The allowed range of pitch angles in degrees, stored as (min, max). Applied when the pose is rotated via rotate.
position: Vec3
The position of the pose.
xRange: Vec2
The allowed range of positions along the x axis, stored as (min, max). Applied when the pose is translated via move.
yawRange: Vec2
The allowed range of yaw angles in degrees, stored as (min, max). Applied when the pose is rotated via rotate.
yRange: Vec2
The allowed range of positions along the y axis, stored as (min, max). Applied when the pose is translated via move.
zRange: Vec2
The allowed range of positions along the z axis, stored as (min, max). Applied when the pose is translated via move.
clone(): Pose
Creates a clone of this pose.
Returns Pose: A new Pose instance with the same position, angles, and distance.
copy(other: Pose): Pose
Copies the position and rotation from another pose.
Parameters
other (Pose): The pose to copy from.Returns Pose: The updated Pose instance.
equalsApprox(other: Pose, epsilon?: number): boolean
Checks if this pose is approximately equal to another pose within a given epsilon.
Parameters
other (Pose): The pose to compare with.epsilon (number, optional, default 1e-6): The tolerance for comparison.Returns boolean: True if the poses are approximately equal, false otherwise.
getFocus(out?: Vec3): Vec3
Gets the focus point of the pose, which is the position plus the forward vector scaled by the distance.
Parameters
out (Vec3, optional): The output vector to store the focus point.Returns Vec3: The focus point of the pose.
lerp(lhs: Pose, rhs: Pose, alpha1: number, alpha2?: number, alpha3?: number): Pose
Lerps between two poses based on the given alpha values.
Parameters
lhs (Pose): The left-hand side pose.rhs (Pose): The right-hand side pose.alpha1 (number): The alpha value for position interpolation.alpha2 (number, optional, default alpha1): The alpha value for angles interpolation.alpha3 (number, optional, default alpha1): The alpha value for distance interpolation.Returns Pose: The updated Pose instance.
look(from: Vec3, to: Vec3): Pose
Sets the pose to look in the direction of the given vector.
Parameters
Returns Pose: The updated Pose instance.
move(offset: Vec3): Pose
Moves the pose by the given vector.
Parameters
offset (Vec3): The vector to move by.Returns Pose: The updated Pose instance.
rotate(euler: Vec3): Pose
Rotates the pose by the given angles in degrees.
Parameters
euler (Vec3): The angles to rotate by.Returns Pose: The updated Pose instance.
set(position: Vec3, angles: Vec3, distance: number): Pose
Sets the position and rotation of the pose.
Parameters
position (Vec3): The new position.angles (Vec3): The new angles in degrees.distance (number): The new focus distance.Returns Pose: The updated Pose instance.
Class · extends InputSource · category: Input
Single gesture input source. One virtual control for a touch screen, either an on-screen
joystick or a drag anywhere on the element depending on layout, producing an
input delta as [x, y] and a doubleTap delta.
new SingleGestureSource()
get joystick(): VirtualJoystick
get layout(): "joystick" | "touch"
set layout(value: "joystick" | "touch")
attach(element: HTMLElement): void
Parameters
element (HTMLElement): The element.destroy(): void
detach(): void
read(): { doubleTap: number[]; input: number[] }
Returns { doubleTap: number[]; input: number[] }
protected _element: HTMLElement | null = nulldeltas: { doubleTap: InputDelta; input: InputDelta }fire(event: string, ...args: any[]): voidoff(event: string, callback: HandleEventCallback): voidon(event: string, callback: HandleEventCallback): voidClass · category: Input Devices
A GamePad stores information about a gamepad from the Gamepad API.
hand: string
The hand this gamepad is usually handled on. Only relevant for XR pads. Value is either "left", "right" or "none".
id: string
The identifier for the gamepad. Its structure depends on device.
index: number
The index for this controller. A gamepad that is disconnected and reconnected will retain the same index.
map: any
The buttons and axes map.
mapping: string
The gamepad mapping detected by the browser. Value is either "standard", "xr-standard", "" or "custom". When empty string, you may need to update the mapping yourself. "custom" means you updated the mapping.
get axes(): number[]
Gets the values from analog axes present on the GamePad. Values are between -1 and 1.
get buttons(): GamePadButton[]
Gets the buttons present on the GamePad.
get connected(): boolean
Gets whether the gamepad is connected.
getAxis(axis: number): number
Get the value of one of the analog axes of the pad.
Parameters
axis (number): The axis to get the value of, use constants PAD_L_STICK_X, etc.Returns number: The value of the axis between -1 and 1.
getButton(index: number): GamePadButton
Retrieve a button from its index.
Parameters
index (number): The index to return the button for.Returns GamePadButton: The button for the searched index. May be a placeholder if none found.
getValue(button: number): number
Returns the value of a button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed.
Parameters
button (number): The button to retrieve, use constants PAD_FACE_1, etc.Returns number: The value of the button between 0 and 1.
isPressed(button: number): boolean
Returns true if the button is pressed.
Parameters
button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: True if the button is pressed.
isTouched(button: number): boolean
Returns true if the button is touched.
Parameters
button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: True if the button is touched.
pulse(intensity: number, duration: number, options?: object): Promise<boolean>
Make the gamepad vibrate.
Parameters
intensity (number): Intensity for the vibration in the range 0 to 1.duration (number): Duration for the vibration in milliseconds.options (object, optional): Options for special vibration pattern.
options.startDelay (number, optional): Delay before the pattern starts, in milliseconds. Defaults to 0.options.strongMagnitude (number, optional): Intensity for strong actuators in the range 0 to 1. Defaults to intensity.options.weakMagnitude (number, optional): Intensity for weak actuators in the range 0 to 1. Defaults to intensity.Returns Promise<boolean>: Return a Promise resulting in true if the pulse was successfully completed.
resetMap(): void
Reset gamepad mapping to default.
updateMap(map: object): void
Update the map for this gamepad.
Parameters
map (object): The new mapping for this gamepad.
map.axes (string[]): Axes mapping for this gamepad.map.buttons (string[]): Buttons mapping for this gamepad.map.mapping ("custom", optional): New mapping format. Will be forced into "custom".map.synthesizedButtons (any, optional): Information about buttons to pull from axes for this gamepad. Requires definition of axis index, min value and max value.Example
this.pad.updateMap({
buttons: [[
'PAD_FACE_1',
'PAD_FACE_2',
'PAD_FACE_3',
'PAD_FACE_4',
'PAD_L_SHOULDER_1',
'PAD_R_SHOULDER_1',
'PAD_L_SHOULDER_2',
'PAD_R_SHOULDER_2',
'PAD_SELECT',
'PAD_START',
'PAD_L_STICK_BUTTON',
'PAD_R_STICK_BUTTON',
'PAD_VENDOR'
],
axes: [
'PAD_L_STICK_X',
'PAD_L_STICK_Y',
'PAD_R_STICK_X',
'PAD_R_STICK_Y'
],
synthesizedButtons: {
PAD_UP: { axis: 0, min: 0, max: 1 },
PAD_DOWN: { axis: 0, min: -1, max: 0 },
PAD_LEFT: { axis: 0, min: -1, max: 0 },
PAD_RIGHT: { axis: 0, min: 0, max: 1 }
}
});
wasPressed(button: number): boolean
Return true if the button was pressed since the last update.
Parameters
button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: Return true if the button was pressed, false if not.
wasReleased(button: number): boolean
Return true if the button was released since the last update.
Parameters
button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: Return true if the button was released, false if not.
wasTouched(button: number): boolean
Return true if the button was touched since the last update.
Parameters
button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: Return true if the button was touched, false if not.
Class · category: Input Devices
A GamePadButton stores information about a button from the Gamepad API.
pressed: boolean = false
Whether the button is currently down.
touched: boolean = false
Whether the button is currently touched.
value: number = 0
The value for the button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed.
wasPressed: boolean = false
Whether the button was pressed.
wasReleased: boolean = false
Whether the button was released since the last update.
wasTouched: boolean = false
Whether the button was touched since the last update.
Class · extends EventHandler · category: Input Devices
Input handler for accessing GamePad input.
For frame-accumulated input deltas rather than raw pad state, see GamepadSource, KeyboardMouseSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.
new GamePads()
Create a new GamePads instance.
current: GamePad[] = []
The list of current gamepads.
gamepadsSupported: boolean
Whether gamepads are supported by this device.
findById(id: string): GamePad | null
Find a connected GamePad from its identifier.
Parameters
id (string): The identifier to search for.Returns GamePad | null: The GamePad with the matching identifier or null if no gamepad is found or the gamepad is not connected.
findByIndex(index: number): GamePad | null
Find a connected GamePad from its device index.
Parameters
index (number): The device index to search for.Returns GamePad | null: The GamePad with the matching device index or null if no gamepad is found or the gamepad is not connected.
getAxis(orderIndex: number, axis: number): number
Get the value of one of the analog axes of the pad.
Parameters
orderIndex (number): The index of the pad to check, use constants PAD_1, PAD_2, etc. For gamepad index call the function from the pad.axis (number): The axis to get the value of, use constants PAD_L_STICK_X, etc.Returns number: The value of the axis between -1 and 1.
getMap(pad: Gamepad): any
Retrieve the order for buttons and axes for given HTML5 Gamepad.
Parameters
pad (Gamepad): The HTML5 Gamepad object.Returns any: Object defining the order of buttons and axes for given HTML5 Gamepad.
isPressed(orderIndex: number, button: number): boolean
Returns true if the button on the pad requested is pressed.
Parameters
orderIndex (number): The order index of the pad to check, use constants PAD_1, PAD_2, etc. For gamepad index call the function from the pad.button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: True if the button is pressed.
poll(pads?: GamePad[]): GamePad[]
Poll for the latest data from the gamepad API.
Parameters
pads (GamePad[], optional, default []): An optional array used to receive the gamepads mapping. This
array will be returned by this function.Returns GamePad[]: An array of gamepads and mappings for the model of gamepad that is
attached.
Example
const gamepads = new GamePads();
const pads = gamepads.poll();
pulse(orderIndex: number, intensity: number, duration: number, options?: object): Promise<boolean>
Make the gamepad vibrate.
Parameters
orderIndex (number): The index of the pad to check, use constants PAD_1, PAD_2, etc. For gamepad index call the function from the pad.intensity (number): Intensity for the vibration in the range 0 to 1.duration (number): Duration for the vibration in milliseconds.options (object, optional): Options for special vibration pattern.
options.startDelay (number, optional): Delay before the pattern starts, in milliseconds. Defaults to 0.options.strongMagnitude (number, optional): Intensity for strong actuators in the range 0 to 1. Defaults to intensity.options.weakMagnitude (number, optional): Intensity for weak actuators in the range 0 to 1. Defaults to intensity.Returns Promise<boolean>: Return a Promise resulting in true if the pulse was successfully completed.
pulseAll(intensity: number, duration: number, options?: object): Promise<boolean[]>
Make all gamepads vibrate.
Parameters
intensity (number): Intensity for the vibration in the range 0 to 1.duration (number): Duration for the vibration in milliseconds.options (object, optional): Options for special vibration pattern.
options.startDelay (number, optional): Delay before the pattern starts, in milliseconds. Defaults to 0.options.strongMagnitude (number, optional): Intensity for strong actuators in the range 0 to 1. Defaults to intensity.options.weakMagnitude (number, optional): Intensity for weak actuators in the range 0 to 1. Defaults to intensity.Returns Promise<boolean[]>: Return a Promise resulting in an array of booleans defining if the pulse was successfully completed for every gamepads.
wasPressed(orderIndex: number, button: number): boolean
Returns true if the button was pressed since the last frame.
Parameters
orderIndex (number): The index of the pad to check, use constants PAD_1, PAD_2, etc. For gamepad index call the function from the pad.button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: True if the button was pressed since the last frame.
wasReleased(orderIndex: number, button: number): boolean
Returns true if the button was released since the last frame.
Parameters
orderIndex (number): The index of the pad to check, use constants PAD_1, PAD_2, etc. For gamepad index call the function from the pad.button (number): The button to test, use constants PAD_FACE_1, etc.Returns boolean: True if the button was released since the last frame.
static EVENT_GAMEPADCONNECTED: string = 'gamepadconnected'
Fired when a gamepad is connected. The handler is passed the GamePad object that was connected.
Example
const onPadConnected = (pad) => {
if (!pad.mapping) {
// Map the gamepad as the system could not find the proper map.
} else {
// Make the gamepad pulse.
}
};
app.keyboard.on("gamepadconnected", onPadConnected, this);
static EVENT_GAMEPADDISCONNECTED: string = 'gamepaddisconnected'
Fired when a gamepad is disconnected. The handler is passed the GamePad object that was disconnected.
Example
const onPadDisconnected = (pad) => {
// Pause the game.
};
app.keyboard.on("gamepaddisconnected", onPadDisconnected, this);
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Input Devices
Manages keyboard input by tracking key states and dispatching events. Extends EventHandler
in order to fire keydown and keyup events (see KeyboardEvent).
Allows the state of individual keys to be queried to check if they are currently pressed or were pressed/released since the last update. The class automatically handles browser visibility changes and window blur events by clearing key states. The Keyboard instance must be attached to a DOM element before it can detect key events.
Key state is derived from the legacy KeyboardEvent.keyCode property. Browsers populate it for
real input, but a hand-constructed new KeyboardEvent(...) leaves it at 0, so synthesized events
must set keyCode explicitly in order to be observed.
Keyboard#wasPressed and Keyboard#wasReleased compare against a snapshot taken once per frame, so a keydown and keyup delivered within the same task are seen by neither. Hold the key across at least one frame.
Your application's Keyboard instance is managed and accessible via AppBase#keyboard.
For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see KeyboardMouseSource, GamepadSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.
new Keyboard(element?: Element | Window, options?: object)
Create a new Keyboard instance.
Parameters
element (Element | Window, optional): Element to attach Keyboard to. Note that elements like
<div> can't accept focus by default. To use keyboard events on an element like this it
must have a value of 'tabindex' e.g. tabindex="0". See
here for more details.options (object, optional, default {}): Optional options object.
options.preventDefault (boolean, optional): Call preventDefault() in key event handlers.
This stops the default action of the event occurring. e.g. Ctrl+T will not open a new
browser tab.options.stopPropagation (boolean, optional): Call stopPropagation() in key event handlers.
This stops the event bubbling up the DOM so no parent handlers will be notified of the
event.Example
// attach keyboard listeners to the window
const keyboard = new Keyboard(window);
preventDefault: boolean
Call preventDefault() in key event handlers.
stopPropagation: boolean
Call stopPropagation() in key event handlers.
attach(element: Element | Window): void
Attach the keyboard event handlers to an Element. If already attached, this first detaches
and clears current and previous key states, even when attaching to the same element. No
keyup events are fired. Unlike Mouse#attach, held input states are not preserved.
Parameters
element (Element | Window): The element to listen for keyboard events on.detach(): void
Detach the keyboard event handlers from the element it is attached to and clear current and
previous key states. This does not fire keyup events.
isPressed(key: number): boolean
Return true if the key is currently down.
Parameters
key (number): The keyCode of the key to test. See the KEY_* constants.Returns boolean: True if the key was pressed, false if not.
wasPressed(key: number): boolean
Returns true if the key was pressed since the last update.
Parameters
key (number): The keyCode of the key to test. See the KEY_* constants.Returns boolean: True if the key was pressed.
wasReleased(key: number): boolean
Returns true if the key was released since the last update.
Parameters
key (number): The keyCode of the key to test. See the KEY_* constants.Returns boolean: True if the key was pressed.
static EVENT_KEYDOWN: string = 'keydown'
Fired when a key is pressed. The handler is passed a KeyboardEvent.
Example
const onKeyDown = (e) => {
if (e.key === KEY_SPACE) {
// space key pressed
}
e.event.preventDefault(); // Use original browser event to prevent browser action.
};
app.keyboard.on('keydown', onKeyDown, this);
static EVENT_KEYUP: string = 'keyup'
Fired when a key is released. The handler is passed a KeyboardEvent.
Example
const onKeyUp = (e) => {
if (e.key === KEY_SPACE) {
// space key released
}
e.event.preventDefault(); // Use original browser event to prevent browser action.
};
app.keyboard.on('keyup', onKeyUp, this);
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Input Devices
The KeyboardEvent is passed into all event handlers registered on the Keyboard. The events are:
new KeyboardEvent(keyboard?: Keyboard, event?: KeyboardEvent)
Create a new KeyboardEvent.
Parameters
keyboard (Keyboard, optional): The keyboard object which is firing the event.event (KeyboardEvent, optional): The original browser event that was fired.Example
const onKeyDown = function (e) {
if (e.key === KEY_SPACE) {
// space key pressed
}
e.event.preventDefault(); // Use original browser event to prevent browser action.
};
app.keyboard.on("keydown", onKeyDown, this);
element: Element | null = null
The element that fired the keyboard event.
event: KeyboardEvent | null = null
The original browser event which was fired.
key: number | null = null
The keyCode of the key that has changed. See the KEY_* constants.
Class · extends EventHandler · category: Input Devices
Manages mouse input by tracking button states and dispatching events. Extends EventHandler
to fire mousedown, mouseup, mousemove and mousewheel events (see MouseEvent).
Allows the state of mouse buttons to be queried to check if they are currently pressed or were
pressed/released since the last update. Provides methods to enable/disable pointer lock for
raw mouse movement input and control over the context menu. The class automatically clears
button states when the window loses focus or the document becomes hidden, without firing
mouseup events. The Mouse instance must be attached to a DOM element before it can detect
mouse events.
The first unlocked mouse movement after creation, detachment or focus loss establishes a new position and reports zero movement delta. Movement outside the target also invalidates the position, so re-entry reports zero delta. Pointer-locked movement uses the browser's relative movement deltas.
Your application's Mouse instance is managed and accessible via AppBase#mouse.
For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see KeyboardMouseSource, GamepadSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.
new Mouse(element?: Element)
Create a new Mouse instance.
Parameters
element (Element, optional): The Element that the mouse events are attached to.attach(element: Element): void
Attach mouse events to an Element. If already attached, this changes the target element while preserving current and previous button states, unlike Keyboard#attach.
Parameters
element (Element): The DOM element to attach the mouse to.detach(): void
Remove mouse events from the element that it is attached to and clear current and previous
button states. The previous mouse position is also invalidated so the next unlocked movement
reports zero delta. This does not fire mouseup events.
disableContextMenu(): void
Disable the context menu usually activated with right-click.
disablePointerLock(success?: LockMouseCallback): void
Return control of the mouse cursor to the user.
Parameters
success (LockMouseCallback, optional): Function called when the mouse lock is disabled.enableContextMenu(): void
Enable the context menu usually activated with right-click. This option is active by default.
enablePointerLock(success?: LockMouseCallback, error?: LockMouseCallback): void
Request that the browser hides the mouse cursor and locks the mouse to the element. Allowing raw access to mouse movement input without risking the mouse exiting the element. Notes:
Parameters
success (LockMouseCallback, optional): Function called if the request for mouse lock is
successful.error (LockMouseCallback, optional): Function called if the request for mouse lock is
unsuccessful.isPressed(button: number): boolean
Returns true if the mouse button is currently pressed.
Parameters
button (number): The mouse button to test. Can be:
Returns boolean: True if the mouse button is current pressed.
update(): void
Update method, should be called once per frame.
wasPressed(button: number): boolean
Returns true if the mouse button was pressed this frame (since the last call to update).
Parameters
button (number): The mouse button to test. Can be:
Returns boolean: True if the mouse button was pressed since the last update.
wasReleased(button: number): boolean
Returns true if the mouse button was released this frame (since the last call to update).
Parameters
button (number): The mouse button to test. Can be:
Returns boolean: True if the mouse button was released since the last update.
static isPointerLocked(): boolean
Check if the mouse pointer has been locked, using enablePointerLock.
Returns boolean: True if locked.
static EVENT_MOUSEDOWN: string = 'mousedown'
Fired when a mouse button is pressed. The handler is passed a MouseEvent.
Example
app.mouse.on('mousedown', (e) => {
console.log(`The ${e.button} button was pressed at position: ${e.x}, ${e.y}`);
});
static EVENT_MOUSEMOVE: string = 'mousemove'
Fired when the mouse is moved. The handler is passed a MouseEvent.
Example
app.mouse.on('mousemove', (e) => {
console.log(`Current mouse position is: ${e.x}, ${e.y}`);
});
static EVENT_MOUSEUP: string = 'mouseup'
Fired when a mouse button is released. The handler is passed a MouseEvent.
Example
app.mouse.on('mouseup', (e) => {
console.log(`The ${e.button} button was released at position: ${e.x}, ${e.y}`);
});
static EVENT_MOUSEWHEEL: string = 'mousewheel'
Fired when a mouse wheel is moved. The handler is passed a MouseEvent.
Example
app.mouse.on('mousewheel', (e) => {
console.log(`The mouse wheel was moved by ${e.wheelDelta}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Input Devices
The MouseEvent object is passed into all event handlers registered on the Mouse. The events are:
new MouseEvent(mouse: Mouse, event: MouseEvent | WheelEvent)
Create a new MouseEvent instance.
Parameters
mouse (Mouse): The Mouse device that is firing this event.event (MouseEvent | WheelEvent): The original browser event that fired.altKey: boolean = false
True if the alt key was pressed when this event was fired.
button: number = MOUSEBUTTON_NONE
The mouse button associated with this event. Can be:
buttons: boolean[]
The pressed state of all mouse buttons at the time this event was fired. A 3-element array of booleans for left, middle and right buttons respectively.
ctrlKey: boolean = false
True if the ctrl key was pressed when this event was fired.
dx: number = 0
The change in x coordinate since the last mouse movement event. When the pointer is not locked, this is zero until an unlocked movement establishes a position after creation, detachment, focus loss, movement outside the target or pointer-locked movement. Under pointer lock, this uses the browser's relative movement delta.
dy: number = 0
The change in y coordinate since the last mouse movement event. When the pointer is not locked, this is zero until an unlocked movement establishes a position after creation, detachment, focus loss, movement outside the target or pointer-locked movement. Under pointer lock, this uses the browser's relative movement delta.
element: Element
The element that the mouse was fired from.
event: MouseEvent | WheelEvent
The original browser event.
metaKey: boolean = false
True if the meta key was pressed when this event was fired.
shiftKey: boolean = false
True if the shift key was pressed when this event was fired.
wheelDelta: number = 0
A value representing the amount the mouse wheel has moved, only valid for Mouse.EVENT_MOUSEWHEEL events.
x: number = 0
The x coordinate of the mouse pointer relative to the element Mouse is attached to.
y: number = 0
The y coordinate of the mouse pointer relative to the element Mouse is attached to.
Class · category: Input Devices
A instance of a single point touch on a TouchDevice.
new Touch(touch: Touch)
Create a new Touch object from the browser Touch.
Parameters
touch (Touch): The browser Touch object.id: number
The identifier of the touch.
target: Element
The target DOM element of the touch event.
touch: Touch
The original browser Touch object.
x: number
The x coordinate relative to the element that the TouchDevice is attached to.
y: number
The y coordinate relative to the element that the TouchDevice is attached to.
Class · extends EventHandler · category: Input Devices
Manages touch input by handling and dispatching touch events. Extends EventHandler
to fire touchstart, touchend, touchmove, and touchcancel events (see TouchEvent).
Detects and processes touch interactions with the attached DOM element, allowing applications to respond to common touch gestures. The TouchDevice instance must be attached to a DOM element before it can detect touch events.
Your application's TouchDevice instance is managed and accessible via AppBase#touch.
new TouchDevice(element: Element)
Create a new touch device and attach it to an element.
Parameters
element (Element): The element to attach listen for events on.attach(element: Element): void
Attach a device to an element in the DOM. If the device is already attached to an element this method will detach it first.
Parameters
element (Element): The element to attach to.detach(): void
Detach a device from the element it is attached to.
static EVENT_TOUCHCANCEL: string = 'touchcancel'
Fired when a touch is interrupted in some way. The exact reasons for canceling a touch can vary from device to device. For example, a modal alert pops up during the interaction; the touch point leaves the document area, or there are more touch points than the device supports, in which case the earliest touch point is canceled. The handler is passed a TouchEvent.
Example
app.touch.on('touchcancel', (e) => {
console.log(`Touch canceled at position: ${e.x}, ${e.y}`);
});
static EVENT_TOUCHEND: string = 'touchend'
Fired when a touch ends. The handler is passed a TouchEvent.
Example
app.touch.on('touchend', (e) => {
console.log(`Touch ended at position: ${e.x}, ${e.y}`);
});
static EVENT_TOUCHMOVE: string = 'touchmove'
Fired when a touch moves. The handler is passed a TouchEvent.
Example
app.touch.on('touchmove', (e) => {
console.log(`Touch moved to position: ${e.x}, ${e.y}`);
});
static EVENT_TOUCHSTART: string = 'touchstart'
Fired when a touch starts. The handler is passed a TouchEvent.
Example
app.touch.on('touchstart', (e) => {
console.log(`Touch started at position: ${e.x}, ${e.y}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Input Devices
The TouchEvent object is passed into all event handlers registered on the TouchDevice. The events are:
new TouchEvent(device: TouchDevice, event: TouchEvent)
Create a new TouchEvent instance. It is created from an existing browser event.
Parameters
device (TouchDevice): The source device of the touch events.event (TouchEvent): The original browser TouchEvent.changedTouches: Touch[] = []
A list of touches that have changed since the last event.
element: Element
The target DOM element that the event was fired from.
event: TouchEvent
The original browser TouchEvent.
touches: Touch[] = []
A list of all touches currently in contact with the device.
getTouchById(id: number, list: Touch[]): Touch | null
Get an event from one of the touch lists by the id. It is useful to access touches by their id so that you can be sure you are referencing the same touch.
Parameters
id (number): The identifier of the touch.list (Touch[]): An array of touches to search.Function · category: Input Devices
getTouchTargetCoords(touch: Touch): { x: number; y: number }
This function takes a browser Touch object and returns the coordinates of the touch relative to the target DOM element.
Parameters
touch (Touch): The browser Touch object.Returns { x: number; y: number }: The coordinates of the touch relative to the touch.target
DOM element.
Class · category: Math
Axis-Aligned Bounding Box. An AABB is commonly used for fast overlap tests in collision detection, spatial indexing and frustum culling.
A box is stored as a center and halfExtents. Set it from its extreme corners with setMinMax and read them back with getMin and getMax. Fit a box to vertex data with compute, grow it to enclose another box with add, and move a local box into world space with setFromTransformedAabb, which is how the engine derives a mesh instance's world bounds from its mesh's local bounds.
Tests such as intersects, containsPoint and intersectsRay return a boolean and allocate nothing. closestPoint writes into an optional result vector, while getMin and getMax return the box's own cached vectors, which should be treated as read-only. The constructor copies the vectors it is given.
Example
// Enclose every mesh instance of a render component in one box
const bounds = new BoundingBox();
entity.render.meshInstances.forEach((meshInstance, i) => {
if (i === 0) {
bounds.copy(meshInstance.aabb);
} else {
bounds.add(meshInstance.aabb);
}
});
Example
// Pick against a box; the ray's direction must be normalized
const hit = new Vec3();
if (bounds.intersectsRay(ray, hit)) {
console.log(`Hit at ${hit}`);
}
new BoundingBox(center?: Vec3, halfExtents?: Vec3)
Create a new BoundingBox instance. The bounding box is axis-aligned.
Parameters
center (Vec3, optional): Center of box. The constructor copies this parameter. Defaults to
(0, 0, 0).halfExtents (Vec3, optional): Half the distance across the box in each axis. The constructor
copies this parameter. Defaults to (0.5, 0.5, 0.5).readonly center: Vec3
Center of box.
readonly halfExtents: Vec3
Half the distance across the box in each axis.
add(other: BoundingBox): void
Combines two bounding boxes into one, enclosing both.
Parameters
other (BoundingBox): Bounding box to add.clone(): BoundingBox
Returns a clone of the AABB.
Returns BoundingBox: A duplicate AABB.
closestPoint(point: Vec3, result?: Vec3): Vec3
Return the point on the AABB closest to a given point. If the point is inside the AABB, the point itself is returned.
Parameters
point (Vec3): Point to find the closest point to.result (Vec3, optional): The vector to store the result in. If not provided, a new Vec3 is
created and returned.Returns Vec3: The closest point on the AABB.
Example
const box = new BoundingBox(new Vec3(0, 0, 0), new Vec3(1, 1, 1));
const point = new Vec3(2, 0, 0);
const closest = box.closestPoint(point); // Returns Vec3(1, 0, 0)
Example
// Reuse a result vector to avoid allocations in hot paths
const result = new Vec3();
box.closestPoint(point, result);
compute(vertices: ArrayLike<number>, numVerts?: number): void
Compute the size of the AABB to encapsulate all specified vertices.
Parameters
vertices (ArrayLike<number>): The vertices used to compute the new size for the
AABB.numVerts (number, optional): Number of vertices to use from the beginning of vertices array.
All vertices are used if not specified.containsPoint(point: Vec3): boolean
Test if a point is inside an AABB.
Parameters
point (Vec3): Point to test.Returns boolean: True if the point is inside the AABB and false otherwise.
copy(src: BoundingBox): void
Copies the contents of a source AABB.
Parameters
src (BoundingBox): The AABB to copy from.equals(other: BoundingBox): boolean
Reports whether two axis-aligned bounding boxes are equal.
Parameters
other (BoundingBox): The AABB to compare to.Returns boolean: True if the AABBs have the same center and half extents, false otherwise.
getMax(): Vec3
Return the maximum corner of the AABB.
Returns Vec3: Maximum corner.
getMin(): Vec3
Return the minimum corner of the AABB.
Returns Vec3: Minimum corner.
intersects(other: BoundingBox): boolean
Test whether two axis-aligned bounding boxes intersect.
Parameters
other (BoundingBox): Bounding box to test against.Returns boolean: True if there is an intersection.
intersectsBoundingSphere(sphere: BoundingSphere): boolean
Test if a Bounding Sphere is overlapping, enveloping, or inside this AABB.
Parameters
sphere (BoundingSphere): Bounding Sphere to test.Returns boolean: True if the Bounding Sphere is overlapping, enveloping, or inside the
AABB and false otherwise.
intersectsRay(ray: Ray, point?: Vec3): boolean
Test if a ray intersects with the AABB.
Parameters
ray (Ray): Ray to test against (direction must be normalized).point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
setFromTransformedAabb(aabb: BoundingBox, m: Mat4, ignoreScale?: boolean): void
Set an AABB to enclose the specified AABB if it were to be transformed by the specified 4x4 matrix.
Parameters
aabb (BoundingBox): Box to transform and enclose.m (Mat4): Transformation matrix to apply to source AABB.ignoreScale (boolean, optional, default false): If true is specified, a scale from the matrix is ignored. Defaults to false.setMinMax(min: Vec3, max: Vec3): void
Sets the minimum and maximum corner of the AABB. Using this function is faster than assigning min and max separately.
Parameters
static computeMinMax(vertices: ArrayLike<number>, min: Vec3, max: Vec3, numVerts?: number): void
Compute the min and max bounding values to encapsulate all specified vertices.
Parameters
Class · category: Math
A bounding sphere is a volume for facilitating fast intersection testing.
A sphere is a center and a radius. It is the cheapest bounding volume to test, so it suits broad-phase checks made before a finer test. containsPoint, intersectsBoundingSphere and intersectsRay return a boolean and allocate nothing. Unlike BoundingBox, the constructor keeps a reference to the center vector it is given rather than copying it, so the sphere follows any later changes to that vector.
Example
// A trigger volume 2 units around an entity
const sphere = new BoundingSphere(entity.getPosition().clone(), 2);
if (sphere.containsPoint(player.getPosition())) {
// the player is within 2 units of the entity
}
new BoundingSphere(center?: Vec3, radius?: number)
Creates a new BoundingSphere instance.
Parameters
center (Vec3, optional): The world space coordinate marking the center of the sphere. The
constructor takes a reference of this parameter.radius (number, optional, default 0.5): The radius of the bounding sphere. Defaults to 0.5.Example
// Create a new bounding sphere centered on the origin with a radius of 0.5
const sphere = new BoundingSphere();
readonly center: Vec3
Center of sphere.
radius: number
The radius of the bounding sphere.
containsPoint(point: Vec3): boolean
Test if a point is inside the sphere.
Parameters
point (Vec3): Point to test.Returns boolean: True if the point is inside the sphere and false otherwise.
Example
const sphere = new BoundingSphere(new Vec3(0, 0, 0), 1);
const point = new Vec3(0.5, 0, 0);
const isInside = sphere.containsPoint(point); // true
intersectsBoundingSphere(sphere: BoundingSphere): boolean
Test if a Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere.
Parameters
sphere (BoundingSphere): Bounding Sphere to test.Returns boolean: True if the Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere and false otherwise.
intersectsRay(ray: Ray, point?: Vec3): boolean
Test if a ray intersects with the sphere.
Parameters
ray (Ray): Ray to test against (direction must be normalized).point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
Class · category: Math
An RGBA color.
Each color component is a floating point value in the range 0 to 1. The r (red), g (green) and b (blue) components define a color in RGB color space. The a (alpha) component defines transparency. An alpha of 1 is fully opaque. An alpha of 0 is fully transparent.
A Color stores the values it is given and does not track whether they are in linear or gamma
(sRGB) space. Convert explicitly with linear and gamma when a value crosses that
boundary. fromString and toString exchange colors with the #RRGGBB and
#RRGGBBAA notation used by CSS, and lerp blends two colors.
Methods modify the color they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. The named constants such as WHITE and RED are frozen shared instances, so copy one before modifying it.
Example
// Set a material color from a CSS hex string
material.diffuse.fromString('#ff8800');
material.update();
Example
// Fade between two colors without allocating
const tint = new Color();
tint.lerp(Color.RED, Color.BLUE, t);
new Color(r?: number, g?: number, b?: number, a?: number)
Creates a new Color instance.
Parameters
r (number, optional): The r value. Defaults to 0.g (number, optional): The g value. Defaults to 0.b (number, optional): The b value. Defaults to 0.a (number, optional): The a value. Defaults to 1.Example
const c1 = new Color(); // defaults to 0, 0, 0, 1
const c2 = new Color(0.1, 0.2, 0.3, 0.4);
new Color(arr: number[])
Creates a new Color instance.
Parameters
arr (number[]): The array to set the color values from.Example
const c = new Color([0.1, 0.2, 0.3, 0.4]);
a: number
The alpha component of the color.
b: number
The blue component of the color.
g: number
The green component of the color.
r: number
The red component of the color.
static readonly BLACK: Color
A constant color set to black [0, 0, 0, 1].
static readonly BLUE: Color
A constant color set to blue [0, 0, 1, 1].
static readonly CYAN: Color
A constant color set to cyan [0, 1, 1, 1].
static readonly GRAY: Color
A constant color set to gray [0.5, 0.5, 0.5, 1].
static readonly GREEN: Color
A constant color set to green [0, 1, 0, 1].
static readonly MAGENTA: Color
A constant color set to magenta [1, 0, 1, 1].
static readonly RED: Color
A constant color set to red [1, 0, 0, 1].
static readonly WHITE: Color
A constant color set to white [1, 1, 1, 1].
static readonly YELLOW: Color
A constant color set to yellow [1, 1, 0, 1].
clone(): Color
Returns a clone of the specified color.
Returns Color: A duplicate color object.
Example
const c = new Color(1, 0, 0, 1);
const cClone = c.clone();
// cClone is [1, 0, 0, 1]
copy(rhs: Color): Color
Copies the contents of a source color to a destination color.
Parameters
rhs (Color): A color to copy to the specified color.Returns Color: Self for chaining.
Example
const src = new Color(1, 0, 0, 1);
const dst = new Color();
dst.copy(src);
console.log("The two colors are " + (dst.equals(src) ? "equal" : "different"));
equals(rhs: Color): boolean
Reports whether two colors are equal.
Parameters
rhs (Color): The color to compare to the specified color.Returns boolean: True if the colors are equal and false otherwise.
Example
const a = new Color(1, 0, 0, 1);
const b = new Color(1, 1, 0, 1);
console.log("The two colors are " + (a.equals(b) ? "equal" : "different"));
fromArray(arr: number[], offset?: number): Color
Set the values of the color from an array.
Parameters
arr (number[]): The array to set the color values from.offset (number, optional, default 0): The zero-based index at which to start copying elements from the
array. Default is 0.Returns Color: Self for chaining.
Example
const c = new Color();
c.fromArray([1, 0, 1, 1]);
// c is set to [1, 0, 1, 1]
fromString(hex: string): Color
Set the values of the color from a string representation '#11223344' or '#112233'.
Parameters
hex (string): A string representation in the format '#RRGGBBAA' or '#RRGGBB'. Where
RR, GG, BB, AA are red, green, blue and alpha values. This is the same format used in
HTML/CSS.Returns Color: Self for chaining.
Example
const c = new Color();
c.fromString('#ff0000');
// c is now [1, 0, 0, 1]
gamma(src?: Color): Color
Converts the color from linear to gamma color space.
Parameters
src (Color, optional): The color to convert to gamma color space. If not set, the operation is
done in place.Returns Color: Self for chaining.
Example
const c = new Color(0.218, 0.218, 0.218, 1);
c.gamma();
// c is now approximately [0.5, 0.5, 0.5, 1]
lerp(lhs: Color, rhs: Color, alpha: number): Color
Returns the result of a linear interpolation between two specified colors.
Parameters
lhs (Color): The color to interpolate from.rhs (Color): The color to interpolate to.alpha (number): The value controlling the point of interpolation. Between 0 and 1,
the linear interpolant will occur on a straight line between lhs and rhs. Outside of this
range, the linear interpolant will occur on a ray extrapolated from this line.Returns Color: Self for chaining.
Example
const a = new Color(0, 0, 0);
const b = new Color(1, 1, 0.5);
const r = new Color();
r.lerp(a, b, 0); // r is equal to a
r.lerp(a, b, 0.5); // r is 0.5, 0.5, 0.25
r.lerp(a, b, 1); // r is equal to b
linear(src?: Color): Color
Converts the color from gamma to linear color space.
Parameters
src (Color, optional): The color to convert to linear color space. If not set, the operation
is done in place.Returns Color: Self for chaining.
Example
const c = new Color(0.5, 0.5, 0.5, 1);
c.linear();
// c is now approximately [0.218, 0.218, 0.218, 1]
mulScalar(scalar: number): Color
Multiplies RGB elements of a Color by a number. Note that the alpha value is left unchanged.
Parameters
scalar (number): The number to multiply by.Returns Color: Self for chaining.
Example
const c = new Color(0.2, 0.4, 0.6, 1);
c.mulScalar(2);
// c is now [0.4, 0.8, 1.2, 1]
set(r: number, g: number, b: number, a?: number): Color
Assign values to the color components, including alpha.
Parameters
r (number): The value for red (0-1).g (number): The value for green (0-1).b (number): The value for blue (0-1).a (number, optional, default 1): The value for the alpha (0-1), defaults to 1.Returns Color: Self for chaining.
Example
const c = new Color();
c.set(1, 0, 0, 1);
// c is now red [1, 0, 0, 1]
toArray(arr?: number[], offset?: number): number[]
Parameters
arr (number[], optional): The array to populate with the color's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns number[]: The color as an array.
toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView
Parameters
arr (ArrayBufferView): The array to populate with the color's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns ArrayBufferView: The color as an array.
toString(alpha: boolean, asArray?: boolean): string
Converts the color to string form. The format is '#RRGGBBAA', where RR, GG, BB, AA are the red, green, blue and alpha values. When the alpha value is not included (the default), this is the same format as used in HTML/CSS.
Parameters
alpha (boolean): If true, the output string will include the alpha value.asArray (boolean, optional): If true, the output will be an array of numbers. Defaults to false.Returns string: The color in string form.
Example
const c = new Color(1, 1, 1);
// Outputs #ffffff
console.log(c.toString());
Class · category: Math
A curve is a collection of keys (time/value pairs). The shape of the curve is defined by its type that specifies an interpolation scheme for the keys.
Keys are kept sorted by time. Supply them to the constructor as a flat [time, value, ...] array
or insert them one at a time with add, then evaluate the curve at any time with
value. The type selects how values between keys are computed:
CURVE_LINEAR, CURVE_SMOOTHSTEP, CURVE_SPLINE or CURVE_STEP.
Curves drive values that change over time or over a normalized range, such as particle size over
a particle's lifetime.
Example
// Ease a value in over one second and read it back a quarter of the way through
const curve = new Curve([0, 0, 1, 1]);
curve.type = CURVE_SMOOTHSTEP;
const v = curve.value(0.25);
new Curve(data?: number[])
Creates a new Curve instance.
Parameters
data (number[], optional): An array of keys (pairs of numbers with the time first and value
second).Example
const curve = new Curve([
0, 0, // At 0 time, value of 0
0.33, 2, // At 0.33 time, value of 2
0.66, 2.6, // At 0.66 time, value of 2.6
1, 3 // At 1 time, value of 3
]);
keys: number[][] = []
The keys that define the curve. Each key is an array of two numbers with the time first and the value second.
tension: number = 0.5
Controls how CURVE_SPLINE tangents are calculated. Valid range is between 0 and 1 where 0 results in a non-smooth curve (equivalent to linear interpolation) and 1 results in a very smooth curve. Use 0.5 for a Catmull-Rom spline.
type: number = CURVE_SMOOTHSTEP
The curve interpolation scheme. Can be:
Defaults to CURVE_SMOOTHSTEP.
get length(): number
Gets the number of keys in the curve.
add(time: number, value: number): number[]
Adds a new key to the curve.
Parameters
time (number): Time to add new key.value (number): Value of new key.Returns number[]: The newly created [time, value] pair.
Example
const curve = new Curve();
curve.add(0, 1); // add key at time 0 with value 1
curve.add(1, 2); // add key at time 1 with value 2
clear(): Curve
Removes all keys from the curve.
Returns Curve: The curve instance.
Example
const curve = new Curve([0, 1, 1, 2]);
curve.clear(); // curve now has no keys
clone(): Curve
Returns a clone of the specified curve object.
Returns Curve: A clone of the specified curve.
Example
const curve = new Curve([0, 0, 1, 10]);
const clonedCurve = curve.clone();
closest(time: number): number[] | null
Returns the key closest to the specified time. When two keys are equally close, the later one is returned.
Parameters
time (number): The time to find the closest key to.Returns number[] | null: The [time, value] pair closest to the specified time, or null if
no keys exist.
Example
const curve = new Curve([0, 1, 0.5, 2, 1, 3]);
const key = curve.closest(0.6); // returns [0.5, 2]
get(index: number): number[]
Gets the [time, value] pair at the specified index.
Parameters
index (number): The index of key to return.Returns number[]: The [time, value] pair at the specified index.
Example
const curve = new Curve([0, 1, 1, 2]);
const key = curve.get(0); // returns [0, 1]
remove(index: number): number[] | null
Removes the key at the specified index.
Parameters
index (number): The index of the key to remove.Returns number[] | null: The removed [time, value] pair, or null if the index is out of
range.
Example
const curve = new Curve([0, 1, 1, 2]);
curve.remove(0); // removes the key at time 0
sort(): void
Sorts keys by time.
value(time: number): number
Returns the interpolated value of the curve at specified time.
Parameters
time (number): The time at which to calculate the value.Returns number: The interpolated value.
Example
const curve = new Curve([0, 0, 1, 10]);
const value = curve.value(0.5); // returns interpolated value at time 0.5
Class · category: Math
A curve set is a collection of curves that share a time axis and are evaluated together, such as the three channels of a color or the components of a vector changing over time.
Build one from an array of [time, value, ...] key arrays, one per curve, or from a number of
empty curves. Setting type applies that interpolation to every curve in the set, and
value returns the value of each curve at a time as one array. Reach an individual
Curve with get.
Example
// Animate an RGB color over time and sample it at the midpoint
const colorOverTime = new CurveSet([
[0, 1, 1, 0], // red: 1 at t = 0, 0 at t = 1
[0, 0, 1, 1], // green: 0 at t = 0, 1 at t = 1
[0, 0, 1, 0] // blue: 0 throughout
]);
const [r, g, b] = colorOverTime.value(0.5);
new CurveSet(...args: any[])
Creates a new CurveSet instance.
Parameters
args (any[]): Variable arguments with several possible formats:
Example
// Create from an array of arrays of keys
const curveSet = new CurveSet([
[
0, 0, // At 0 time, value of 0
0.33, 2, // At 0.33 time, value of 2
0.66, 2.6, // At 0.66 time, value of 2.6
1, 3 // At 1 time, value of 3
],
[
0, 34,
0.33, 35,
0.66, 36,
1, 37
]
]);
curves: Curve[] = []
The array of curves in the set.
get length(): number
Gets the number of curves in the curve set.
get type(): number
set type(value: number)
Gets the interpolation scheme applied to all curves in the curve set.
add(data?: number[]): Curve
Appends a new curve to the curve set. The new curve adopts the curve set's current CurveSet#type interpolation scheme, so that all curves in the set continue to share the same type.
Parameters
data (number[], optional): An array of keys (pairs of numbers with the time first and value
second) for the new curve.Returns Curve: The newly created curve.
Example
const curveSet = new CurveSet([[0, 0, 1, 1]]);
const curve = curveSet.add([0, 0, 1, 0.5]); // append a second curve
clear(): CurveSet
Removes all curves from the curve set, leaving it empty.
Returns CurveSet: The curve set instance.
Example
const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.clear(); // the set now has no curves
clearKeys(): CurveSet
Removes all keys from every curve in the set, while keeping the curves themselves. The number of curves is unchanged, so CurveSet#value still returns an array of the same length.
Returns CurveSet: The curve set instance.
Example
const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.clearKeys(); // both curves are now empty, but the set still has 2 curves
clone(): CurveSet
Returns a clone of the specified curve set object.
Returns CurveSet: A clone of the specified curve set.
Example
const curveSet = new CurveSet([[0, 0, 1, 1]]);
const clonedCurveSet = curveSet.clone();
get(index: number): Curve
Return a specific curve in the curve set.
Parameters
index (number): The index of the curve to return.Returns Curve: The curve at the specified index.
Example
const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
const curve = curveSet.get(0); // returns the first curve
remove(indexOrCurve: number | Curve): Curve | null
Removes a curve from the curve set.
Parameters
indexOrCurve (number | Curve): The index of the curve to remove, or the curve instance
itself.Returns Curve | null: The removed curve, or null if it was not found.
Example
const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.remove(0); // remove by index
curveSet.remove(curveSet.get(0)); // or remove by reference
value(time: number, result?: number[]): number[]
Returns the interpolated value of all curves in the curve set at the specified time.
Parameters
time (number): The time at which to calculate the value.result (number[], optional, default []): The interpolated curve values at the specified time. If this
parameter is not supplied, the function allocates a new array internally to return the
result.Returns number[]: The interpolated curve values at the specified time.
Example
const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
const values = curveSet.value(0.5); // returns interpolated values for all curves at time 0.5
Class · category: Math
Utility static class providing functionality to pack float values to various storage representations.
float2Half converts a JavaScript number to the 16-bit half-float encoding used by half-precision textures and vertex formats, so float data can be uploaded to the GPU at half the size.
Example
// Fill a half-float buffer from an array of numbers
const halves = new Uint16Array(values.length);
for (let i = 0; i < values.length; i++) {
halves[i] = FloatPacking.float2Half(values[i]);
}
static float2Half(value: number): number
Packs a float to a 16-bit half-float representation used by the GPU.
Parameters
value (number): The float value to pack.Returns number: The 16-bit half-float representation as an integer.
Example
const half = FloatPacking.float2Half(1.5);
Class · category: Math
A frustum is a shape that defines the viewing space of a camera. It can be used to determine visibility of points and bounding spheres. Typically, you would not create a Frustum shape directly, but instead query CameraComponent#frustum.
A frustum is six Planes, read and written with getPlane and setPlane, and normally derived from a camera's combined view-projection matrix with setFromMat4. containsPoint and containsAabb return a boolean. containsSphere returns 0 for a sphere outside, 1 for one that intersects and 2 for one fully inside, so callers can skip finer tests for objects that are entirely visible. None of the tests allocate.
Example
// Skip work for objects the camera cannot see
const frustum = entity.camera.frustum;
if (frustum.containsAabb(meshInstance.aabb)) {
// visible: update it
}
new Frustum()
Create a new Frustum instance.
Example
const frustum = new Frustum();
add(other: Frustum): Frustum
Expands this frustum to also contain another frustum. The other frustum's 8 corner points are computed, and each of this frustum's planes is pushed outwards just far enough to contain them all. The result is a conservative convex volume that contains both frustums. This is useful for multi-view rendering such as stereo XR, where culling should keep objects visible in any view.
Note: keeping each plane's orientation makes this correct for arbitrary frusta, including the asymmetric per-eye projections of XR headsets, where matching planes of the two eyes have different normals and a per-plane "outermost" selection would wrongly cut into the combined volume at a distance.
Parameters
other (Frustum): The other frustum to add.Returns Frustum: Self for chaining.
clone(): Frustum
Returns a clone of the specified frustum.
Returns Frustum: A duplicate frustum.
Example
const frustum = new Frustum();
const clone = frustum.clone();
containsAabb(aabb: BoundingBox): boolean
Tests whether an axis aligned bounding box intersects the frustum.
The test is conservative in the same way the plane based sphere test is: a box lying just outside a frustum corner can be reported as intersecting. It is however always at least as tight as testing the box's bounding sphere, since the extent of a box along a plane normal never exceeds the radius of its bounding sphere.
Unlike Frustum#containsSphere, a box completely inside the frustum is not distinguished from one merely intersecting it. Detecting that costs a comparison per plane and no caller needs it.
Parameters
aabb (BoundingBox): The bounding box to test.Returns boolean: True if the bounding box intersects or is inside the frustum, false if it
is completely outside.
containsPoint(point: Vec3): boolean
Tests whether a point is inside the frustum. Note that points lying in a frustum plane are considered to be outside the frustum.
Parameters
point (Vec3): The point to test.Returns boolean: True if the point is inside the frustum, false otherwise.
containsSphere(sphere: BoundingSphere): number
Tests whether a bounding sphere intersects the frustum. If the sphere is outside the frustum, zero is returned. If the sphere intersects the frustum, 1 is returned. If the sphere is completely inside the frustum, 2 is returned. Note that a sphere touching a frustum plane from the outside is considered to be outside the frustum.
Parameters
sphere (BoundingSphere): The sphere to test.Returns number: 0 if the bounding sphere is outside the frustum, 1 if it intersects the
frustum and 2 if it is contained by the frustum.
copy(src: Frustum): Frustum
Copies the contents of a source frustum to a destination frustum.
Parameters
src (Frustum): A source frustum to copy to the destination frustum.Returns Frustum: Self for chaining.
Example
const src = entity.camera.frustum;
const dst = new Frustum();
dst.copy(src);
getPlane(index: number, result: Plane): Plane
Returns one of the frustum's six planes. The planes are ordered right, left, bottom, top, far, near, and their normals point inwards.
Parameters
index (number): The index of the plane, from 0 to 5.result (Plane): The plane to write to.Returns Plane: The supplied plane, containing the frustum plane.
Example
const plane = new Plane();
entity.camera.frustum.getPlane(0, plane);
setFromMat4(matrix: Mat4): void
Updates the frustum shape based on the supplied 4x4 matrix.
Parameters
matrix (Mat4): The matrix describing the shape of the frustum.Example
// Create a perspective projection matrix
const projection = new Mat4();
projection.setPerspective(45, 16 / 9, 1, 1000);
// Create a frustum shape that is represented by the matrix
const frustum = new Frustum();
frustum.setFromMat4(projection);
setPlane(index: number, plane: Plane): Frustum
Sets one of the frustum's six planes. The plane is normalized as it is stored, as the frustum's tests require unit length normals. The planes are ordered right, left, bottom, top, far, near, and their normals must point inwards.
Parameters
index (number): The index of the plane, from 0 to 5.plane (Plane): The plane to store.Returns Frustum: Self for chaining.
Class · category: Math
Sampling kernels: sets of 2D offsets, generated on demand, used to take several samples around a point, as blur, soft shadow and ambient occlusion effects do.
concentric produces a center point followed by points arranged in evenly spaced rings out
to a radius of one, returned as a flat [x, y, x, y, ...] array ready to upload as a shader
uniform.
Example
// A kernel with 3 rings and 8 points in the innermost ring
const offsets = Kernel.concentric(3, 8); // [0, 0, x1, y1, x2, y2, ...]
static concentric(numRings: number, numPoints: number): number[]
Generate a set of points distributed in a series of concentric rings around the origin. The spacing between points is determined by the number of points in the first ring, and subsequent rings maintain this spacing by adjusting their number of points accordingly.
Parameters
numRings (number): The number of concentric rings to generate.numPoints (number): The number of points in the first ring.Returns number[]: An array where each point is represented by two consecutive numbers (x, y).
Example
// Generate a kernel with 3 rings and 8 points in the first ring
const kernel = Kernel.concentric(3, 8);
// kernel is a flat array: [x0, y0, x1, y1, x2, y2, ...]
Class · category: Math
A 3x3 matrix. Mat3 is commonly used to represent rotation matrices, 2D transformations or the upper-left portion of a 4x4 matrix for transforming normals.
A new Mat3 is the identity. Elements live in data, a 9-element Float32Array in
column-major order, so the first three entries are the first column. Build one from a rotation
with setFromQuat, or take the upper-left 3x3 of a Mat4 with setFromMat4,
and apply it to a Vec3 with transformVector. getX, getY and
getZ read the columns, which for a rotation matrix are its axes.
Methods modify the matrix they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. IDENTITY and ZERO are frozen shared instances.
Example
// Take the rotation and scale of an entity's world transform and apply it to a direction
const rotationScale = new Mat3().setFromMat4(entity.getWorldTransform());
const worldDirection = rotationScale.transformVector(localDirection);
new Mat3()
Create a new Mat3 instance. It is initialized to the identity matrix.
data: Float32Array<ArrayBufferLike>
Matrix elements in the form of a flat array.
static readonly IDENTITY: Mat3
A constant matrix set to the identity.
static readonly ZERO: Mat3
A constant matrix with all elements set to 0.
clone(): Mat3
Creates a duplicate of the specified matrix.
Returns Mat3: A duplicate matrix.
Example
const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const dst = src.clone();
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
copy(rhs: Mat3): Mat3
Copies the contents of a source 3x3 matrix to a destination 3x3 matrix.
Parameters
rhs (Mat3): A 3x3 matrix to be copied.Returns Mat3: Self for chaining.
Example
const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const dst = new Mat3();
dst.copy(src);
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
equals(rhs: Mat3): boolean
Reports whether two matrices are equal.
Parameters
rhs (Mat3): The other matrix.Returns boolean: True if the matrices are equal and false otherwise.
Example
const a = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const b = new Mat3();
console.log("The two matrices are " + (a.equals(b) ? "equal" : "different"));
getX(x?: Vec3): Vec3
Extracts the x-axis from the specified matrix.
Parameters
x (Vec3, optional): The vector to receive the x axis of the matrix.Returns Vec3: The x-axis of the specified matrix.
Example
const m = new Mat3();
const xAxis = m.getX(); // Vec3(1, 0, 0) for identity matrix
getY(y?: Vec3): Vec3
Extracts the y-axis from the specified matrix.
Parameters
y (Vec3, optional): The vector to receive the y axis of the matrix.Returns Vec3: The y-axis of the specified matrix.
Example
const m = new Mat3();
const yAxis = m.getY(); // Vec3(0, 1, 0) for identity matrix
getZ(z?: Vec3): Vec3
Extracts the z-axis from the specified matrix.
Parameters
z (Vec3, optional): The vector to receive the z axis of the matrix.Returns Vec3: The z-axis of the specified matrix.
Example
const m = new Mat3();
const zAxis = m.getZ(); // Vec3(0, 0, 1) for identity matrix
isIdentity(): boolean
Reports whether the specified matrix is the identity matrix.
Returns boolean: True if the matrix is identity and false otherwise.
Example
const m = new Mat3();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
set(src: number[]): Mat3
Copies the contents of a source array[9] to a destination 3x3 matrix.
Parameters
src (number[]): An array[9] to be copied.Returns Mat3: Self for chaining.
Example
const dst = new Mat3();
dst.set([0, 1, 2, 3, 4, 5, 6, 7, 8]);
setFromMat4(m: Mat4): Mat3
Converts the specified 4x4 matrix to a Mat3.
Parameters
m (Mat4): The 4x4 matrix to convert.Returns Mat3: Self for chaining.
Example
const m4 = new Mat4();
const m3 = new Mat3().setFromMat4(m4);
setFromQuat(r: Quat): Mat3
Sets this matrix to the given quaternion rotation.
Parameters
r (Quat): A quaternion rotation.Returns Mat3: Self for chaining.
Example
const r = new Quat(1, 2, 3, 4).normalize();
const m = new Mat3();
m.setFromQuat(r);
setIdentity(): Mat3
Sets the matrix to the identity matrix.
Returns Mat3: Self for chaining.
Example
m.setIdentity();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
toString(): string
Converts the matrix to string form.
Returns string: The matrix in string form.
Example
const m = new Mat3();
// Outputs [1, 0, 0, 0, 1, 0, 0, 0, 1]
console.log(m.toString());
transformVector(vec: Vec3, res?: Vec3): Vec3
Transforms a 3-dimensional vector by a 3x3 matrix.
Parameters
vec (Vec3): The 3-dimensional vector to be transformed.res (Vec3, optional): An optional 3-dimensional vector to receive the result of the
transformation.Returns Vec3: The input vector v transformed by the current instance.
Example
const m = new Mat3();
const v = new Vec3(1, 2, 3);
const result = m.transformVector(v);
transpose(src?: Mat3): Mat3
Generates the transpose of the specified 3x3 matrix.
Parameters
src (Mat3, optional): The matrix to transpose. If not set, the matrix is transposed in-place.Returns Mat3: Self for chaining.
Example
const m = new Mat3();
// Transpose in place
m.transpose();
Class · category: Math
A 4x4 matrix. Mat4 is commonly used to represent world, view and projection transformations in 3D graphics, combining rotation, translation and scale into a single matrix.
A new Mat4 is the identity. Elements live in data, a 16-element Float32Array in
column-major order: the translation occupies elements 12, 13 and 14. Build a transform with
setTRS, setFromEulerAngles or setFromAxisAngle, a camera matrix with
setLookAt, setPerspective or setOrtho, and read parts back with
getTranslation, getScale and getEulerAngles. Angles are in degrees.
Matrices combine by multiplication: r.mul2(a, b) computes a * b, so b is applied first when
the result transforms a point. transformPoint applies the full transform including
translation, while transformVector applies only rotation and scale, which is what
directions need.
Methods modify the matrix they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. IDENTITY and ZERO are frozen shared instances, and the matrix returned by GraphNode#getWorldTransform is internal storage to be treated as read-only.
Example
// Compose a transform from position, rotation and scale
const world = new Mat4().setTRS(
new Vec3(0, 1, 0),
new Quat().setFromEulerAngles(0, 45, 0),
Vec3.ONE
);
Example
// Transform a local point into world space
const worldPoint = entity.getWorldTransform().transformPoint(localPoint);
new Mat4()
Create a new Mat4 instance. It is initialized to the identity matrix.
data: Float32Array<ArrayBufferLike>
Matrix elements in the form of a flat array.
static readonly IDENTITY: Mat4
A constant matrix set to the identity.
static readonly ZERO: Mat4
A constant matrix with all elements set to 0.
add(rhs: Mat4): Mat4
Adds the specified 4x4 matrix to the current instance.
Parameters
rhs (Mat4): The 4x4 matrix used as the second operand of the addition.Returns Mat4: Self for chaining.
Example
const m = new Mat4();
m.add(Mat4.ONE);
console.log("The result of the addition is: " + m.toString());
add2(lhs: Mat4, rhs: Mat4): Mat4
Adds the specified 4x4 matrices together and stores the result in the current instance.
Parameters
lhs (Mat4): The 4x4 matrix used as the first operand of the addition.rhs (Mat4): The 4x4 matrix used as the second operand of the addition.Returns Mat4: Self for chaining.
Example
const m = new Mat4();
m.add2(Mat4.IDENTITY, Mat4.ONE);
console.log("The result of the addition is: " + m.toString());
clone(): Mat4
Creates a duplicate of the specified matrix.
Returns Mat4: A duplicate matrix.
Example
const src = new Mat4().setFromEulerAngles(10, 20, 30);
const dst = src.clone();
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
copy(rhs: Mat4): Mat4
Copies the contents of a source 4x4 matrix to a destination 4x4 matrix.
Parameters
rhs (Mat4): A 4x4 matrix to be copied.Returns Mat4: Self for chaining.
Example
const src = new Mat4().setFromEulerAngles(10, 20, 30);
const dst = new Mat4();
dst.copy(src);
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));
equals(rhs: Mat4): boolean
Reports whether two matrices are equal.
Parameters
rhs (Mat4): The other matrix.Returns boolean: True if the matrices are equal and false otherwise.
Example
const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4();
console.log("The two matrices are " + (a.equals(b) ? "equal" : "different"));
getEulerAngles(eulers?: Vec3): Vec3
Extracts the Euler angles equivalent to the rotational portion of the specified matrix. The returned Euler angles are in intrinsic XYZ order and in degrees.
Parameters
eulers (Vec3, optional): A 3-d vector to receive the Euler angles.Returns Vec3: A 3-d vector containing the Euler angles.
Example
// Create a 4x4 rotation matrix of 45 degrees around the y-axis
const m = new Mat4().setFromAxisAngle(Vec3.UP, 45);
const eulers = m.getEulerAngles();
getScale(scale?: Vec3): Vec3
Extracts the scale component from the specified 4x4 matrix.
Parameters
scale (Vec3, optional): Vector to receive the scale.Returns Vec3: The scale in X, Y and Z of the specified 4x4 matrix.
Example
// Query the scale component
const scale = m.getScale();
getTranslation(t?: Vec3): Vec3
Extracts the translational component from the specified 4x4 matrix.
Parameters
t (Vec3, optional): The vector to receive the translation of the matrix.Returns Vec3: The translation of the specified 4x4 matrix.
Example
// Create a 4x4 matrix
const m = new Mat4();
// Query the translation component
const t = new Vec3();
m.getTranslation(t);
getX(x?: Vec3): Vec3
Extracts the x-axis from the specified 4x4 matrix.
Parameters
x (Vec3, optional): The vector to receive the x axis of the matrix.Returns Vec3: The x-axis of the specified 4x4 matrix.
Example
// Create a 4x4 matrix
const m = new Mat4();
// Query the x-axis component
const x = new Vec3();
m.getX(x);
getY(y?: Vec3): Vec3
Extracts the y-axis from the specified 4x4 matrix.
Parameters
y (Vec3, optional): The vector to receive the y axis of the matrix.Returns Vec3: The y-axis of the specified 4x4 matrix.
Example
// Create a 4x4 matrix
const m = new Mat4();
// Query the y-axis component
const y = new Vec3();
m.getY(y);
getZ(z?: Vec3): Vec3
Extracts the z-axis from the specified 4x4 matrix.
Parameters
z (Vec3, optional): The vector to receive the z axis of the matrix.Returns Vec3: The z-axis of the specified 4x4 matrix.
Example
// Create a 4x4 matrix
const m = new Mat4();
// Query the z-axis component
const z = new Vec3();
m.getZ(z);
invert(src?: Mat4): Mat4
Sets the matrix to the inverse of a source matrix.
Parameters
src (Mat4, optional): The matrix to invert. If not set, the matrix is inverted in-place.Returns Mat4: Self for chaining.
Example
// Create a 4x4 rotation matrix of 180 degrees around the y-axis
const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180);
// Invert in place
rot.invert();
isIdentity(): boolean
Reports whether the specified matrix is the identity matrix.
Returns boolean: True if the matrix is identity and false otherwise.
Example
const m = new Mat4();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
mul(rhs: Mat4): Mat4
Multiplies the current instance by the specified 4x4 matrix.
Parameters
rhs (Mat4): The 4x4 matrix used as the second multiplicand of the operation.Returns Mat4: Self for chaining.
Example
const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);
// a = a * b
a.mul(b);
console.log("The result of the multiplication is: " + a.toString());
mul2(lhs: Mat4, rhs: Mat4): Mat4
Multiplies the specified 4x4 matrices together and stores the result in the current instance.
Parameters
lhs (Mat4): The 4x4 matrix used as the first multiplicand of the operation.rhs (Mat4): The 4x4 matrix used as the second multiplicand of the operation.Returns Mat4: Self for chaining.
Example
const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);
const r = new Mat4();
// r = a * b
r.mul2(a, b);
console.log("The result of the multiplication is: " + r.toString());
mulAffine2(lhs: Mat4, rhs: Mat4): Mat4
Multiplies the specified 4x4 matrices together and stores the result in the current instance. This function assumes the matrices are affine transformation matrices, where the upper left 3x3 elements are a rotation matrix, and the bottom left 3 elements are translation. The rightmost column is assumed to be [0, 0, 0, 1]. The parameters are not verified to be in the expected format. This function is faster than general mul2.
Parameters
lhs (Mat4): The affine transformation 4x4 matrix used as the first multiplicand of
the operation.rhs (Mat4): The affine transformation 4x4 matrix used as the second multiplicand of
the operation.Returns Mat4: Self for chaining.
Example
const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);
const r = new Mat4();
// r = a * b (optimized for affine transforms)
r.mulAffine2(a, b);
set(src: number[]): Mat4
Sets matrix data from an array.
Parameters
src (number[]): Source array. Must have 16 values.Returns Mat4: Self for chaining.
Example
const m = new Mat4();
m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]);
setFromAxisAngle(axis: Vec3, angle: number): Mat4
Sets the specified matrix to a rotation matrix equivalent to a rotation around an axis. The axis must be normalized (unit length) and the angle must be specified in degrees.
Parameters
axis (Vec3): The normalized axis vector around which to rotate.angle (number): The angle of rotation in degrees.Returns Mat4: Self for chaining.
Example
// Create a 4x4 rotation matrix
const rm = new Mat4().setFromAxisAngle(Vec3.UP, 90);
setFromEulerAngles(ex: number, ey: number, ez: number): Mat4
Sets the specified matrix to a rotation matrix defined by Euler angles. The rotation is applied using an intrinsic XYZ order: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis. Angles are specified in degrees.
Parameters
ex (number): Angle to rotate around X axis in degrees.ey (number): Angle to rotate around Y axis in degrees.ez (number): Angle to rotate around Z axis in degrees.Returns Mat4: Self for chaining.
Example
const m = new Mat4();
m.setFromEulerAngles(45, 90, 180);
setIdentity(): Mat4
Sets the specified matrix to the identity matrix.
Returns Mat4: Self for chaining.
Example
m.setIdentity();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));
setLookAt(position: Vec3, target: Vec3, up: Vec3): Mat4
Sets the specified matrix to a viewing matrix derived from an eye point, a target point and an up vector. The matrix maps the target point to the negative z-axis and the eye point to the origin, so that when you use a typical projection matrix, the center of the scene maps to the center of the viewport. Similarly, the direction described by the up vector projected onto the viewing plane is mapped to the positive y-axis so that it points upward in the viewport. The up vector must not be parallel to the line of sight from the eye to the reference point.
Parameters
position (Vec3): 3-d vector holding view position.target (Vec3): 3-d vector holding reference point.up (Vec3): 3-d vector holding the up direction.Returns Mat4: Self for chaining.
Example
const position = new Vec3(10, 10, 10);
const target = new Vec3(0, 0, 0);
const up = new Vec3(0, 1, 0);
const m = new Mat4().setLookAt(position, target, up);
setOrtho(left: number, right: number, bottom: number, top: number, near: number, far: number): Mat4
Sets the specified matrix to an orthographic projection matrix. The function's parameters define the shape of a cuboid-shaped frustum.
Parameters
left (number): The x-coordinate for the left edge of the camera's projection plane
in eye space.right (number): The x-coordinate for the right edge of the camera's projection plane
in eye space.bottom (number): The y-coordinate for the bottom edge of the camera's projection
plane in eye space.top (number): The y-coordinate for the top edge of the camera's projection plane in
eye space.near (number): The near clip plane in eye coordinates.far (number): The far clip plane in eye coordinates.Returns Mat4: Self for chaining.
Example
// Create a 4x4 orthographic projection matrix
const ortho = new Mat4().setOrtho(-2, 2, -2, 2, 1, 1000);
setPerspective(fov: number, aspect: number, znear: number, zfar: number, fovIsHorizontal?: boolean): Mat4
Sets the specified matrix to a perspective projection matrix. The function's parameters define the shape of a frustum.
Parameters
fov (number): The frustum's field of view in degrees. The fovIsHorizontal parameter
controls whether this is a vertical or horizontal field of view. By default, it's a vertical
field of view.aspect (number): The aspect ratio of the frustum's projection plane
(width / height).znear (number): The near clip plane in eye coordinates.zfar (number): The far clip plane in eye coordinates.fovIsHorizontal (boolean, optional): Set to true to treat the fov as horizontal (x-axis) and
false for vertical (y-axis). Defaults to false.Returns Mat4: Self for chaining.
Example
// Create a 4x4 perspective projection matrix
const persp = new Mat4().setPerspective(45, 16 / 9, 1, 1000);
setReflection(normal: Vec3, distance: number): Mat4
Sets the matrix to a reflection matrix, which can be used as a mirror transformation by the plane.
Parameters
normal (Vec3): The normal of the plane to reflect by.distance (number): The distance of plane to reflect by.Returns Mat4: Self for chaining.
Example
// Create a reflection matrix for a horizontal plane at y=0
const reflection = new Mat4().setReflection(Vec3.UP, 0);
setTRS(t: Vec3, r: Quat, s: Vec3): Mat4
Sets the specified matrix to the concatenation of a translation, a quaternion rotation and a scale.
Parameters
Returns Mat4: Self for chaining.
Example
const t = new Vec3(10, 20, 30);
const r = new Quat();
const s = new Vec3(2, 2, 2);
const m = new Mat4();
m.setTRS(t, r, s);
toString(): string
Converts the specified matrix to string form.
Returns string: The matrix in string form.
Example
const m = new Mat4();
// Outputs [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
console.log(m.toString());
transformPoint(vec: Vec3, res?: Vec3): Vec3
Transforms a 3-dimensional point by a 4x4 matrix.
Parameters
vec (Vec3): The 3-dimensional point to be transformed.res (Vec3, optional): An optional 3-dimensional point to receive the result of the
transformation.Returns Vec3: The input point v transformed by the current instance.
Example
// Create a 3-dimensional point
const v = new Vec3(1, 2, 3);
// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);
const tv = m.transformPoint(v);
transformVec4(vec: Vec4, res?: Vec4): Vec4
Transforms a 4-dimensional vector by a 4x4 matrix.
Parameters
vec (Vec4): The 4-dimensional vector to be transformed.res (Vec4, optional): An optional 4-dimensional vector to receive the result of the
transformation.Returns Vec4: The input vector v transformed by the current instance.
Example
// Create an input 4-dimensional vector
const v = new Vec4(1, 2, 3, 4);
// Create an output 4-dimensional vector
const result = new Vec4();
// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);
m.transformVec4(v, result);
transformVector(vec: Vec3, res?: Vec3): Vec3
Transforms a 3-dimensional vector by a 4x4 matrix.
Parameters
vec (Vec3): The 3-dimensional vector to be transformed.res (Vec3, optional): An optional 3-dimensional vector to receive the result of the
transformation.Returns Vec3: The input vector v transformed by the current instance.
Example
// Create a 3-dimensional vector
const v = new Vec3(1, 2, 3);
// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);
const tv = m.transformVector(v);
transpose(src?: Mat4): Mat4
Sets the matrix to the transpose of a source matrix.
Parameters
src (Mat4, optional): The matrix to transpose. If not set, the matrix is transposed in-place.Returns Mat4: Self for chaining.
Example
const m = new Mat4();
// Transpose in place
m.transpose();
Class · category: Math
An oriented bounding box is a box that can be rotated and translated in 3D space. It is defined by a world transform and half extents. Unlike an axis-aligned bounding box, an OBB can be oriented arbitrarily.
The constructor takes a Mat4 holding the box's position and rotation, then its half extents. Scale is assumed to be one, so size the box with the half extents rather than the matrix. worldTransform can be reassigned at any time and the setter copies the matrix, so assigning an entity's world transform each frame gives a box that follows it. The tests containsPoint, intersectsRay and intersectsBoundingSphere return a boolean and allocate nothing.
Example
// A 2 x 1 x 4 box that follows an entity
const box = new OrientedBox(entity.getWorldTransform(), new Vec3(1, 0.5, 2));
// later, after the entity has moved
box.worldTransform = entity.getWorldTransform();
if (box.containsPoint(player.getPosition())) {
// the player is inside the box
}
new OrientedBox(worldTransform?: Mat4, halfExtents?: Vec3)
Create a new OrientedBox instance.
Parameters
worldTransform (Mat4, optional): Transform that has the orientation and position of the box.
Scale is assumed to be one. Defaults to identity matrix.halfExtents (Vec3, optional): Half the distance across the box in each local axis. Defaults
to (0.5, 0.5, 0.5).get worldTransform(): Mat4
set worldTransform(value: Mat4)
Gets the world transform of the OBB.
containsPoint(point: Vec3): boolean
Test if a point is inside an OBB.
Parameters
point (Vec3): Point to test.Returns boolean: True if the point is inside the OBB and false otherwise.
intersectsBoundingSphere(sphere: BoundingSphere): boolean
Test if a Bounding Sphere is overlapping, enveloping, or inside this OBB.
Parameters
sphere (BoundingSphere): Bounding Sphere to test.Returns boolean: True if the Bounding Sphere is overlapping, enveloping or inside this OBB
and false otherwise.
intersectsRay(ray: Ray, point?: Vec3): boolean
Test if a ray intersects with the OBB.
Parameters
ray (Ray): Ray to test against (direction must be normalized).point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
Class · category: Math
An infinite plane. Internally, it's represented in a parametric equation form:
ax + by + cz + distance = 0.
A plane is a normal and a distance from the origin along that normal. Define one with the constructor or setFromPointNormal from a normal and a point the plane passes through, or with set from the four coefficients. None of these normalize the normal they are given, and distance is only a true distance when the normal is unit length, so call normalize afterwards if it is not. intersectsRay and intersectsLine return whether a hit occurred and write the hit point into an optional vector. The ray's direction must be normalized.
Example
// Find where a ray from the camera meets the ground plane at y = 0
const ground = new Plane(Vec3.UP, 0);
const hit = new Vec3();
if (ground.intersectsRay(ray, hit)) {
marker.setPosition(hit);
}
new Plane(normal?: Vec3, distance?: number)
Create a new Plane instance.
Parameters
normal (Vec3, optional, default Vec3.UP): Normal of the plane. The constructor copies this parameter. Defaults
to Vec3.UP.distance (number, optional, default 0): The distance from the plane to the origin, along its normal.
Defaults to 0.distance: number
The distance from the plane to the origin, along its normal.
normal: Vec3
The normal of the plane.
clone(): Plane
Returns a clone of the specified plane.
Returns Plane: A duplicate plane.
copy(src: Plane): Plane
Copies the contents of a source plane to a destination plane.
Parameters
src (Plane): A source plane to copy to the destination plane.Returns Plane: Self for chaining.
intersectsLine(start: Vec3, end: Vec3, point?: Vec3): boolean
Test if the plane intersects between two points.
Parameters
start (Vec3): Start position of line.end (Vec3): End position of line.point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
intersectsRay(ray: Ray, point?: Vec3): boolean
Test if a ray intersects with the infinite plane.
Parameters
ray (Ray): Ray to test against (direction must be normalized).point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
normalize(): Plane
Normalize the plane.
Returns Plane: Self for chaining.
set(nx: number, ny: number, nz: number, d: number): Plane
Sets the plane based on a normal and a distance from the origin.
Parameters
nx (number): The x-component of the normal.ny (number): The y-component of the normal.nz (number): The z-component of the normal.d (number): The distance from the origin.Returns Plane: Self for chaining.
setFromPointNormal(point: Vec3, normal: Vec3): Plane
Sets the plane based on a specified normal and a point on the plane.
Parameters
Returns Plane: Self for chaining.
Class · category: Math
A quaternion representing rotation in 3D space. Quaternions are typically used to represent rotations in 3D applications, offering advantages over Euler angles including no gimbal lock and more efficient interpolation.
A new Quat is the identity rotation. Build a rotation with setFromEulerAngles,
setFromAxisAngle, setFromDirections or setFromMat4, and read one back
with getEulerAngles or getAxisAngle. Angles are in degrees throughout. Rotations
combine by multiplication: a.mul(b) and r.mul2(a, b) both compute a * b, the same product
Mat4 uses, and transformVector applies a rotation to a Vec3. Interpolate
with slerp for constant angular speed, or with the cheaper lerp when the two
rotations are close together.
Methods modify the quaternion they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. The static constants IDENTITY and ZERO are frozen shared instances, and the quaternion returned by GraphNode#getRotation is internal storage to be treated as read-only.
Example
// Rotate an entity 90 degrees about the world Y axis
const rotation = new Quat().setFromAxisAngle(Vec3.UP, 90);
entity.setRotation(rotation);
Example
// Turn smoothly towards a target orientation each frame
const smoothed = new Quat().slerp(entity.getRotation(), targetRotation, 0.1);
entity.setRotation(smoothed);
new Quat(x?: number, y?: number, z?: number, w?: number)
Creates a new Quat instance.
Parameters
x (number, optional): The x value. Defaults to 0.y (number, optional): The y value. Defaults to 0.z (number, optional): The z value. Defaults to 0.w (number, optional): The w value. Defaults to 1.Example
const q1 = new Quat(); // defaults to 0, 0, 0, 1
const q2 = new Quat(1, 2, 3, 4);
new Quat(arr: number[])
Creates a new Quat instance.
Parameters
arr (number[]): The array to set the quaternion values from.Example
const q = new Quat([1, 2, 3, 4]);
w: number
The w component of the quaternion.
x: number
The x component of the quaternion.
y: number
The y component of the quaternion.
z: number
The z component of the quaternion.
static readonly IDENTITY: Quat
A constant quaternion set to [0, 0, 0, 1] (the identity). Represents no rotation.
static readonly ZERO: Quat
A constant quaternion set to [0, 0, 0, 0].
clone(): Quat
Returns an identical copy of the specified quaternion.
Returns Quat: A new quaternion identical to this one.
Example
const q = new Quat(-0.11, -0.15, -0.46, 0.87);
const qclone = q.clone();
console.log("The result of the cloning is: " + qclone.toString());
copy(rhs: Quat): Quat
Copies the contents of a source quaternion to a destination quaternion.
Parameters
rhs (Quat): The quaternion to be copied.Returns Quat: Self for chaining.
Example
const src = new Quat();
const dst = new Quat();
dst.copy(src);
console.log("The two quaternions are " + (src.equals(dst) ? "equal" : "different"));
dot(other: Quat): number
Calculates the dot product of two quaternions.
Parameters
other (Quat): The quaternion to calculate the dot product with.Returns number: The dot product of the two quaternions.
Example
const a = new Quat(1, 0, 0, 0);
const b = new Quat(0, 1, 0, 0);
console.log("Dot product: " + a.dot(b)); // Outputs 0
equals(rhs: Quat): boolean
Reports whether two quaternions are equal.
Parameters
rhs (Quat): The quaternion to be compared against.Returns boolean: True if the quaternions are equal and false otherwise.
Example
const a = new Quat();
const b = new Quat();
console.log("The two quaternions are " + (a.equals(b) ? "equal" : "different"));
equalsApprox(rhs: Quat, epsilon?: number): boolean
Reports whether two quaternions are equal using an absolute error tolerance.
Parameters
rhs (Quat): The quaternion to be compared against.epsilon (number, optional, default 1e-6): The maximum difference between each component of the two
quaternions. Defaults to 1e-6.Returns boolean: True if the quaternions are equal and false otherwise.
Example
const a = new Quat();
const b = new Quat();
console.log("The two quaternions are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));
fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Quat
Set the values of the quaternion from an array.
Parameters
arr (number[] | ArrayBufferView<ArrayBufferLike>): The array to set the quaternion values from.offset (number, optional, default 0): The zero-based index at which to start copying elements from the
array. Default is 0.Returns Quat: Self for chaining.
Example
const q = new Quat();
q.fromArray([20, 10, 5, 0]);
// q is set to [20, 10, 5, 0]
getAxisAngle(axis: Vec3): number
Gets the rotation axis and angle for a given quaternion. If a quaternion is created with
setFromAxisAngle, this method will return the same values as provided in the original
parameter list OR functionally equivalent values.
Parameters
axis (Vec3): The 3-dimensional vector to receive the axis of rotation.Returns number: Angle, in degrees, of the rotation.
Example
const q = new Quat();
q.setFromAxisAngle(new Vec3(0, 1, 0), 90);
const v = new Vec3();
const angle = q.getAxisAngle(v);
// Outputs 90
console.log(angle);
// Outputs [0, 1, 0]
console.log(v.toString());
getEulerAngles(eulers?: Vec3): Vec3
Converts this quaternion to Euler angles, specified in degrees. The decomposition uses an intrinsic XYZ order, representing the angles required to achieve the quaternion's orientation by rotating sequentially: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis.
Parameters
eulers (Vec3, optional): An optional 3-dimensional vector to receive the calculated
Euler angles (output parameter). If not provided, a new Vec3 object will be allocated
and returned.Returns Vec3: The 3-dimensional vector holding the Euler angles in degrees. This will be
the same object passed in as the eulers parameter (if one was provided).
Example
const q = new Quat();
q.setFromAxisAngle(Vec3.UP, 90);
const e = new Vec3();
q.getEulerAngles(e);
// Outputs [0, 90, 0]
console.log(e.toString());
invert(src?: Quat): Quat
Generates the inverse of the specified quaternion.
Parameters
src (Quat, optional): The quaternion to invert. If not set, the operation is done in place.Returns Quat: Self for chaining.
Example
// Create a quaternion rotated 180 degrees around the y-axis
const rot = new Quat().setFromEulerAngles(0, 180, 0);
// Invert in place
rot.invert();
length(): number
Returns the magnitude of the specified quaternion.
Returns number: The magnitude of the specified quaternion.
Example
const q = new Quat(0, 0, 0, 5);
const len = q.length();
// Outputs 5
console.log("The length of the quaternion is: " + len);
lengthSq(): number
Returns the magnitude squared of the specified quaternion.
Returns number: The magnitude squared of the quaternion.
Example
const q = new Quat(3, 4, 0, 0);
const lenSq = q.lengthSq();
// Outputs 25
console.log("The length squared of the quaternion is: " + lenSq);
lerp(lhs: Quat, rhs: Quat, alpha: number): Quat
Performs a linear interpolation between two quaternions. The result of the interpolation is written to the quaternion calling the function.
Parameters
lhs (Quat): The quaternion to interpolate from.rhs (Quat): The quaternion to interpolate to.alpha (number): The unclamped interpolation factor. Values between 0 and 1 interpolate
between lhs and rhs; values outside this range extrapolate beyond them.Returns Quat: Self for chaining.
Example
const q1 = new Quat(-0.11, -0.15, -0.46, 0.87);
const q2 = new Quat(-0.21, -0.21, -0.67, 0.68);
const result = new Quat();
result.lerp(q1, q2, 0); // Return q1
result.lerp(q1, q2, 0.5); // Return the midpoint interpolant
result.lerp(q1, q2, 1); // Return q2
mul(rhs: Quat): Quat
Returns the result of multiplying the specified quaternions together.
Parameters
rhs (Quat): The quaternion used as the second multiplicand of the operation.Returns Quat: Self for chaining.
Example
const a = new Quat().setFromEulerAngles(0, 30, 0);
const b = new Quat().setFromEulerAngles(0, 60, 0);
// a becomes a 90 degree rotation around the Y axis
// In other words, a = a * b
a.mul(b);
console.log("The result of the multiplication is: " + a.toString());
mul2(lhs: Quat, rhs: Quat): Quat
Returns the result of multiplying the specified quaternions together.
Parameters
lhs (Quat): The quaternion used as the first multiplicand of the operation.rhs (Quat): The quaternion used as the second multiplicand of the operation.Returns Quat: Self for chaining.
Example
const a = new Quat().setFromEulerAngles(0, 30, 0);
const b = new Quat().setFromEulerAngles(0, 60, 0);
const r = new Quat();
// r is set to a 90 degree rotation around the Y axis
// In other words, r = a * b
r.mul2(a, b);
mulScalar(scalar: number, src?: Quat): Quat
Multiplies each element of a quaternion by a number.
Parameters
scalar (number): The number to multiply by.src (Quat, optional): The quaternion to scale. If not set, the operation is done in place.Returns Quat: Self for chaining.
Example
const q = new Quat(1, 2, 3, 4);
q.mulScalar(2);
// q is now [2, 4, 6, 8]
normalize(src?: Quat): Quat
Normalizes the specified quaternion.
Parameters
src (Quat, optional): The quaternion to normalize. If not set, the operation is done in place.Returns Quat: Self for chaining.
Example
const v = new Quat(0, 0, 0, 5);
v.normalize();
// Outputs [0, 0, 0, 1]
console.log(v.toString());
set(x: number, y: number, z: number, w: number): Quat
Sets the specified quaternion to the supplied numerical values.
Parameters
x (number): The x component of the quaternion.y (number): The y component of the quaternion.z (number): The z component of the quaternion.w (number): The w component of the quaternion.Returns Quat: Self for chaining.
Example
const q = new Quat();
q.set(1, 0, 0, 0);
// Outputs 1, 0, 0, 0
console.log("The result of the quaternion set is: " + q.toString());
setFromAxisAngle(axis: Vec3, angle: number): Quat
Sets a quaternion from an angular rotation around an axis.
Parameters
axis (Vec3): World space axis around which to rotate. Should be normalized.angle (number): Angle to rotate around the given axis in degrees.Returns Quat: Self for chaining.
Example
const q = new Quat();
q.setFromAxisAngle(Vec3.UP, 90);
setFromDirections(from: Vec3, to: Vec3): Quat
Set the quaternion that represents the shortest rotation from one direction to another.
Parameters
from (Vec3): The direction to rotate from. It should be normalized.to (Vec3): The direction to rotate to. It should be normalized.Returns Quat: Self for chaining.
Example
const q = new Quat();
const from = new Vec3(0, 0, 1);
const to = new Vec3(0, 1, 0);
q.setFromDirections(from, to);
setFromEulerAngles(ex: number | Vec3, ey?: number, ez?: number): Quat
Sets this quaternion to represent a rotation specified by Euler angles in degrees. The rotation is applied using an intrinsic XYZ order: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis.
Parameters
ex (number | Vec3): The angle to rotate around the X-axis in degrees, or a Vec3
object containing the X, Y, and Z angles in degrees in its respective components (ex.x,
ex.y, ex.z).ey (number, optional): The angle to rotate around the Y-axis in degrees. This parameter is
only used if ex is provided as a number.ez (number, optional): The angle to rotate around the Z-axis in degrees. This parameter is
only used if ex is provided as a number.Returns Quat: The quaternion itself (this), now representing the orientation from the
specified XYZ Euler angles. Allows for method chaining.
Example
// Create a quaternion from 3 individual Euler angles (interpreted as X, Y, Z order)
const q1 = new Quat();
q1.setFromEulerAngles(45, 90, 180); // 45 deg around X, then 90 deg around Y', then 180 deg around Z''
console.log("From numbers:", q1.toString());
Example
// Create the same quaternion from a Vec3 containing the angles (X, Y, Z)
const anglesVec = new Vec3(45, 90, 180);
const q2 = new Quat();
q2.setFromEulerAngles(anglesVec);
console.log("From Vec3:", q2.toString()); // Should match q1
setFromMat4(m: Mat4): Quat
Converts the specified 4x4 matrix to a quaternion. Note that since a quaternion is purely a representation for orientation, only the rotational part of the matrix is used.
Parameters
m (Mat4): The 4x4 matrix to convert.Returns Quat: Self for chaining.
Example
// Create a 4x4 rotation matrix of 180 degrees around the y-axis
const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180);
// Convert to a quaternion
const q = new Quat().setFromMat4(rot);
slerp(lhs: Quat, rhs: Quat, alpha: number): Quat
Performs a spherical interpolation between two quaternions. The result of the interpolation is written to the quaternion calling the function.
Parameters
lhs (Quat): The quaternion to interpolate from.rhs (Quat): The quaternion to interpolate to.alpha (number): The unclamped interpolation factor. Values between 0 and 1 interpolate
between lhs and rhs; values outside this range extrapolate beyond them.Returns Quat: Self for chaining.
Example
const q1 = new Quat(-0.11, -0.15, -0.46, 0.87);
const q2 = new Quat(-0.21, -0.21, -0.67, 0.68);
const result = new Quat();
result.slerp(q1, q2, 0); // Return q1
result.slerp(q1, q2, 0.5); // Return the midpoint interpolant
result.slerp(q1, q2, 1); // Return q2
toArray(arr?: number[], offset?: number): number[]
Parameters
arr (number[], optional): The array to populate with the quaternion's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns number[]: The quaternion as an array.
toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView
Parameters
arr (ArrayBufferView): The array to populate with the quaternion's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns ArrayBufferView: The quaternion as an array.
toString(): string
Converts the quaternion to string form.
Returns string: The quaternion in string form.
Example
const q = new Quat(0, 0, 0, 1);
// Outputs [0, 0, 0, 1]
console.log(q.toString());
transformVector(vec: Vec3, res?: Vec3): Vec3
Transforms a 3-dimensional vector by the specified quaternion.
Parameters
vec (Vec3): The 3-dimensional vector to be transformed.res (Vec3, optional): An optional 3-dimensional vector to receive the result of the transformation.Returns Vec3: The transformed vector (res if specified, otherwise a new Vec3).
Example
// Create a 3-dimensional vector
const v = new Vec3(1, 2, 3);
// Create a quaternion rotation
const q = new Quat().setFromEulerAngles(10, 20, 30);
const tv = q.transformVector(v);
Class · category: Math
An infinite ray. Rays are commonly used for picking, raycasting and intersection tests.
A ray is an origin and a direction. It performs no intersection itself: pass it
to the intersectsRay method of a BoundingBox, BoundingSphere,
OrientedBox, Plane or Tri. Keep the direction normalized, as those tests
require it. The constructor copies the vectors it is given, and set updates both in
place.
Example
// A ray from the camera through a screen position
const ray = new Ray();
entity.camera.screenToWorld(x, y, entity.camera.nearClip, ray.origin);
entity.camera.screenToWorld(x, y, entity.camera.farClip, ray.direction);
ray.direction.sub(ray.origin).normalize();
new Ray(origin?: Vec3, direction?: Vec3)
Creates a new Ray instance. The ray is infinite, starting at a given origin and pointing in a given direction.
Parameters
origin (Vec3, optional): The starting point of the ray. The constructor copies
this parameter. Defaults to the origin (0, 0, 0).direction (Vec3, optional): The direction of the ray. The constructor copies
this parameter. Defaults to a direction down the world negative Z axis (0, 0, -1).Example
// Create a new ray starting at the position of this entity and pointing down
// the entity's negative Z axis
const ray = new Ray(this.entity.getPosition(), this.entity.forward);
readonly direction: Vec3
The direction of the ray.
readonly origin: Vec3
The starting point of the ray.
clone(): Ray
Returns a clone of the Ray.
Returns Ray: A duplicate Ray.
copy(src: Ray): Ray
Copies the contents of a source Ray.
Parameters
src (Ray): The Ray to copy from.Returns Ray: Self for chaining.
set(origin: Vec3, direction: Vec3): Ray
Sets origin and direction to the supplied vector values.
Parameters
Returns Ray: Self for chaining.
Class · category: Math
A triangle defined by three Vec3 vectors.
The vertices are v0, v1 and v2; the constructor and set copy the vectors they are given. intersectsRay tests a Ray whose direction is normalized against either face of the triangle and writes the hit point into an optional vector. It is the building block for precise picking against mesh geometry.
Example
const tri = new Tri(new Vec3(0, 0, 0), new Vec3(1, 0, 0), new Vec3(0, 1, 0));
const hit = new Vec3();
if (tri.intersectsRay(ray, hit)) {
console.log(`Hit the triangle at ${hit}`);
}
new Tri(v0?: Vec3, v1?: Vec3, v2?: Vec3)
Creates a new Tri object.
Parameters
v0 (Vec3, optional, default Vec3.ZERO): The first 3-dimensional vector.v1 (Vec3, optional, default Vec3.ZERO): The second 3-dimensional vector.v2 (Vec3, optional, default Vec3.ZERO): The third 3-dimensional vector.Example
const v0 = new Vec3(1, 0, 0);
const v1 = new Vec3(0, 1, 0);
const v2 = new Vec3(2, 2, 1);
const t = new Tri(v0, v1, v2);
readonly v0: Vec3
The first 3-dimensional vector of the triangle.
readonly v1: Vec3
The second 3-dimensional vector of the triangle.
readonly v2: Vec3
The third 3-dimensional vector of the triangle.
intersectsRay(ray: Ray, point?: Vec3): boolean
Test if a ray intersects with the triangle.
Parameters
ray (Ray): Ray to test against (direction must be normalized).point (Vec3, optional): If there is an intersection, the intersection point will be copied
into here.Returns boolean: True if there is an intersection.
set(v0: Vec3, v1: Vec3, v2: Vec3): Tri
Sets the specified triangle to the supplied 3-dimensional vectors.
Parameters
v0 (Vec3): The value set on the first 3-dimensional vector of the triangle.v1 (Vec3): The value set on the second 3-dimensional vector of the triangle.v2 (Vec3): The value set on the third 3-dimensional vector of the triangle.Returns Tri: Self for chaining.
Example
const t = new Tri(Vec3.UP, Vec3.RIGHT, Vec3.BACK);
const v0 = new Vec3(1, 0, 0);
const v1 = new Vec3(0, 1, 0);
const v2 = new Vec3(2, 2, 1);
t.set(v0, v1, v2);
// Outputs [[1, 0, 0], [0, 1, 0], [2, 2, 1]]
console.log("The result of the triangle set is: " + t.toString());
toString(): string
Converts the specified triangle to string form.
Returns string: The triangle in string form.
Example
const t = new Tri(Vec3.UP, Vec3.RIGHT, Vec3.BACK);
// Outputs [[0, 1, 0], [1, 0, 0], [0, 0, 1]]
console.log(t.toString());
Class · category: Math
A 2-dimensional vector. Vec2 is commonly used to represent 2D positions, directions, texture coordinates (UVs) or any pair of related numeric values.
Operations follow one convention throughout the math classes: a method that modifies the vector
it is called on returns it, so calls can be chained and nothing is allocated, while queries such
as distance and dot return a number. Two-operand forms such as add2 and
sub2 write the result of lhs op rhs into this, and it is safe for this to also be
one of the operands. Use clone for an independent copy and copy to overwrite one
vector with another.
The static constants such as ZERO and UP are frozen shared instances: read them freely, but writing to one throws. Copy a constant before modifying it.
Example
// Scroll a texture offset each frame without allocating
const offset = new Vec2(0, 0);
const speed = new Vec2(0.1, 0);
offset.addScaled(speed, dt);
Example
// Chain mutating operations; each returns the vector it was called on
const toTarget = new Vec2().sub2(target, position).normalize();
const distance = target.distance(position);
new Vec2(x?: number, y?: number)
Creates a new Vec2 instance.
Parameters
x (number, optional): The x value. Defaults to 0.y (number, optional): The y value. Defaults to 0.Example
const v1 = new Vec2(); // defaults to 0, 0
const v2 = new Vec2(1, 2);
new Vec2(arr: number[])
Creates a new Vec2 instance.
Parameters
arr (number[]): The array to set the vector values from.Example
const v = new Vec2([1, 2]);
x: number
The first component of the vector.
y: number
The second component of the vector.
static readonly DOWN: Vec2
A constant vector set to [0, -1].
static readonly HALF: Vec2
A constant vector set to [0.5, 0.5].
static readonly LEFT: Vec2
A constant vector set to [-1, 0].
static readonly ONE: Vec2
A constant vector set to [1, 1].
static readonly RIGHT: Vec2
A constant vector set to [1, 0].
static readonly UP: Vec2
A constant vector set to [0, 1].
static readonly ZERO: Vec2
A constant vector set to [0, 0].
add(rhs: Vec2): Vec2
Adds a 2-dimensional vector to another in place.
Parameters
rhs (Vec2): The vector to add to the specified vector.Returns Vec2: Self for chaining.
Example
const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
a.add(b);
// Outputs [30, 30]
console.log("The result of the addition is: " + a.toString());
add2(lhs: Vec2, rhs: Vec2): Vec2
Adds two 2-dimensional vectors together and returns the result.
Parameters
lhs (Vec2): The first vector operand for the addition.rhs (Vec2): The second vector operand for the addition.Returns Vec2: Self for chaining.
Example
const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
const r = new Vec2();
r.add2(a, b);
// Outputs [30, 30]
console.log("The result of the addition is: " + r.toString());
addScalar(scalar: number): Vec2
Adds a number to each element of a vector.
Parameters
scalar (number): The number to add.Returns Vec2: Self for chaining.
Example
const vec = new Vec2(3, 4);
vec.addScalar(2);
// Outputs [5, 6]
console.log("The result of the addition is: " + vec.toString());
addScaled(rhs: Vec2, scalar: number): Vec2
Adds a 2-dimensional vector scaled by scalar value. Does not modify the vector being added.
Parameters
rhs (Vec2): The vector to add to the specified vector.scalar (number): The number to multiply the added vector with.Returns Vec2: Self for chaining.
Example
const vec = new Vec2(1, 2);
vec.addScaled(Vec2.UP, 2);
// Outputs [1, 4]
console.log("The result of the addition is: " + vec.toString());
angle(): number
Returns the angle in degrees of the specified 2-dimensional vector.
Returns number: The angle in degrees of the specified 2-dimensional vector.
Example
const v = new Vec2(6, 0);
const angle = v.angle();
// Outputs 90..
console.log("The angle of the vector is: " + angle);
angleTo(rhs: Vec2): number
Returns the shortest Euler angle between two 2-dimensional vectors.
Parameters
rhs (Vec2): The 2-dimensional vector to calculate angle to.Returns number: The shortest angle in degrees between two 2-dimensional vectors.
Example
const a = new Vec2(0, 10); // up
const b = new Vec2(1, -1); // down-right
const angle = a.angleTo(b);
// Outputs 135..
console.log("The angle between vectors a and b: " + angle);
ceil(src?: Vec2): Vec2
Each element is rounded up to the next largest integer.
Parameters
src (Vec2, optional): The vector to ceil. If not set, the operation is done in place.Returns Vec2: Self for chaining.
Example
const v = new Vec2(1.2, 3.1);
v.ceil();
// v is now [2, 4]
clone(): Vec2
Returns an identical copy of the specified 2-dimensional vector.
Returns Vec2: A 2-dimensional vector containing the result of the cloning.
Example
const v = new Vec2(10, 20);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());
copy(rhs: Vec2): Vec2
Copies the contents of a source 2-dimensional vector to a destination 2-dimensional vector.
Parameters
rhs (Vec2): A vector to copy to the specified vector.Returns Vec2: Self for chaining.
Example
const src = new Vec2(10, 20);
const dst = new Vec2();
dst.copy(src);
console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));
cross(rhs: Vec2): number
Returns the result of a cross product operation performed on the two specified 2-dimensional vectors.
Parameters
rhs (Vec2): The second 2-dimensional vector operand of the cross product.Returns number: The cross product of the two vectors.
Example
const right = new Vec2(1, 0);
const up = new Vec2(0, 1);
const crossProduct = right.cross(up);
// Prints 1
console.log("The result of the cross product is: " + crossProduct);
distance(rhs: Vec2): number
Returns the distance between the two specified 2-dimensional vectors.
Parameters
rhs (Vec2): The second 2-dimensional vector to test.Returns number: The distance between the two vectors.
Example
const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const d = v1.distance(v2);
console.log("The distance between v1 and v2 is: " + d);
distanceSq(rhs: Vec2): number
Returns the squared distance between the two specified 2-dimensional vectors.
Parameters
rhs (Vec2): The second 2-dimensional vector to test.Returns number: The squared distance between the two vectors.
Example
const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const d = v1.distanceSq(v2);
console.log("The squared distance between v1 and v2 is: " + d);
div(rhs: Vec2): Vec2
Divides a 2-dimensional vector by another in place.
Parameters
rhs (Vec2): The vector to divide the specified vector by.Returns Vec2: Self for chaining.
Example
const a = new Vec2(4, 9);
const b = new Vec2(2, 3);
a.div(b);
// Outputs [2, 3]
console.log("The result of the division is: " + a.toString());
div2(lhs: Vec2, rhs: Vec2): Vec2
Divides one 2-dimensional vector by another and writes the result to the specified vector.
Parameters
lhs (Vec2): The dividend vector (the vector being divided).rhs (Vec2): The divisor vector (the vector dividing the dividend).Returns Vec2: Self for chaining.
Example
const a = new Vec2(4, 9);
const b = new Vec2(2, 3);
const r = new Vec2();
r.div2(a, b);
// Outputs [2, 3]
console.log("The result of the division is: " + r.toString());
divScalar(scalar: number): Vec2
Divides each element of a vector by a number.
Parameters
scalar (number): The number to divide by.Returns Vec2: Self for chaining.
Example
const vec = new Vec2(3, 6);
vec.divScalar(3);
// Outputs [1, 2]
console.log("The result of the division is: " + vec.toString());
dot(rhs: Vec2): number
Returns the result of a dot product operation performed on the two specified 2-dimensional vectors.
Parameters
rhs (Vec2): The second 2-dimensional vector operand of the dot product.Returns number: The result of the dot product operation.
Example
const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);
equals(rhs: Vec2): boolean
Reports whether two vectors are equal.
Parameters
rhs (Vec2): The vector to compare to the specified vector.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec2(1, 2);
const b = new Vec2(4, 5);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));
equalsApprox(rhs: Vec2, epsilon?: number): boolean
Reports whether two vectors are equal using an absolute error tolerance.
Parameters
rhs (Vec2): The vector to be compared against.epsilon (number, optional, default 1e-6): The maximum difference between each component of the two
vectors. Defaults to 1e-6.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec2();
const b = new Vec2();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));
floor(src?: Vec2): Vec2
Each element is set to the largest integer less than or equal to its value.
Parameters
src (Vec2, optional): The vector to floor. If not set, the operation is done in place.Returns Vec2: Self for chaining.
Example
const v = new Vec2(1.2, 3.9);
v.floor();
// v is now [1, 3]
fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec2
Set the values of the vector from an array.
Parameters
arr (number[] | ArrayBufferView<ArrayBufferLike>): The array to set the vector values from.offset (number, optional, default 0): The zero-based index at which to start copying elements from the
array. Default is 0.Returns Vec2: Self for chaining.
Example
const v = new Vec2();
v.fromArray([20, 10]);
// v is set to [20, 10]
length(): number
Returns the magnitude of the specified 2-dimensional vector.
Returns number: The magnitude of the specified 2-dimensional vector.
Example
const vec = new Vec2(3, 4);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);
lengthSq(): number
Returns the magnitude squared of the specified 2-dimensional vector.
Returns number: The magnitude squared of the specified 2-dimensional vector.
Example
const vec = new Vec2(3, 4);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);
lerp(lhs: Vec2, rhs: Vec2, alpha: number): Vec2
Returns the result of a linear interpolation between two specified 2-dimensional vectors.
Parameters
lhs (Vec2): The 2-dimensional vector to interpolate from.rhs (Vec2): The 2-dimensional vector to interpolate to.alpha (number): The value controlling the point of interpolation. Between 0 and 1,
the linear interpolant will occur on a straight line between lhs and rhs. Outside of this
range, the linear interpolant will occur on a ray extrapolated from this line.Returns Vec2: Self for chaining.
Example
const a = new Vec2(0, 0);
const b = new Vec2(10, 10);
const r = new Vec2();
r.lerp(a, b, 0); // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5
r.lerp(a, b, 1); // r is equal to b
max(rhs: Vec2): Vec2
Each element is assigned a value from rhs parameter if it is larger.
Parameters
rhs (Vec2): The 2-dimensional vector used as the source of elements to compare to.Returns Vec2: Self for chaining.
Example
const a = new Vec2(5, 1);
const b = new Vec2(2, 8);
a.max(b);
// a is now [5, 8]
min(rhs: Vec2): Vec2
Each element is assigned a value from rhs parameter if it is smaller.
Parameters
rhs (Vec2): The 2-dimensional vector used as the source of elements to compare to.Returns Vec2: Self for chaining.
Example
const a = new Vec2(5, 1);
const b = new Vec2(2, 8);
a.min(b);
// a is now [2, 1]
mul(rhs: Vec2): Vec2
Multiplies a 2-dimensional vector to another in place.
Parameters
rhs (Vec2): The 2-dimensional vector used as the second multiplicand of the operation.Returns Vec2: Self for chaining.
Example
const a = new Vec2(2, 3);
const b = new Vec2(4, 5);
a.mul(b);
// Outputs 8, 15
console.log("The result of the multiplication is: " + a.toString());
mul2(lhs: Vec2, rhs: Vec2): Vec2
Returns the result of multiplying the specified 2-dimensional vectors together.
Parameters
lhs (Vec2): The 2-dimensional vector used as the first multiplicand of the operation.rhs (Vec2): The 2-dimensional vector used as the second multiplicand of the operation.Returns Vec2: Self for chaining.
Example
const a = new Vec2(2, 3);
const b = new Vec2(4, 5);
const r = new Vec2();
r.mul2(a, b);
// Outputs 8, 15
console.log("The result of the multiplication is: " + r.toString());
mulScalar(scalar: number): Vec2
Multiplies each element of a vector by a number.
Parameters
scalar (number): The number to multiply by.Returns Vec2: Self for chaining.
Example
const vec = new Vec2(3, 6);
vec.mulScalar(3);
// Outputs [9, 18]
console.log("The result of the multiplication is: " + vec.toString());
normalize(src?: Vec2): Vec2
Returns this 2-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.
Parameters
src (Vec2, optional): The vector to normalize. If not set, the operation is done in place.Returns Vec2: Self for chaining.
Example
const v = new Vec2(25, 0);
v.normalize();
// Outputs 1, 0
console.log("The result of the vector normalization is: " + v.toString());
rotate(degrees: number): Vec2
Rotate a vector by an angle in degrees.
Parameters
degrees (number): The number to degrees to rotate the vector by.Returns Vec2: Self for chaining.
Example
const v = new Vec2(0, 10);
v.rotate(45); // rotates by 45 degrees
// Outputs [7.071068.., 7.071068..]
console.log("Vector after rotation is: " + v.toString());
round(src?: Vec2): Vec2
Each element is rounded up or down to the nearest integer.
Parameters
src (Vec2, optional): The vector to round. If not set, the operation is done in place.Returns Vec2: Self for chaining.
Example
const v = new Vec2(1.4, 3.6);
v.round();
// v is now [1, 4]
set(x: number, y: number): Vec2
Sets the specified 2-dimensional vector to the supplied numerical values.
Parameters
x (number): The value to set on the first component of the vector.y (number): The value to set on the second component of the vector.Returns Vec2: Self for chaining.
Example
const v = new Vec2();
v.set(5, 10);
// Outputs 5, 10
console.log("The result of the vector set is: " + v.toString());
sub(rhs: Vec2): Vec2
Subtracts a 2-dimensional vector from another in place.
Parameters
rhs (Vec2): The vector to subtract from the specified vector.Returns Vec2: Self for chaining.
Example
const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
a.sub(b);
// Outputs [-10, -10]
console.log("The result of the subtraction is: " + a.toString());
sub2(lhs: Vec2, rhs: Vec2): Vec2
Subtracts two 2-dimensional vectors from one another and returns the result.
Parameters
lhs (Vec2): The first vector operand for the subtraction.rhs (Vec2): The second vector operand for the subtraction.Returns Vec2: Self for chaining.
Example
const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
const r = new Vec2();
r.sub2(a, b);
// Outputs [-10, -10]
console.log("The result of the subtraction is: " + r.toString());
subScalar(scalar: number): Vec2
Subtracts a number from each element of a vector.
Parameters
scalar (number): The number to subtract.Returns Vec2: Self for chaining.
Example
const vec = new Vec2(3, 4);
vec.subScalar(2);
// Outputs [1, 2]
console.log("The result of the subtraction is: " + vec.toString());
toArray(arr?: number[], offset?: number): number[]
Parameters
arr (number[], optional): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns number[]: The vector as an array.
toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView
Parameters
arr (ArrayBufferView): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns ArrayBufferView: The vector as an array.
toString(): string
Converts the vector to string form.
Returns string: The vector in string form.
Example
const v = new Vec2(20, 10);
// Outputs [20, 10]
console.log(v.toString());
Class · category: Math
A 3-dimensional vector. Vec3 is commonly used to represent 3D positions, directions, Euler angles or scales.
Operations follow one convention throughout the math classes: a method that modifies the vector
it is called on returns it, so calls can be chained and nothing is allocated, while queries such
as distance and dot return a number. Two-operand forms such as add2,
sub2 and cross write the result of lhs op rhs into this, and it is safe for
this to also be one of the operands. Use clone for an independent copy and copy
to overwrite one vector with another.
The static constants such as ZERO, UP and FORWARD are frozen shared instances: read them freely, but writing to one throws. Vectors returned by engine getters such as GraphNode#getPosition are internal storage and should be treated as read-only; clone them if you need to keep or modify the value.
Example
// Move a point 5 units along a direction without allocating
const position = new Vec3(1, 2, 3);
const direction = new Vec3(0, 0, -1);
position.addScaled(direction, 5); // position is now [1, 2, -2]
Example
// Chain mutating operations; each returns the vector it was called on
const toTarget = new Vec3().sub2(target, origin).normalize();
const distance = target.distance(origin);
Example
// Keep a copy of an entity's position, then modify it safely
const start = entity.getPosition().clone();
start.y += 1;
new Vec3(x?: number, y?: number, z?: number)
Creates a new Vec3 instance.
Parameters
x (number, optional): The x value. Defaults to 0.y (number, optional): The y value. Defaults to 0.z (number, optional): The z value. Defaults to 0.Example
const v1 = new Vec3(); // defaults to 0, 0, 0
const v2 = new Vec3(1, 2, 3);
new Vec3(arr: number[])
Creates a new Vec3 instance.
Parameters
arr (number[]): The array to set the vector values from.Example
const v = new Vec3([1, 2, 3]);
x: number
The first component of the vector.
y: number
The second component of the vector.
z: number
The third component of the vector.
static readonly BACK: Vec3
A constant vector set to [0, 0, 1].
static readonly DOWN: Vec3
A constant vector set to [0, -1, 0].
static readonly FORWARD: Vec3
A constant vector set to [0, 0, -1].
static readonly HALF: Vec3
A constant vector set to [0.5, 0.5, 0.5].
static readonly LEFT: Vec3
A constant vector set to [-1, 0, 0].
static readonly ONE: Vec3
A constant vector set to [1, 1, 1].
static readonly RIGHT: Vec3
A constant vector set to [1, 0, 0].
static readonly UP: Vec3
A constant vector set to [0, 1, 0].
static readonly ZERO: Vec3
A constant vector set to [0, 0, 0].
add(rhs: Vec3): Vec3
Adds a 3-dimensional vector to another in place.
Parameters
rhs (Vec3): The vector to add to the specified vector.Returns Vec3: Self for chaining.
Example
const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
a.add(b);
// Outputs [30, 30, 30]
console.log("The result of the addition is: " + a.toString());
add2(lhs: Vec3, rhs: Vec3): Vec3
Adds two 3-dimensional vectors together and returns the result.
Parameters
lhs (Vec3): The first vector operand for the addition.rhs (Vec3): The second vector operand for the addition.Returns Vec3: Self for chaining.
Example
const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
const r = new Vec3();
r.add2(a, b);
// Outputs [30, 30, 30]
console.log("The result of the addition is: " + r.toString());
addScalar(scalar: number): Vec3
Adds a number to each element of a vector.
Parameters
scalar (number): The number to add.Returns Vec3: Self for chaining.
Example
const vec = new Vec3(3, 4, 5);
vec.addScalar(2);
// Outputs [5, 6, 7]
console.log("The result of the addition is: " + vec.toString());
addScaled(rhs: Vec3, scalar: number): Vec3
Adds a 3-dimensional vector scaled by scalar value. Does not modify the vector being added.
Parameters
rhs (Vec3): The vector to add to the specified vector.scalar (number): The number to multiply the added vector with.Returns Vec3: Self for chaining.
Example
const vec = new Vec3(1, 2, 3);
vec.addScaled(Vec3.UP, 2);
// Outputs [1, 4, 3]
console.log("The result of the addition is: " + vec.toString());
ceil(src?: Vec3): Vec3
Each element is rounded up to the next largest integer.
Parameters
src (Vec3, optional): The vector to ceil. If not set, the operation is done in place.Returns Vec3: Self for chaining.
Example
const v = new Vec3(1.2, 3.1, 5.9);
v.ceil();
// v is now [2, 4, 6]
clone(): Vec3
Returns an identical copy of the specified 3-dimensional vector.
Returns Vec3: A 3-dimensional vector containing the result of the cloning.
Example
const v = new Vec3(10, 20, 30);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());
copy(rhs: Vec3): Vec3
Copies the contents of a source 3-dimensional vector to a destination 3-dimensional vector.
Parameters
rhs (Vec3): A vector to copy to the specified vector.Returns Vec3: Self for chaining.
Example
const src = new Vec3(10, 20, 30);
const dst = new Vec3();
dst.copy(src);
console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));
cross(lhs: Vec3, rhs: Vec3): Vec3
Returns the result of a cross product operation performed on the two specified 3-dimensional vectors.
Parameters
lhs (Vec3): The first 3-dimensional vector operand of the cross product.rhs (Vec3): The second 3-dimensional vector operand of the cross product.Returns Vec3: Self for chaining.
Example
const back = new Vec3().cross(Vec3.RIGHT, Vec3.UP);
// Prints the Z axis (i.e. [0, 0, 1])
console.log("The result of the cross product is: " + back.toString());
distance(rhs: Vec3): number
Returns the distance between the two specified 3-dimensional vectors.
Parameters
rhs (Vec3): The second 3-dimensional vector to test.Returns number: The distance between the two vectors.
Example
const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const d = v1.distance(v2);
console.log("The distance between v1 and v2 is: " + d);
distanceSq(rhs: Vec3): number
Returns the squared distance between the two specified 3-dimensional vectors.
Parameters
rhs (Vec3): The second 3-dimensional vector to test.Returns number: The squared distance between the two vectors.
Example
const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const d = v1.distanceSq(v2);
console.log("The squared distance between v1 and v2 is: " + d);
div(rhs: Vec3): Vec3
Divides a 3-dimensional vector by another in place.
Parameters
rhs (Vec3): The vector to divide the specified vector by.Returns Vec3: Self for chaining.
Example
const a = new Vec3(4, 9, 16);
const b = new Vec3(2, 3, 4);
a.div(b);
// Outputs [2, 3, 4]
console.log("The result of the division is: " + a.toString());
div2(lhs: Vec3, rhs: Vec3): Vec3
Divides one 3-dimensional vector by another and writes the result to the specified vector.
Parameters
lhs (Vec3): The dividend vector (the vector being divided).rhs (Vec3): The divisor vector (the vector dividing the dividend).Returns Vec3: Self for chaining.
Example
const a = new Vec3(4, 9, 16);
const b = new Vec3(2, 3, 4);
const r = new Vec3();
r.div2(a, b);
// Outputs [2, 3, 4]
console.log("The result of the division is: " + r.toString());
divScalar(scalar: number): Vec3
Divides each element of a vector by a number.
Parameters
scalar (number): The number to divide by.Returns Vec3: Self for chaining.
Example
const vec = new Vec3(3, 6, 9);
vec.divScalar(3);
// Outputs [1, 2, 3]
console.log("The result of the division is: " + vec.toString());
dot(rhs: Vec3): number
Returns the result of a dot product operation performed on the two specified 3-dimensional vectors.
Parameters
rhs (Vec3): The second 3-dimensional vector operand of the dot product.Returns number: The result of the dot product operation.
Example
const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);
equals(rhs: Vec3): boolean
Reports whether two vectors are equal.
Parameters
rhs (Vec3): The vector to compare to the specified vector.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec3(1, 2, 3);
const b = new Vec3(4, 5, 6);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));
equalsApprox(rhs: Vec3, epsilon?: number): boolean
Reports whether two vectors are equal using an absolute error tolerance.
Parameters
rhs (Vec3): The vector to be compared against.epsilon (number, optional, default 1e-6): The maximum difference between each component of the two
vectors. Defaults to 1e-6.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec3();
const b = new Vec3();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));
floor(src?: Vec3): Vec3
Each element is set to the largest integer less than or equal to its value.
Parameters
src (Vec3, optional): The vector to floor. If not set, the operation is done in place.Returns Vec3: Self for chaining.
Example
const v = new Vec3(1.2, 3.9, 5.5);
v.floor();
// v is now [1, 3, 5]
fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec3
Set the values of the vector from an array.
Parameters
arr (number[] | ArrayBufferView<ArrayBufferLike>): The array to set the vector values from.offset (number, optional, default 0): The zero-based index at which to start copying elements from the
array. Default is 0.Returns Vec3: Self for chaining.
Example
const v = new Vec3();
v.fromArray([20, 10, 5]);
// v is set to [20, 10, 5]
length(): number
Returns the magnitude of the specified 3-dimensional vector.
Returns number: The magnitude of the specified 3-dimensional vector.
Example
const vec = new Vec3(3, 4, 0);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);
lengthSq(): number
Returns the magnitude squared of the specified 3-dimensional vector.
Returns number: The magnitude squared of the specified 3-dimensional vector.
Example
const vec = new Vec3(3, 4, 0);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);
lerp(lhs: Vec3, rhs: Vec3, alpha: number): Vec3
Returns the result of a linear interpolation between two specified 3-dimensional vectors.
Parameters
lhs (Vec3): The 3-dimensional vector to interpolate from.rhs (Vec3): The 3-dimensional vector to interpolate to.alpha (number): The value controlling the point of interpolation. Between 0 and 1,
the linear interpolant will occur on a straight line between lhs and rhs. Outside of this
range, the linear interpolant will occur on a ray extrapolated from this line.Returns Vec3: Self for chaining.
Example
const a = new Vec3(0, 0, 0);
const b = new Vec3(10, 10, 10);
const r = new Vec3();
r.lerp(a, b, 0); // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5, 5
r.lerp(a, b, 1); // r is equal to b
max(rhs: Vec3): Vec3
Each element is assigned a value from rhs parameter if it is larger.
Parameters
rhs (Vec3): The 3-dimensional vector used as the source of elements to compare to.Returns Vec3: Self for chaining.
Example
const a = new Vec3(5, 1, 7);
const b = new Vec3(2, 8, 3);
a.max(b);
// a is now [5, 8, 7]
min(rhs: Vec3): Vec3
Each element is assigned a value from rhs parameter if it is smaller.
Parameters
rhs (Vec3): The 3-dimensional vector used as the source of elements to compare to.Returns Vec3: Self for chaining.
Example
const a = new Vec3(5, 1, 7);
const b = new Vec3(2, 8, 3);
a.min(b);
// a is now [2, 1, 3]
mul(rhs: Vec3): Vec3
Multiplies a 3-dimensional vector to another in place.
Parameters
rhs (Vec3): The 3-dimensional vector used as the second multiplicand of the operation.Returns Vec3: Self for chaining.
Example
const a = new Vec3(2, 3, 4);
const b = new Vec3(4, 5, 6);
a.mul(b);
// Outputs [8, 15, 24]
console.log("The result of the multiplication is: " + a.toString());
mul2(lhs: Vec3, rhs: Vec3): Vec3
Returns the result of multiplying the specified 3-dimensional vectors together.
Parameters
lhs (Vec3): The 3-dimensional vector used as the first multiplicand of the operation.rhs (Vec3): The 3-dimensional vector used as the second multiplicand of the operation.Returns Vec3: Self for chaining.
Example
const a = new Vec3(2, 3, 4);
const b = new Vec3(4, 5, 6);
const r = new Vec3();
r.mul2(a, b);
// Outputs [8, 15, 24]
console.log("The result of the multiplication is: " + r.toString());
mulScalar(scalar: number): Vec3
Multiplies each element of a vector by a number.
Parameters
scalar (number): The number to multiply by.Returns Vec3: Self for chaining.
Example
const vec = new Vec3(3, 6, 9);
vec.mulScalar(3);
// Outputs [9, 18, 27]
console.log("The result of the multiplication is: " + vec.toString());
normalize(src?: Vec3): Vec3
Returns this 3-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.
Parameters
src (Vec3, optional): The vector to normalize. If not set, the operation is done in place.Returns Vec3: Self for chaining.
Example
const v = new Vec3(25, 0, 0);
v.normalize();
// Outputs [1, 0, 0]
console.log("The result of the vector normalization is: " + v.toString());
project(rhs: Vec3): Vec3
Projects this 3-dimensional vector onto the specified vector.
Parameters
rhs (Vec3): The vector onto which the original vector will be projected on.Returns Vec3: Self for chaining.
Example
const v = new Vec3(5, 5, 5);
const normal = new Vec3(1, 0, 0);
v.project(normal);
// Outputs [5, 0, 0]
console.log("The result of the vector projection is: " + v.toString());
round(src?: Vec3): Vec3
Each element is rounded up or down to the nearest integer.
Parameters
src (Vec3, optional): The vector to round. If not set, the operation is done in place.Returns Vec3: Self for chaining.
Example
const v = new Vec3(1.4, 3.6, 5.5);
v.round();
// v is now [1, 4, 6]
set(x: number, y: number, z: number): Vec3
Sets the specified 3-dimensional vector to the supplied numerical values.
Parameters
x (number): The value to set on the first component of the vector.y (number): The value to set on the second component of the vector.z (number): The value to set on the third component of the vector.Returns Vec3: Self for chaining.
Example
const v = new Vec3();
v.set(5, 10, 20);
// Outputs [5, 10, 20]
console.log("The result of the vector set is: " + v.toString());
sub(rhs: Vec3): Vec3
Subtracts a 3-dimensional vector from another in place.
Parameters
rhs (Vec3): The vector to subtract from the specified vector.Returns Vec3: Self for chaining.
Example
const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
a.sub(b);
// Outputs [-10, -10, -10]
console.log("The result of the subtraction is: " + a.toString());
sub2(lhs: Vec3, rhs: Vec3): Vec3
Subtracts two 3-dimensional vectors from one another and returns the result.
Parameters
lhs (Vec3): The first vector operand for the subtraction.rhs (Vec3): The second vector operand for the subtraction.Returns Vec3: Self for chaining.
Example
const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
const r = new Vec3();
r.sub2(a, b);
// Outputs [-10, -10, -10]
console.log("The result of the subtraction is: " + r.toString());
subScalar(scalar: number): Vec3
Subtracts a number from each element of a vector.
Parameters
scalar (number): The number to subtract.Returns Vec3: Self for chaining.
Example
const vec = new Vec3(3, 4, 5);
vec.subScalar(2);
// Outputs [1, 2, 3]
console.log("The result of the subtraction is: " + vec.toString());
toArray(arr?: number[], offset?: number): number[]
Parameters
arr (number[], optional): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns number[]: The vector as an array.
toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView
Parameters
arr (ArrayBufferView): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns ArrayBufferView: The vector as an array.
toString(): string
Converts the vector to string form.
Returns string: The vector in string form.
Example
const v = new Vec3(20, 10, 5);
// Outputs [20, 10, 5]
console.log(v.toString());
Class · category: Math
A 4-dimensional vector. Vec4 is commonly used to represent homogeneous coordinates or shader uniforms requiring four components.
Operations follow one convention throughout the math classes: a method that modifies the vector
it is called on returns it, so calls can be chained and nothing is allocated, while queries such
as length and dot return a number. Two-operand forms such as add2 and
mul2 write the result of lhs op rhs into this, and it is safe for this to also be
one of the operands. Use clone for an independent copy and copy to overwrite one
vector with another.
The static constants ZERO, HALF and ONE are frozen shared instances: read them freely, but writing to one throws.
Example
// Interpolate between two 4-component values into a third, without allocating
const from = new Vec4(0, 0, 0, 0);
const to = new Vec4(1, 1, 1, 1);
const result = new Vec4();
result.lerp(from, to, 0.25); // result is now [0.25, 0.25, 0.25, 0.25]
new Vec4(x?: number, y?: number, z?: number, w?: number)
Creates a new Vec4 instance.
Parameters
x (number, optional): The x value. Defaults to 0.y (number, optional): The y value. Defaults to 0.z (number, optional): The z value. Defaults to 0.w (number, optional): The w value. Defaults to 0.Example
const v1 = new Vec4(); // defaults to 0, 0, 0, 0
const v2 = new Vec4(1, 2, 3, 4);
new Vec4(arr: number[])
Creates a new Vec4 instance.
Parameters
arr (number[]): The array to set the vector values from.Example
const v = new Vec4([1, 2, 3, 4]);
w: number
The fourth component of the vector.
x: number
The first component of the vector.
y: number
The second component of the vector.
z: number
The third component of the vector.
static readonly HALF: Vec4
A constant vector set to [0.5, 0.5, 0.5, 0.5].
static readonly ONE: Vec4
A constant vector set to [1, 1, 1, 1].
static readonly ZERO: Vec4
A constant vector set to [0, 0, 0, 0].
add(rhs: Vec4): Vec4
Adds a 4-dimensional vector to another in place.
Parameters
rhs (Vec4): The vector to add to the specified vector.Returns Vec4: Self for chaining.
Example
const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
a.add(b);
// Outputs [30, 30, 30, 30]
console.log("The result of the addition is: " + a.toString());
add2(lhs: Vec4, rhs: Vec4): Vec4
Adds two 4-dimensional vectors together and returns the result.
Parameters
lhs (Vec4): The first vector operand for the addition.rhs (Vec4): The second vector operand for the addition.Returns Vec4: Self for chaining.
Example
const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
const r = new Vec4();
r.add2(a, b);
// Outputs [30, 30, 30, 30]
console.log("The result of the addition is: " + r.toString());
addScalar(scalar: number): Vec4
Adds a number to each element of a vector.
Parameters
scalar (number): The number to add.Returns Vec4: Self for chaining.
Example
const vec = new Vec4(3, 4, 5, 6);
vec.addScalar(2);
// Outputs [5, 6, 7, 8]
console.log("The result of the addition is: " + vec.toString());
addScaled(rhs: Vec4, scalar: number): Vec4
Adds a 4-dimensional vector scaled by scalar value. Does not modify the vector being added.
Parameters
rhs (Vec4): The vector to add to the specified vector.scalar (number): The number to multiply the added vector with.Returns Vec4: Self for chaining.
Example
const vec = new Vec4(1, 2, 3, 4);
vec.addScaled(Vec4.ONE, 2);
// Outputs [3, 4, 5, 6]
console.log("The result of the addition is: " + vec.toString());
ceil(src?: Vec4): Vec4
Each element is rounded up to the next largest integer.
Parameters
src (Vec4, optional): The vector to ceil. If not set, the operation is done in place.Returns Vec4: Self for chaining.
Example
const v = new Vec4(1.2, 3.1, 5.9, 7.4);
v.ceil();
// v is now [2, 4, 6, 8]
clone(): Vec4
Returns an identical copy of the specified 4-dimensional vector.
Returns Vec4: A 4-dimensional vector containing the result of the cloning.
Example
const v = new Vec4(10, 20, 30, 40);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());
copy(rhs: Vec4): Vec4
Copies the contents of a source 4-dimensional vector to a destination 4-dimensional vector.
Parameters
rhs (Vec4): A vector to copy to the specified vector.Returns Vec4: Self for chaining.
Example
const src = new Vec4(10, 20, 30, 40);
const dst = new Vec4();
dst.copy(src);
console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));
div(rhs: Vec4): Vec4
Divides a 4-dimensional vector by another in place.
Parameters
rhs (Vec4): The vector to divide the specified vector by.Returns Vec4: Self for chaining.
Example
const a = new Vec4(4, 9, 16, 25);
const b = new Vec4(2, 3, 4, 5);
a.div(b);
// Outputs [2, 3, 4, 5]
console.log("The result of the division is: " + a.toString());
div2(lhs: Vec4, rhs: Vec4): Vec4
Divides one 4-dimensional vector by another and writes the result to the specified vector.
Parameters
lhs (Vec4): The dividend vector (the vector being divided).rhs (Vec4): The divisor vector (the vector dividing the dividend).Returns Vec4: Self for chaining.
Example
const a = new Vec4(4, 9, 16, 25);
const b = new Vec4(2, 3, 4, 5);
const r = new Vec4();
r.div2(a, b);
// Outputs [2, 3, 4, 5]
console.log("The result of the division is: " + r.toString());
divScalar(scalar: number): Vec4
Divides each element of a vector by a number.
Parameters
scalar (number): The number to divide by.Returns Vec4: Self for chaining.
Example
const vec = new Vec4(3, 6, 9, 12);
vec.divScalar(3);
// Outputs [1, 2, 3, 4]
console.log("The result of the division is: " + vec.toString());
dot(rhs: Vec4): number
Returns the result of a dot product operation performed on the two specified 4-dimensional vectors.
Parameters
rhs (Vec4): The second 4-dimensional vector operand of the dot product.Returns number: The result of the dot product operation.
Example
const v1 = new Vec4(5, 10, 20, 40);
const v2 = new Vec4(10, 20, 40, 80);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);
equals(rhs: Vec4): boolean
Reports whether two vectors are equal.
Parameters
rhs (Vec4): The vector to compare to the specified vector.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec4(1, 2, 3, 4);
const b = new Vec4(5, 6, 7, 8);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));
equalsApprox(rhs: Vec4, epsilon?: number): boolean
Reports whether two vectors are equal using an absolute error tolerance.
Parameters
rhs (Vec4): The vector to be compared against.epsilon (number, optional, default 1e-6): The maximum difference between each component of the two
vectors. Defaults to 1e-6.Returns boolean: True if the vectors are equal and false otherwise.
Example
const a = new Vec4();
const b = new Vec4();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));
floor(src?: Vec4): Vec4
Each element is set to the largest integer less than or equal to its value.
Parameters
src (Vec4, optional): The vector to floor. If not set, the operation is done in place.Returns Vec4: Self for chaining.
Example
const v = new Vec4(1.2, 3.9, 5.5, 7.8);
v.floor();
// v is now [1, 3, 5, 7]
fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec4
Set the values of the vector from an array.
Parameters
arr (number[] | ArrayBufferView<ArrayBufferLike>): The array to set the vector values from.offset (number, optional, default 0): The zero-based index at which to start copying elements from the
array. Default is 0.Returns Vec4: Self for chaining.
Example
const v = new Vec4();
v.fromArray([20, 10, 5, 0]);
// v is set to [20, 10, 5, 0]
length(): number
Returns the magnitude of the specified 4-dimensional vector.
Returns number: The magnitude of the specified 4-dimensional vector.
Example
const vec = new Vec4(3, 4, 0, 0);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);
lengthSq(): number
Returns the magnitude squared of the specified 4-dimensional vector.
Returns number: The magnitude squared of the specified 4-dimensional vector.
Example
const vec = new Vec4(3, 4, 0, 0);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);
lerp(lhs: Vec4, rhs: Vec4, alpha: number): Vec4
Returns the result of a linear interpolation between two specified 4-dimensional vectors.
Parameters
lhs (Vec4): The 4-dimensional vector to interpolate from.rhs (Vec4): The 4-dimensional vector to interpolate to.alpha (number): The value controlling the point of interpolation. Between 0 and 1,
the linear interpolant will occur on a straight line between lhs and rhs. Outside of this
range, the linear interpolant will occur on a ray extrapolated from this line.Returns Vec4: Self for chaining.
Example
const a = new Vec4(0, 0, 0, 0);
const b = new Vec4(10, 10, 10, 10);
const r = new Vec4();
r.lerp(a, b, 0); // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5, 5, 5
r.lerp(a, b, 1); // r is equal to b
max(rhs: Vec4): Vec4
Each element is assigned a value from rhs parameter if it is larger.
Parameters
rhs (Vec4): The 4-dimensional vector used as the source of elements to compare to.Returns Vec4: Self for chaining.
Example
const a = new Vec4(5, 1, 7, 3);
const b = new Vec4(2, 8, 3, 9);
a.max(b);
// a is now [5, 8, 7, 9]
min(rhs: Vec4): Vec4
Each element is assigned a value from rhs parameter if it is smaller.
Parameters
rhs (Vec4): The 4-dimensional vector used as the source of elements to compare to.Returns Vec4: Self for chaining.
Example
const a = new Vec4(5, 1, 7, 3);
const b = new Vec4(2, 8, 3, 9);
a.min(b);
// a is now [2, 1, 3, 3]
mul(rhs: Vec4): Vec4
Multiplies a 4-dimensional vector to another in place.
Parameters
rhs (Vec4): The 4-dimensional vector used as the second multiplicand of the operation.Returns Vec4: Self for chaining.
Example
const a = new Vec4(2, 3, 4, 5);
const b = new Vec4(4, 5, 6, 7);
a.mul(b);
// Outputs 8, 15, 24, 35
console.log("The result of the multiplication is: " + a.toString());
mul2(lhs: Vec4, rhs: Vec4): Vec4
Returns the result of multiplying the specified 4-dimensional vectors together.
Parameters
lhs (Vec4): The 4-dimensional vector used as the first multiplicand of the operation.rhs (Vec4): The 4-dimensional vector used as the second multiplicand of the operation.Returns Vec4: Self for chaining.
Example
const a = new Vec4(2, 3, 4, 5);
const b = new Vec4(4, 5, 6, 7);
const r = new Vec4();
r.mul2(a, b);
// Outputs 8, 15, 24, 35
console.log("The result of the multiplication is: " + r.toString());
mulScalar(scalar: number): Vec4
Multiplies each element of a vector by a number.
Parameters
scalar (number): The number to multiply by.Returns Vec4: Self for chaining.
Example
const vec = new Vec4(3, 6, 9, 12);
vec.mulScalar(3);
// Outputs [9, 18, 27, 36]
console.log("The result of the multiplication is: " + vec.toString());
normalize(src?: Vec4): Vec4
Returns this 4-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.
Parameters
src (Vec4, optional): The vector to normalize. If not set, the operation is done in place.Returns Vec4: Self for chaining.
Example
const v = new Vec4(25, 0, 0, 0);
v.normalize();
// Outputs 1, 0, 0, 0
console.log("The result of the vector normalization is: " + v.toString());
round(src?: Vec4): Vec4
Each element is rounded up or down to the nearest integer.
Parameters
src (Vec4, optional): The vector to round. If not set, the operation is done in place.Returns Vec4: Self for chaining.
Example
const v = new Vec4(1.4, 3.6, 5.5, 7.2);
v.round();
// v is now [1, 4, 6, 7]
set(x: number, y: number, z: number, w: number): Vec4
Sets the specified 4-dimensional vector to the supplied numerical values.
Parameters
x (number): The value to set on the first component of the vector.y (number): The value to set on the second component of the vector.z (number): The value to set on the third component of the vector.w (number): The value to set on the fourth component of the vector.Returns Vec4: Self for chaining.
Example
const v = new Vec4();
v.set(5, 10, 20, 40);
// Outputs 5, 10, 20, 40
console.log("The result of the vector set is: " + v.toString());
sub(rhs: Vec4): Vec4
Subtracts a 4-dimensional vector from another in place.
Parameters
rhs (Vec4): The vector to subtract from the specified vector.Returns Vec4: Self for chaining.
Example
const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
a.sub(b);
// Outputs [-10, -10, -10, -10]
console.log("The result of the subtraction is: " + a.toString());
sub2(lhs: Vec4, rhs: Vec4): Vec4
Subtracts two 4-dimensional vectors from one another and returns the result.
Parameters
lhs (Vec4): The first vector operand for the subtraction.rhs (Vec4): The second vector operand for the subtraction.Returns Vec4: Self for chaining.
Example
const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
const r = new Vec4();
r.sub2(a, b);
// Outputs [-10, -10, -10, -10]
console.log("The result of the subtraction is: " + r.toString());
subScalar(scalar: number): Vec4
Subtracts a number from each element of a vector.
Parameters
scalar (number): The number to subtract.Returns Vec4: Self for chaining.
Example
const vec = new Vec4(3, 4, 5, 6);
vec.subScalar(2);
// Outputs [1, 2, 3, 4]
console.log("The result of the subtraction is: " + vec.toString());
toArray(arr?: number[], offset?: number): number[]
Parameters
arr (number[], optional): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns number[]: The vector as an array.
toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView
Parameters
arr (ArrayBufferView): The array to populate with the vector's number
components. If not specified, a new array is created.offset (number, optional): The zero-based index at which to start copying elements to the
array. Default is 0.Returns ArrayBufferView: The vector as an array.
toString(): string
Converts the vector to string form.
Returns string: The vector in string form.
Example
const v = new Vec4(20, 10, 5, 0);
// Outputs [20, 10, 5, 0]
console.log(v.toString());
Function · category: Math
bytesToInt24(r: number, g: number, b: number): number
Convert 3 8 bit Numbers into a single unsigned 24 bit Number.
Parameters
r (number): A single byte (0-255).g (number): A single byte (0-255).b (number): A single byte (0-255).Returns number: A single unsigned 24 bit Number.
Example
// Set result1 to 0x112233 from an array of 3 values
const result1 = math.bytesToInt24([0x11, 0x22, 0x33]);
// Set result2 to 0x112233 from 3 discrete values
const result2 = math.bytesToInt24(0x11, 0x22, 0x33);
Function · category: Math
bytesToInt32(r: number, g: number, b: number, a: number): number
Convert 4 1-byte Numbers into a single unsigned 32bit Number.
Parameters
r (number): A single byte (0-255).g (number): A single byte (0-255).b (number): A single byte (0-255).a (number): A single byte (0-255).Returns number: A single unsigned 32bit Number.
Example
// Set result1 to 0x11223344 from an array of 4 values
const result1 = math.bytesToInt32([0x11, 0x22, 0x33, 0x44]);
// Set result2 to 0x11223344 from 4 discrete values
const result2 = math.bytesToInt32(0x11, 0x22, 0x33, 0x44);
Function · category: Math
clamp(value: number, min: number, max: number): number
Clamp a number between min and max inclusive.
Parameters
value (number): Number to clamp.min (number): Min value.max (number): Max value.Returns number: The clamped value.
Example
math.clamp(5, 0, 10); // returns 5
math.clamp(-5, 0, 10); // returns 0
math.clamp(15, 0, 10); // returns 10
Function · category: Math
intToBytes24(i: number): number[]
Convert a 24-bit integer into an array of 3 bytes.
Parameters
i (number): Number holding an integer value.Returns number[]: An array of 3 bytes.
Example
// Set bytes to [0x11, 0x22, 0x33]
const bytes = math.intToBytes24(0x112233);
Function · category: Math
intToBytes32(i: number): number[]
Convert a 32-bit integer into an array of 4 bytes.
Parameters
i (number): Number holding an integer value.Returns number[]: An array of 4 bytes.
Example
// Set bytes to [0x11, 0x22, 0x33, 0x44]
const bytes = math.intToBytes32(0x11223344);
Function · category: Math
lerp(a: number, b: number, alpha: number): number
Calculates the linear interpolation of two numbers.
Parameters
a (number): Number to linearly interpolate from.b (number): Number to linearly interpolate to.alpha (number): The interpolation factor, clamped to the range 0 to 1.Returns number: The linear interpolation of two numbers.
Example
math.lerp(0, 10, 0); // returns 0
math.lerp(0, 10, 0.5); // returns 5
math.lerp(0, 10, 1); // returns 10
Function · category: Math
lerpAngle(a: number, b: number, alpha: number): number
Calculates the linear interpolation of two angles ensuring that interpolation is correctly performed across the 360 to 0 degree boundary. Angles are supplied in degrees.
Parameters
a (number): Angle (in degrees) to linearly interpolate from.b (number): Angle (in degrees) to linearly interpolate to.alpha (number): The value controlling the result of interpolation. When alpha is 0,
a is returned. When alpha is 1, b is returned. Between 0 and 1, a linear interpolation
between a and b is returned. alpha is clamped between 0 and 1.Returns number: The linear interpolation of two angles.
Example
math.lerpAngle(350, 10, 0.5); // returns 0 (shortest path crosses 360/0 boundary)
math.lerpAngle(0, 90, 0.5); // returns 45
Function · category: Math
lerpUnclamped(a: number, b: number, alpha: number): number
Calculates the unclamped linear interpolation of two numbers.
Parameters
a (number): Number to linearly interpolate from.b (number): Number to linearly interpolate to.alpha (number): The interpolation factor. Values outside the range 0 to 1 extrapolate
beyond a or b.Returns number: The linear interpolation of two numbers.
Example
math.lerpUnclamped(0, 10, -0.5); // returns -5
math.lerpUnclamped(0, 10, 0.5); // returns 5
math.lerpUnclamped(0, 10, 1.5); // returns 15
Function · category: Math
nearestPowerOfTwo(val: number): number
Returns the nearest (smaller or larger) power of 2 for the specified value.
Parameters
val (number): The value for which to calculate the nearest power of 2.Returns number: The nearest power of 2.
Example
math.nearestPowerOfTwo(17); // returns 16
math.nearestPowerOfTwo(24); // returns 32
Function · category: Math
nextPowerOfTwo(val: number): number
Returns the next power of 2 for the specified value.
Parameters
val (number): The value for which to calculate the next power of 2.Returns number: The next power of 2.
Example
math.nextPowerOfTwo(17); // returns 32
math.nextPowerOfTwo(32); // returns 32
Function · category: Math
powerOfTwo(x: number): boolean
Returns true if argument is a power-of-two and false otherwise.
Parameters
x (number): Number to check for power-of-two property.Returns boolean: true if power-of-two and false otherwise.
Example
math.powerOfTwo(32); // returns true
math.powerOfTwo(17); // returns false
Function · category: Math
random(min: number, max: number): number
Return a pseudo-random number between min and max. The number generated is in the range [min, max), that is inclusive of the minimum but exclusive of the maximum.
Parameters
min (number): Lower bound for range.max (number): Upper bound for range.Returns number: Pseudo-random number between the supplied range.
Example
math.random(0, 10); // returns a random number between 0 and 10
Function · category: Math
roundUp(numToRound: number, multiple: number): number
Rounds a number up to nearest multiple.
Parameters
numToRound (number): The number to round up.multiple (number): The multiple to round up to.Returns number: A number rounded up to nearest multiple.
Example
math.roundUp(17, 4); // returns 20
math.roundUp(16, 4); // returns 16
Function · category: Math
smootherstep(min: number, max: number, x: number): number
An improved version of the math.smoothstep function which has zero 1st and 2nd order derivatives at t=0 and t=1.
See https://en.wikipedia.org/wiki/Smoothstep#Variations for more details.
Parameters
min (number): The lower bound of the interpolation range.max (number): The upper bound of the interpolation range.x (number): The value to interpolate.Returns number: The smoothly interpolated value clamped between zero and one.
Example
math.smootherstep(0, 10, 5); // returns 0.5
Function · category: Math
smoothstep(min: number, max: number, x: number): number
The function interpolates smoothly between two input values based on a third one that should be between the first two. The returned value is clamped between 0 and 1.
The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0. This makes it easy to create a sequence of transitions using smoothstep to interpolate each segment rather than using a more sophisticated or expensive interpolation technique.
See https://en.wikipedia.org/wiki/Smoothstep for more details.
Parameters
min (number): The lower bound of the interpolation range.max (number): The upper bound of the interpolation range.x (number): The value to interpolate.Returns number: The smoothly interpolated value clamped between zero and one.
Example
math.smoothstep(0, 10, 5); // returns 0.5
Namespace · category: Math
Math API.
Class · extends PhysicsWorld · category: Physics
The Ammo.js (Bullet) physics backend. The Ammo global must be available when the world is
constructed - load the library first, then supply the backend to the application:
WasmModule.setConfig('Ammo', {
glueUrl: 'ammo.wasm.js',
wasmUrl: 'ammo.wasm.wasm',
fallbackUrl: 'ammo.js'
});
await new Promise((resolve) => {
WasmModule.getInstance('Ammo', () => resolve());
});
const options = new AppOptions();
options.physicsWorld = new AmmoPhysicsWorld();
When AppOptions#physicsWorld is omitted, the engine creates this backend automatically once application libraries have loaded, if the Ammo global is present.
new AmmoPhysicsWorld()
Create a new AmmoPhysicsWorld instance. The Ammo library must be loaded before the backend is constructed.
nativeWorld: anyClass · extends Component · category: Physics
The CollisionComponent enables an Entity to act as a collision volume. Use it on its own to define a trigger volume. Or use it in conjunction with a RigidBodyComponent to make a collision volume that can be simulated using the physics engine.
When an entity is configured as a trigger volume, if an entity with a dynamic or kinematic body enters or leaves that trigger volume, both entities will receive trigger events.
You should never need to use the CollisionComponent constructor directly. To add a CollisionComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('collision'); // This defaults to 1x1x1 box-shaped trigger volume
To create a 0.5 radius dynamic rigid body sphere:
const entity = new Entity();
entity.addComponent('collision', {
type: 'sphere'
});
entity.addComponent('rigidbody', {
type: 'dynamic'
});
Once the CollisionComponent is added to the entity, you can access it via the Entity#collision property:
entity.collision.type = 'cylinder'; // Set the collision volume to a cylinder
console.log(entity.collision.type); // Get the collision volume type and print it
Relevant Engine API examples:
get angularOffset(): Readonly<Quat>
set angularOffset(arg: Readonly<Quat>)
Gets the rotational offset of the collision shape from the Entity rotation in local space. Use the setter to update the collision shape.
get asset(): number | Asset<string> | null
set asset(arg: number | Asset<string> | null)
Gets the asset or asset id for the model of the mesh collision volume.
get axis(): number
set axis(arg: number)
Gets the local space axis with which the capsule, cylinder or cone-shaped collision volume's length is aligned.
get checkVertexDuplicates(): boolean
set checkVertexDuplicates(arg: boolean)
Gets whether checking for duplicate vertices should be enabled when creating collision meshes.
get convexHull(): boolean
set convexHull(arg: boolean)
Gets whether the collision mesh should be treated as a convex hull.
get halfExtents(): Readonly<Vec3>
set halfExtents(arg: Readonly<Vec3>)
Gets the half-extents of the box-shaped collision volume in the x, y and z axes. Use the setter to update the collision shape.
get height(): number
set height(arg: number)
Gets the total height of the capsule, cylinder or cone-shaped collision volume from tip to tip.
get linearOffset(): Readonly<Vec3>
set linearOffset(arg: Readonly<Vec3>)
Gets the positional offset of the collision shape from the Entity position along the local axes. Use the setter to update the collision shape.
get model(): Model | null
set model(arg: Model | null)
Gets the model that is added to the scene graph for the mesh collision volume.
get radius(): number
set radius(arg: number)
Gets the radius of the sphere, capsule, cylinder or cone-shaped collision volumes.
get renderAsset(): number | Asset<string> | null
set renderAsset(arg: number | Asset<string> | null)
Gets the render asset id of the mesh collision volume.
get type(): "mesh" | "box" | "capsule" | "compound" | "cone" | "cylinder" | "sphere"
set type(arg: "mesh" | "box" | "capsule" | "compound" | "cone" | "cylinder" | "sphere")
Gets the type of the collision volume.
getShapePosition(): Vec3
Returns the world position for the collision shape, taking into account of any offsets.
Returns Vec3: The world position for the collision shape.
getShapeRotation(): Quat
Returns the world rotation for the collision shape, taking into account of any offsets.
Returns Quat: The world rotation for the collision.
static EVENT_COLLISIONEND: string = 'collisionend'
Fired when two rigid bodies stop touching. The handler is passed an Entity that represents the other rigid body involved in the collision.
Example
entity.collision.on('collisionend', (other) => {
console.log(`${entity.name} stopped touching ${other.name}`);
});
static EVENT_COLLISIONSTART: string = 'collisionstart'
Fired when two rigid bodies start touching. The handler is passed the ContactResult object which contains details of the contact between the two rigid bodies.
Example
entity.collision.on('collisionstart', (result) => {
console.log(`${entity.name} started touching ${result.other.name}`);
});
static EVENT_CONTACT: string = 'contact'
Fired when a contact occurs between two rigid bodies. The handler is passed a ContactResult object which contains details of the contact between the two rigid bodies.
Example
entity.collision.on('contact', (result) => {
console.log(`Contact between ${entity.name} and ${result.other.name}`);
});
static EVENT_TRIGGERENTER: string = 'triggerenter'
Fired when a rigid body enters a trigger volume. The handler is passed an Entity representing the rigid body that entered this collision volume.
Example
entity.collision.on('triggerenter', (other) => {
console.log(`${other.name} entered trigger volume ${entity.name}`);
});
static EVENT_TRIGGERLEAVE: string = 'triggerleave'
Fired when a rigid body exits a trigger volume. The handler is passed an Entity representing the rigid body that exited this collision volume.
Example
entity.collision.on('triggerleave', (other) => {
console.log(`${other.name} exited trigger volume ${entity.name}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Physics
Manages the CollisionComponents of an application. Reach it through
app.systems.collision; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Physics
Represents a single point of contact between two colliding rigid bodies in the physics simulation. Each contact point stores detailed spatial information about the collision, including both local and world space coordinates of the exact contact points on both entities, the contact normal direction, and the collision impulse force.
Contact points are generated by the physics engine during collision detection and are typically accessed through a ContactResult object, which can contain multiple contact points for a single collision between two entities. Multiple contact points commonly occur when objects collide along edges or faces rather than at a single point.
The impulse property can be particularly useful for gameplay mechanics that need to respond differently based on the force of impact, such as damage calculations or sound effect volume.
Contact points are pooled and reused by the physics system, so a contact point and its vectors are only valid inside the event handler that receives them. Copy any values that are needed later, for example with Vec3#clone.
Example
// Access contact points from a collision event
entity.collision.on('contact', (result) => {
// Get the first contact point
const contact = result.contacts[0];
// Get the contact position in world space
const worldPos = contact.point;
// Check how hard the collision was
if (contact.impulse > 10) {
console.log("That was a hard impact!");
}
});
impulse: number
The total accumulated impulse applied by the constraint solver during the last sub-step. This value represents how hard two objects collided. Higher values indicate stronger impacts.
localPoint: Vec3
The point on the entity where the contact occurred, in the local space of its rigid body. That space has the entity's world position and rotation, with any CollisionComponent#linearOffset and CollisionComponent#angularOffset applied, and ignores the entity's scale.
localPointOther: Vec3
The point on the other entity where the contact occurred, in the local space of the other entity's rigid body (see ContactPoint#localPoint).
normal: Vec3
The normal vector of the contact on the other entity, in world space. This vector points away from the surface of the other entity at the point of contact.
point: Vec3
The point on the entity where the contact occurred, in world space.
pointOther: Vec3
The point on the other entity where the contact occurred, in world space.
Class · category: Physics
Represents a collection of contact points between two entities in a physics collision. When rigid bodies collide, this object stores the entity involved in the collision and an array of specific contact points where the collision occurred. This information is used by the physics system to resolve collisions and notify components through events.
Instances of this class are passed to event handlers for the contact and collisionstart
events on individual RigidBodyComponent and CollisionComponent instances.
Unlike SingleContactResult which is used for global contact events, ContactResult objects provide information about collision from the perspective of one entity, with information about which other entity was involved and all points of contact.
Contact results are pooled and reused by the physics system, so a result and its contact points are only valid inside the event handler that receives them. Copy any values that are needed later.
Please refer to the following event documentation for more information:
contacts: ContactPoint[]
An array of ContactPoints with the other entity.
other: Entity
The entity that was involved in the contact with this entity.
Class · extends Component · category: Physics
The JointComponent constrains the relative motion of two rigid bodies. The entity holding the joint component is not itself constrained - instead, its world transform defines the joint frame: the anchor point and axes that the constraint operates about. The constrained bodies are assigned via entityA and entityB, both of which must have a RigidBodyComponent. If entityB is null, entityA is constrained to a fixed point in world space.
A joint's primary axis is the joint entity's local X axis: a hinge rotates about X, a slider translates along X and a ball joint twists about X. To aim a joint, rotate the joint entity. A common pattern is to parent the joint entity to entityA at the pivot point.
The joint frames are captured when the underlying constraint is created - typically when the component is enabled and both bodies are present in the physics simulation. Moving the joint entity afterwards has no effect on an existing constraint. Call refreshFrames to re-capture the frames from the current world transforms. Entity scale is ignored, matching the behavior of rigid bodies.
At creation the two joint frames coincide, so every degree of freedom reads zero: limits and
equilibrium values are measured from the initial relative pose of the two bodies, not from the
joint entity's transform or any absolute separation. Linear degrees of freedom are positive
when entityB (or the world anchor when entityB is null) moves along the
joint's positive axes relative to entityA. Angular degrees of freedom measure the
opposite body: they are positive when entityA rotates counter-clockwise about the
joint's axes relative to entityB or the world anchor, viewed from each axis's positive
end (right-handed). In the door hinge example below, the limits of [0, 110] let the door
swing counter-clockwise, viewed from above, up to 110 degrees from its starting pose.
Many properties apply only to specific joint types; each one documents the types it affects, and properties without such a note (for example entityA, enableCollision and breakImpulse) apply to all types.
To add a JointComponent to an Entity, use Entity#addComponent:
// Create a door hinge: the joint entity's position is the hinge point and its
// local X axis (rotated here to point up) is the hinge axis
const hinge = new Entity('hinge');
hinge.setPosition(1, 1, 0);
hinge.setEulerAngles(0, 0, 90);
hinge.addComponent('joint', {
type: JOINTTYPE_HINGE,
entityA: door,
entityB: doorFrame,
enableLimits: true,
limits: new Vec2(0, 110)
});
app.root.addChild(hinge);
get angularDamping(): Vec3
set angularDamping(arg: Vec3)
get angularEquilibrium(): Vec3
set angularEquilibrium(arg: Vec3)
get angularLimitsX(): Vec2
set angularLimitsX(arg: Vec2)
get angularLimitsY(): Vec2
set angularLimitsY(arg: Vec2)
get angularLimitsZ(): Vec2
set angularLimitsZ(arg: Vec2)
get angularMotionX(): "free" | "limited" | "locked"
set angularMotionX(arg: "free" | "limited" | "locked")
get angularMotionY(): "free" | "limited" | "locked"
set angularMotionY(arg: "free" | "limited" | "locked")
get angularMotionZ(): "free" | "limited" | "locked"
set angularMotionZ(arg: "free" | "limited" | "locked")
get angularStiffness(): Vec3
set angularStiffness(arg: Vec3)
get breakImpulse(): number
set breakImpulse(impulse: number)
get enableCollision(): boolean
set enableCollision(enableCollision: boolean)
get enableLimits(): boolean
set enableLimits(arg: boolean)
get entityA(): Entity | null
set entityA(arg: Entity | null)
get entityB(): Entity | null
set entityB(arg: Entity | null)
get isBroken(): boolean
get limits(): Vec2
set limits(arg: Vec2)
get linearDamping(): Vec3
set linearDamping(arg: Vec3)
get linearEquilibrium(): Vec3
set linearEquilibrium(arg: Vec3)
get linearLimitsX(): Vec2
set linearLimitsX(arg: Vec2)
get linearLimitsY(): Vec2
set linearLimitsY(arg: Vec2)
get linearLimitsZ(): Vec2
set linearLimitsZ(arg: Vec2)
get linearMotionX(): "free" | "limited" | "locked"
set linearMotionX(arg: "free" | "limited" | "locked")
get linearMotionY(): "free" | "limited" | "locked"
set linearMotionY(arg: "free" | "limited" | "locked")
get linearMotionZ(): "free" | "limited" | "locked"
set linearMotionZ(arg: "free" | "limited" | "locked")
get linearStiffness(): Vec3
set linearStiffness(arg: Vec3)
get maxMotorForce(): number
set maxMotorForce(arg: number)
get motorSpeed(): number
set motorSpeed(arg: number)
get swingLimitY(): number
set swingLimitY(arg: number)
get swingLimitZ(): number
set swingLimitZ(arg: number)
get twistLimit(): number
set twistLimit(arg: number)
get type(): "fixed" | "ball" | "hinge" | "slider" | "6dof"
set type(type: "fixed" | "ball" | "hinge" | "slider" | "6dof")
onBeforeRemove(): void
refreshFrames(): void
Destroys and recreates the underlying constraint, re-capturing the joint frames from the current world transforms of the joint entity, entityA and entityB. Call this after moving the joint entity to re-anchor the joint, or to re-attach a joint that has broken.
static EVENT_BREAK: string = 'break'
Fired when the applied impulse on the joint exceeds breakImpulse and the constraint breaks. The broken joint no longer constrains its bodies and isBroken becomes true. Call refreshFrames to re-attach it. Note that on ammo builds that expose no constraint state, breakage of 6dof joints cannot be detected, so this event does not fire for them - other joint types are unaffected.
Example
entity.joint.on('break', () => {
console.log('The joint broke');
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Physics
Manages the JointComponents of an application. Reach it through app.systems.joint;
components are created with Entity#addComponent, never by calling the system directly.
ComponentType: typeof JointComponent
destroy(): void
app: AppBaseid: stringschema: any[]store: {}fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends PhysicsWorld · category: Physics
A no-op physics backend. The PhysicsWorld base class is a functional no-op - bodies, shapes and joints are created but inert, raycasts miss and stepping does nothing - so this subclass adds nothing. It exists to let physics component lifecycle run without a physics engine loaded, and is installed explicitly:
const options = new AppOptions();
options.physicsWorld = new NullPhysicsWorld();
It is never auto-selected - without it, an application with no physics library keeps the default behavior where physics components are inert placeholders.
new NullPhysicsWorld()nativeWorld: any = nullClass · category: Physics
The base class for physics backends. A PhysicsWorld owns the lifecycle of a physics engine's simulation world: stepping, gravity, body and shape factories, joints, raycasts and contact reporting. Backends subclass it and override every method.
The base implementation is a functional no-op: bodies and joints are created but inert, raycasts miss and stepping does nothing. NullPhysicsWorld uses this to let physics component lifecycle run without a physics engine loaded.
Supply a backend to an application with AppOptions#physicsWorld.
Applications drive physics through the physics components - the methods of this class form the internal contract between the engine and a backend and are not called directly.
new PhysicsWorld()
nativeWorld: any = null
The backend-native world object - btDiscreteDynamicsWorld when the Ammo backend is active, null otherwise.
Class · category: Physics
Contains the result of a successful raycast intersection with a rigid body. When a ray intersects with a rigid body in the physics simulation, this class stores the complete information about that intersection including the entity, the exact point of impact, the normal at the impact point, and the fractional distance along the ray where the intersection occurred.
Instances of this class are created and returned by RigidBodyComponentSystem#raycastFirst and RigidBodyComponentSystem#raycastAll methods when performing physics raycasts.
entity: Entity
The entity that was hit.
hitFraction: number
The normalized distance (between 0 and 1) at which the ray hit occurred from the starting point.
normal: Vec3
The normal vector of the surface where the ray hit in world space.
point: Vec3
The point at which the ray hit the entity in world space.
Class · extends Component · category: Physics
The RigidBodyComponent, when combined with a CollisionComponent, allows your entities to be simulated using realistic physics. A RigidBodyComponent will fall under gravity and collide with other rigid bodies. Using scripts, you can apply forces and impulses to rigid bodies.
You should never need to use the RigidBodyComponent constructor directly. To add a RigidBodyComponent to an Entity, use Entity#addComponent:
// Create a static 1x1x1 box-shaped rigid body
const entity = new Entity();
entity.addComponent('collision'); // Without options, this defaults to a 1x1x1 box shape
entity.addComponent('rigidbody'); // Without options, this defaults to a 'static' body
To create a dynamic sphere with mass of 10, do:
const entity = new Entity();
entity.addComponent('collision', {
type: 'sphere'
});
entity.addComponent('rigidbody', {
type: 'dynamic',
mass: 10
});
Once the RigidBodyComponent is added to the entity, you can access it via the Entity#rigidbody property:
entity.rigidbody.mass = 10;
console.log(entity.rigidbody.mass);
For player movement, playcanvas/scripts/esm/first-person-controller.mjs and
playcanvas/scripts/esm/third-person-controller.mjs ship complete rigidbody character
controllers with capsule collision, damped ground and air movement, sprinting, jumping and
camera control. Attach one instead of driving the body by hand.
Relevant Engine API examples:
get angularDamping(): number
set angularDamping(damping: number)
Gets the rate at which a body loses angular velocity over time.
get angularFactor(): Readonly<Vec3>
set angularFactor(factor: Readonly<Vec3>)
Gets the scaling factor for angular movement of the body in each axis. Use the setter to update the physics body.
get angularVelocity(): Readonly<Vec3>
set angularVelocity(velocity: Readonly<Vec3>)
Gets the rotational speed of the body around each world axis. Use the setter to update the physics body.
get friction(): number
set friction(friction: number)
Gets the friction value used when contacts occur between two bodies.
get gravityScale(): number
set gravityScale(scale: number)
Gets the scale applied to the world gravity for this body.
get group(): number
set group(group: number)
Gets the collision group this body belongs to.
get linearDamping(): number
set linearDamping(damping: number)
Gets the rate at which a body loses linear velocity over time.
get linearFactor(): Readonly<Vec3>
set linearFactor(factor: Readonly<Vec3>)
Gets the scaling factor for linear movement of the body in each axis. Use the setter to update the physics body.
get linearVelocity(): Readonly<Vec3>
set linearVelocity(velocity: Readonly<Vec3>)
Gets the speed of the body in a given direction. Use the setter to update the physics body.
get mask(): number
set mask(mask: number)
Gets the collision mask sets which groups this body collides with.
get mass(): number
set mass(mass: number)
Gets the mass of the body.
get restitution(): number
set restitution(restitution: number)
Gets the value that controls the amount of energy lost when two rigid bodies collide.
get rollingFriction(): number
set rollingFriction(friction: number)
Gets the torsional friction orthogonal to the contact point.
get type(): "static" | "dynamic" | "kinematic"
set type(type: "static" | "dynamic" | "kinematic")
Gets the rigid body type determines how the body is simulated.
activate(): void
Forcibly activate the rigid body simulation. Only affects rigid bodies of type BODYTYPE_DYNAMIC.
applyForce(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void
Apply a force to the body at a point. By default, the force is applied at the origin of the body. However, the force can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.
Parameters
x (number): X-component of the force in world space.y (number): Y-component of the force in world space.z (number): Z-component of the force in world space.px (number, optional): X-component of the relative point at which to apply the force in
world space.py (number, optional): Y-component of the relative point at which to apply the force in
world space.pz (number, optional): Z-component of the relative point at which to apply the force in
world space.Returns void
Example
// Apply an approximation of gravity at the body's center
this.entity.rigidbody.applyForce(0, -10, 0);
Example
// Apply an approximation of gravity at 1 unit down the world Z from the center of the body
this.entity.rigidbody.applyForce(0, -10, 0, 0, 0, 1);
applyForce(force: Vec3, relativePoint?: Vec3): void
Apply a force to the body at a point. By default, the force is applied at the origin of the body. However, the force can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.
Parameters
force (Vec3): Vector representing the force in world space.relativePoint (Vec3, optional): Optional vector representing the relative point at which to
apply the force in world space.Returns void
Example
// Calculate a force vector pointing in the world space direction of the entity
const force = this.entity.forward.clone().mulScalar(100);
// Apply the force at the body's center
this.entity.rigidbody.applyForce(force);
Example
// Apply a force at some relative offset from the body's center
// Calculate a force vector pointing in the world space direction of the entity
const force = this.entity.forward.clone().mulScalar(100);
// Calculate the world space relative offset
const relativePoint = new Vec3();
const childEntity = this.entity.findByName('Engine');
relativePoint.sub2(childEntity.getPosition(), this.entity.getPosition());
// Apply the force
this.entity.rigidbody.applyForce(force, relativePoint);
applyImpulse(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void
Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the impulse is applied at the origin of the body. However, the impulse can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.
Parameters
x (number): X-component of the impulse in world space.y (number): Y-component of the impulse in world space.z (number): Z-component of the impulse in world space.px (number, optional): X-component of the relative point at which to apply the impulse in
world space.py (number, optional): Y-component of the relative point at which to apply the impulse in
world space.pz (number, optional): Z-component of the relative point at which to apply the impulse in
world space.Returns void
Example
// Apply an impulse along the world space positive y-axis at the body's origin
entity.rigidbody.applyImpulse(0, 10, 0);
Example
// Apply an impulse along the world space positive y-axis at 1 unit along the world space
// positive z-axis from the body's origin
entity.rigidbody.applyImpulse(0, 10, 0, 0, 0, 1);
applyImpulse(impulse: Vec3, relativePoint?: Vec3): void
Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the impulse is applied at the origin of the body. However, the impulse can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.
Parameters
impulse (Vec3): Vector representing the impulse in world space.relativePoint (Vec3, optional): Optional vector representing the relative point at which to
apply the impulse in world space.Returns void
Example
// Apply an impulse along the world space positive y-axis at the body's origin
const impulse = new Vec3(0, 10, 0);
entity.rigidbody.applyImpulse(impulse);
Example
// Apply an impulse along the world space positive y-axis at 1 unit along the world space
// positive z-axis from the body's origin
const impulse = new Vec3(0, 10, 0);
const relativePoint = new Vec3(0, 0, 1);
entity.rigidbody.applyImpulse(impulse, relativePoint);
Example
// Apply an impulse at an offset given in the entity's local space, by first rotating the
// offset into world space
const impulse = new Vec3(0, 10, 0);
const relativePoint = entity.getRotation().transformVector(new Vec3(0, 0, 1));
entity.rigidbody.applyImpulse(impulse, relativePoint);
applyTorque(x: number, y: number, z: number): void
Apply torque (rotational force) to the body.
Parameters
x (number): The x-component of the torque force in world space.y (number): The y-component of the torque force in world space.z (number): The z-component of the torque force in world space.Returns void
Example
entity.rigidbody.applyTorque(0, 10, 0);
applyTorque(torque: Vec3): void
Apply torque (rotational force) to the body.
Parameters
torque (Vec3): Vector representing the torque force in world space.Returns void
Example
const torque = new Vec3(0, 10, 0);
entity.rigidbody.applyTorque(torque);
applyTorqueImpulse(x: number, y: number, z: number): void
Apply a torque impulse (rotational force applied instantaneously) to the body.
Parameters
x (number): X-component of the torque impulse in world space.y (number): Y-component of the torque impulse in world space.z (number): Z-component of the torque impulse in world space.Returns void
Example
entity.rigidbody.applyTorqueImpulse(0, 10, 0);
applyTorqueImpulse(torque: Vec3): void
Apply a torque impulse (rotational force applied instantaneously) to the body.
Parameters
torque (Vec3): Vector representing the torque impulse in world space.Returns void
Example
const torque = new Vec3(0, 10, 0);
entity.rigidbody.applyTorqueImpulse(torque);
isActive(): boolean
Returns true if the rigid body is currently actively being simulated. I.e. Not 'sleeping'.
Returns boolean: True if the body is active.
isKinematic(): boolean
Returns true if the rigid body is of type BODYTYPE_KINEMATIC.
Returns boolean: True if kinematic.
isStatic(): boolean
Returns true if the rigid body is of type BODYTYPE_STATIC.
Returns boolean: True if static.
isStaticOrKinematic(): boolean
Returns true if the rigid body is of type BODYTYPE_STATIC or BODYTYPE_KINEMATIC.
Returns boolean: True if static or kinematic.
teleport(x: number, y: number, z: number, rx?: number, ry?: number, rz?: number): void
Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.
Parameters
x (number): X-coordinate of the new world space position.y (number): Y-coordinate of the new world space position.z (number): Z-coordinate of the new world space position.rx (number, optional): X-rotation of the world space Euler angles in degrees.ry (number, optional): Y-rotation of the world space Euler angles in degrees.rz (number, optional): Z-rotation of the world space Euler angles in degrees.Returns void
Example
// Teleport the entity to the origin
entity.rigidbody.teleport(0, 0, 0);
Example
// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
entity.rigidbody.teleport(1, 2, 3, 0, 0, 0);
teleport(position: Vec3, angles?: Vec3): void
Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.
Parameters
position (Vec3): Vector holding the new world space position.angles (Vec3, optional): Vector holding the new world space Euler angles in degrees.Returns void
Example
// Teleport the entity to the origin
entity.rigidbody.teleport(Vec3.ZERO);
Example
// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
const position = new Vec3(1, 2, 3);
entity.rigidbody.teleport(position, Vec3.ZERO);
teleport(position: Vec3, rotation?: Quat): void
Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.
Parameters
position (Vec3): Vector holding the new world space position.rotation (Quat, optional): Quaternion holding the new world space rotation.Returns void
Example
// Teleport the entity to the origin
entity.rigidbody.teleport(Vec3.ZERO);
Example
// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
const position = new Vec3(1, 2, 3);
entity.rigidbody.teleport(position, Quat.IDENTITY);
static EVENT_COLLISIONEND: string = 'collisionend'
Fired when two rigid bodies stop touching. The handler is passed an Entity that represents the other rigid body involved in the collision.
Example
entity.rigidbody.on('collisionend', (other) => {
console.log(`${entity.name} stopped touching ${other.name}`);
});
static EVENT_COLLISIONSTART: string = 'collisionstart'
Fired when two rigid bodies start touching. The handler is passed a ContactResult object containing details of the contact between the two rigid bodies.
Example
entity.rigidbody.on('collisionstart', (result) => {
console.log(`Collision started between ${entity.name} and ${result.other.name}`);
});
static EVENT_CONTACT: string = 'contact'
Fired when a contact occurs between two rigid bodies. The handler is passed a ContactResult object containing details of the contact between the two rigid bodies.
Example
entity.rigidbody.on('contact', (result) => {
console.log(`Contact between ${entity.name} and ${result.other.name}`);
});
static EVENT_TRIGGERENTER: string = 'triggerenter'
Fired when a rigid body enters a trigger volume. The handler is passed an Entity representing the trigger volume that this rigid body entered.
Example
entity.rigidbody.on('triggerenter', (trigger) => {
console.log(`Entity ${entity.name} entered trigger volume ${trigger.name}`);
});
static EVENT_TRIGGERLEAVE: string = 'triggerleave'
Fired when a rigid body exits a trigger volume. The handler is passed an Entity representing the trigger volume that this rigid body exited.
Example
entity.rigidbody.on('triggerleave', (trigger) => {
console.log(`Entity ${entity.name} exited trigger volume ${trigger.name}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Physics
The RigidBodyComponentSystem manages the physics simulation for all rigid body components
in the application and is accessed as app.systems.rigidbody. It owns the physics world,
creates and destroys the bodies behind rigid body and collision components, steps the
simulation once per frame and writes the resulting transforms back to their entities. It also
holds global settings such as RigidBodyComponentSystem#gravity, performs raycasts
and reports collisions.
The system is only functional once a physics backend is installed: either by supplying
AppOptions#physicsWorld when creating the application, or automatically when the
application has loaded the Ammo.js WasmModule. Use a recent Ammo.js build: mesh
colliders only follow entity scale with a build that exposes btScaledBvhTriangleMeshShape.
Set RigidBodyComponentSystem#timeScale to slow the simulation down, speed it up or pause it, for example while a pause menu is open, and call RigidBodyComponentSystem#step to advance it manually.
gravity: Vec3
The world space vector representing global gravity in the physics simulation. Defaults to [0, -9.81, 0] which is an approximation of the gravitational force on Earth.
The value is applied to the physics backend at the start of the next step, whether the vector is modified in place or replaced with a new one.
Example
// Set the gravity in the physics world to simulate a planet with low gravity
app.systems.rigidbody.gravity = new Vec3(0, -3.7, 0);
timeScale: number = 1
Scales the time the simulation is advanced by each frame. Defaults to 1. Values below 1 run physics in slow motion and values above 1 speed it up. 0 pauses the simulation: the system stops advancing it, bodies freeze in place, entity transforms are no longer driven by their bodies and no contact or trigger events fire. The rest of the application keeps running, so this suits a pause menu or inventory screen that must stay interactive while the game world stands still. Negative values are treated as 0.
This scale is applied on top of AppBase#timeScale. The simulation can still be advanced manually with RigidBodyComponentSystem#step while paused, for example to drive it from a custom time source.
How slow motion below one fixed substep per frame looks depends on the backend: the Ammo backend interpolates body transforms between substeps so motion stays smooth, while other backends may only move bodies on the frames in which a substep runs. Fast forward is limited by the maximum number of substeps the simulation may take per frame, beyond which it runs slower than requested.
Forces applied with RigidBodyComponent#applyForce while paused accumulate on the body and are applied together on the next step, because forces are only cleared when the simulation steps. Impulses and velocity changes take effect immediately.
Example
// Freeze the game world while the pause menu is open
app.systems.rigidbody.timeScale = 0;
Example
// Run physics at quarter speed for a slow motion effect
app.systems.rigidbody.timeScale = 0.25;
get physicsWorld(): PhysicsWorld | null
Gets the installed physics backend, or null when no backend is installed. Supply a backend via AppOptions#physicsWorld, or load the Ammo.js library to have one installed automatically.
raycastAll(start: Vec3, end: Vec3, options?: object): RaycastResult[]
Raycast the world and return all entities the ray hits. It returns an array of
RaycastResult, one for each hit. If no hits are detected, the returned array will be
of length 0. Results are returned in no particular order unless options.sort is true, in
which case they are sorted by distance with the closest first.
Parameters
start (Vec3): The world space point where the ray starts.end (Vec3): The world space point where the ray ends.options (object, optional, default {}): The additional options for the raycasting.
options.filterCallback (Function, optional): Custom function to use to filter entities.
Must return true to proceed with result. Takes the entity to evaluate as argument.options.filterCollisionGroup (number, optional): Collision group to apply to the raycast.options.filterCollisionMask (number, optional): Collision mask to apply to the raycast.options.filterTags (any[], optional): Tags filters. Defined the same way as a Tags#has
query but within an array.options.hitBackFaces (boolean, optional): Whether the ray can hit the back faces of mesh
colliders, which face away from the ray: the far side of a closed mesh, or the first surface
met by a ray starting inside one. A back-face hit reports a normal flipped to face the start
of the ray. Other collision shapes never report back-face hits. Defaults to true.options.sort (boolean, optional): Whether to sort raycast results based on distance with closest
first. Defaults to false.Returns RaycastResult[]: An array of raycast hit results (0 length if there were no hits
or no physics backend is installed).
Example
// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2));
Example
// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity is tagged with `bird` OR `mammal`
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
filterTags: [ "bird", "mammal" ]
});
Example
// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity has a `camera` component
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
filterCallback: (entity) => entity && entity.camera
});
Example
// Return all results of a raycast between 0, 2, 2 and 0, -2, -2, skipping the back faces
// of mesh colliders so a ray through a closed mesh hits it only where it enters
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
hitBackFaces: false
});
Example
// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity is tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`)
// and the entity has an `anim` component
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
filterTags: [
[ "carnivore", "mammal" ],
[ "carnivore", "reptile" ]
],
filterCallback: (entity) => entity && entity.anim
});
raycastFirst(start: Vec3, end: Vec3, options?: object): RaycastResult | null
Raycast the world and return the first entity the ray hits. Fire a ray into the world from start to end, if the ray hits an entity with a collision component, it returns a RaycastResult, otherwise returns null.
Parameters
start (Vec3): The world space point where the ray starts.end (Vec3): The world space point where the ray ends.options (object, optional, default {}): The additional options for the raycasting.
options.filterCallback (Function, optional): Custom function to use to filter entities.
Must return true to proceed with result. Takes one argument: the entity to evaluate.options.filterCollisionGroup (number, optional): Collision group to apply to the raycast.options.filterCollisionMask (number, optional): Collision mask to apply to the raycast.options.filterTags (any[], optional): Tags filters. Defined the same way as a Tags#has
query but within an array.options.hitBackFaces (boolean, optional): Whether the ray can hit the back faces of mesh
colliders, which face away from the ray: the far side of a closed mesh, or the first surface
met by a ray starting inside one. A back-face hit reports a normal flipped to face the start
of the ray. Other collision shapes never report back-face hits. Defaults to true.Returns RaycastResult | null: The result of the raycasting, or null if there was no hit or
no physics backend is installed.
step(dt: number): void
Advances the physics simulation by dt seconds. Synchronizes triggers, compound shapes and kinematic bodies from their entities, steps the backend in fixed-length substeps (up to a maximum number per call), writes the resulting transforms of dynamic bodies back to their entities and fires contact and trigger events.
The system calls this once per frame with the frame delta time multiplied by RigidBodyComponentSystem#timeScale, unless that is 0. Call it directly to step the simulation manually: to advance it while paused, to fast forward it by stepping several times in one frame, or to drive it from a custom time source. Automatic stepping continues while timeScale is above 0, so calling this every frame as well advances the simulation twice per frame. Set timeScale to 0 first when taking over stepping entirely. The delta is used as given, without applying timeScale. Does nothing when no physics backend is installed.
Parameters
dt (number): The amount of time to advance the simulation by, in seconds.Example
// Pause automatic stepping and advance the simulation by 1/60 s per key press
const physics = app.systems.rigidbody;
physics.timeScale = 0;
app.keyboard.on('keydown', (event) => {
if (event.key === KEY_SPACE) {
physics.step(1 / 60);
}
});
static EVENT_CONTACT: string = 'contact'
Fired when a contact occurs between two rigid bodies. The handler is passed a SingleContactResult object containing details of the contact between the two bodies.
Example
app.systems.rigidbody.on('contact', (result) => {
console.log(`Contact between ${result.a.name} and ${result.b.name}`);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Physics
Represents the detailed data of a single contact point between two rigid bodies in the physics simulation. This class provides comprehensive information about the contact, including the entities involved, the exact contact points in both local and world space coordinates, the contact normal, and the collision impulse force.
Instances of this class are created by the physics engine when collision events occur and are
passed to event handlers only through the global contact event on the
RigidBodyComponentSystem. Individual rigid body components receive instances of
ContactResult instead.
Instances are pooled and reused by the physics system, so a result and its vectors are only valid inside the event handler that receives them. Copy any values that are needed later.
Example
app.systems.rigidbody.on('contact', (result) => {
console.log(`Contact between ${result.a.name} and ${result.b.name}`);
});
a: Entity
The first entity involved in the contact.
b: Entity
The second entity involved in the contact.
impulse: number
The total accumulated impulse applied by the constraint solver during the last sub-step. Describes how hard two bodies collided.
localPointA: Vec3
The point on Entity A where the contact occurred, in the local space of A's rigid body (see ContactPoint#localPoint).
localPointB: Vec3
The point on Entity B where the contact occurred, in the local space of B's rigid body.
normal: Vec3
The normal vector of the contact on Entity B, in world space.
pointA: Vec3
The point on Entity A where the contact occurred, in world space.
pointB: Vec3
The point on Entity B where the contact occurred, in world space.
Class · category: Physics
Creates a trigger object used to create internal physics objects that interact with rigid bodies and trigger collision events with no collision response.
new Trigger(app: AppBase, component: CollisionComponent)
Create a new Trigger instance.
Parameters
app (AppBase): The running AppBase.component (CollisionComponent): The component for which the trigger will be created.Class · extends EventHandler · category: Script
The Script class is the fundamental base class for all scripts within PlayCanvas. It provides
the minimal interface required for a script to be compatible with both the Engine and the
Editor.
At its core, a script is simply a collection of methods that are called at various points in the Engine's lifecycle. These methods are:
Script#initialize - Called once when the script is initialized.Script#postInitialize - Called once after all scripts have been initialized.Script#update - Called every frame, if the script is enabled.Script#postUpdate - Called every frame, after all scripts have been updated.Script#swap - Called when a script is redefined.These methods are entirely optional, but provide a useful way to manage the lifecycle of a script and perform any necessary setup and cleanup.
Below is a simple example of a script that rotates an entity every frame.
Example
import { Script } from 'playcanvas';
export class Rotator extends Script {
static scriptName = 'rotator';
update(dt) {
this.entity.rotateLocal(0, 1, 0);
}
}
When this script is attached to an entity, the update will be called every frame, slowly rotating the entity around the Y-axis.
For more information on how to create scripts, see the Scripting Overview.
The playcanvas package also ships a library of ready-to-use Script subclasses under the
playcanvas/scripts/esm/ subpath — camera and character controllers, post-processing, water,
sky, grid, shadow catcher, planar reflections, XR and Gaussian-splat effects. Import them
directly, for example
import { CameraControls } from 'playcanvas/scripts/esm/camera-controls.mjs'.
new Script(args: object)
Create a new Script instance.
Parameters
args (object): The input arguments object.
app: AppBase
The AppBase that the instance of this script belongs to.
entity: Entity
The Entity that the instance of this script belongs to.
get enabled(): boolean
set enabled(value: boolean)
Gets the running state of the script instance. Returns true when the script instance is enabled and its owning Entity (and all ancestors) and ScriptComponent are also enabled; otherwise false.
static get scriptName(): string | null
static set scriptName(value: string | null)
Gets the unique name of the script.
protected initScript(args: ScriptInitializationArgs): void
Parameters
args (ScriptInitializationArgs): The input arguments object.static EVENT_ATTR: string = 'attr'
Fired when script attributes have changed. This event is available in two forms. They are as follows:
attr - Fired for any attribute change. The handler is passed the name of the attribute
that changed, the value of the attribute before the change and the value of the attribute
after the change.attr:[name] - Fired for a specific attribute change. The handler is passed the value of
the attribute before the change and the value of the attribute after the change.Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('attr', (name, newValue, oldValue) => {
console.log(`Attribute '${name}' changed from '${oldValue}' to '${newValue}'`);
});
}
};
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('attr:speed', (newValue, oldValue) => {
console.log(`Attribute 'speed' changed from '${oldValue}' to '${newValue}'`);
});
}
};
static EVENT_DESTROY: string = 'destroy'
Fired when a script instance is destroyed and removed from component.
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('destroy', () => {
// no longer part of the entity
// this is a good place to clean up allocated resources used by the script
});
}
};
static EVENT_DISABLE: string = 'disable'
Fired when a script instance becomes disabled.
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('disable', () => {
// Script Instance is now disabled
});
}
};
static EVENT_ENABLE: string = 'enable'
Fired when a script instance becomes enabled.
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('enable', () => {
// Script Instance is now enabled
});
}
};
static EVENT_ERROR: string = 'error'
Fired when a script instance had an exception. The script instance will be automatically disabled. The handler is passed an Error object containing the details of the exception and the name of the method that threw the exception.
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('error', (err, method) => {
// caught an exception
console.log(err.stack);
});
}
};
static EVENT_STATE: string = 'state'
Fired when a script instance changes state to enabled or disabled. The handler is passed a boolean parameter that states whether the script instance is now enabled or disabled.
Example
export class PlayerController extends Script {
static scriptName = 'playerController';
initialize() {
this.on('state', (enabled) => {
console.log(`Script Instance is now ${enabled ? 'enabled' : 'disabled'}`);
});
}
};
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Script
Container of Script Attribute definitions. Implements an interface to add/remove attributes and store their definition for a ScriptType. Note: An instance of ScriptAttributes is created automatically by each ScriptType.
new ScriptAttributes(scriptType: typeof ScriptType)
Create a new ScriptAttributes instance.
Parameters
scriptType (typeof ScriptType): Script Type that attributes relate to.add(name: string, args: object): void
Add Attribute.
Parameters
name (string): Name of an attribute.args (object): Object with Arguments for an attribute.
args.array (boolean, optional): If attribute can hold single or multiple values.
args.assetType (string, optional): Name of asset type to be used in 'asset' type attribute
picker in Editor's UI, defaults to '*' (all).
args.color (string, optional): String of color channels for Curves for field type 'curve',
can be any combination of rgba characters. Defining this property will render Gradient in
Editor's field UI.
args.curves (string[], optional): List of names for Curves for field type 'curve'.
args.default (any, optional): Default attribute value.
args.description (string, optional): Description for Editor's for field UI.
args.enum (any[], optional): List of fixed choices for field, defined as array of objects,
where key in object is a title of an option.
args.max (number, optional): Maximum value for type 'number', if max and min defined, slider
will be rendered in Editor's UI.
args.min (number, optional): Minimum value for type 'number', if max and min defined, slider
will be rendered in Editor's UI.
args.placeholder (string | string[], optional): Placeholder for Editor's for field UI.
For multi-field types, such as vec2, vec3, and others use array of strings.
args.precision (number, optional): Level of precision for field type 'number' with floating
values.
args.schema (any[], optional): List of attributes for type 'json'. Each attribute
description is an object with the same properties as regular script attributes but with an
added 'name' field to specify the name of each attribute in the JSON.
args.size (number, optional): If attribute is array, maximum number of values can be set.
args.step (number, optional): Step value for type 'number'. The amount used to increment the
value when using the arrow keys in the Editor's UI.
args.title (string, optional): Title for Editor's for field UI.
args.type ("string" | "number" | "boolean" | "rgb" | "curve" | "json" | "vec2" | "vec3" | "vec4" | "entity" | "asset" | "rgba"): Type
of an attribute value. Can be:
Example
PlayerController.attributes.add('fullName', {
type: 'string'
});
Example
PlayerController.attributes.add('speed', {
type: 'number',
title: 'Speed',
placeholder: 'km/h',
default: 22.2
});
Example
PlayerController.attributes.add('resolution', {
type: 'number',
default: 32,
enum: [
{ '32x32': 32 },
{ '64x64': 64 },
{ '128x128': 128 }
]
});
Example
PlayerController.attributes.add('config', {
type: 'json',
schema: [{
name: 'speed',
type: 'number',
title: 'Speed',
placeholder: 'km/h',
default: 22.2
}, {
name: 'resolution',
type: 'number',
default: 32,
enum: [
{ '32x32': 32 },
{ '64x64': 64 },
{ '128x128': 128 }
]
}]
});
get(name: string): any
Get object with attribute arguments. Note: Changing argument properties will not affect existing Script Instances.
Parameters
name (string): Name of an attribute.Returns any: Arguments with attribute properties.
Example
// changing default value for an attribute 'fullName'
var attr = PlayerController.attributes.get('fullName');
if (attr) attr.default = 'Unknown';
has(name: string): boolean
Detect if Attribute is added.
Parameters
name (string): Name of an attribute.Returns boolean: True if Attribute is defined.
Example
if (PlayerController.attributes.has('fullName')) {
// attribute fullName is defined
}
remove(name: string): boolean
Remove Attribute.
Parameters
name (string): Name of an attribute.Returns boolean: True if removed or false if not defined.
Example
PlayerController.attributes.remove('fullName');
Class · extends Component · category: Script
The ScriptComponent enables an Entity to have custom behavior by attaching scripts written in JavaScript (or TypeScript).
You should never need to use the ScriptComponent constructor directly. To add a ScriptComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('script');
Once the ScriptComponent is added to the entity, you can access it via the Entity#script property:
// Option 1: Add a script using the name registered in the ScriptRegistry
entity.script.create('cameraControls');
// Option 2: Add a script using the script class
entity.script.create(CameraControls);
For more details on scripting see the Scripting Section of the User Manual.
get scripts(): readonly Script[]
set scripts(value: readonly Script[])
Gets the array of all script instances attached to an entity. Use create, destroy and move to change attached scripts or their order.
create<T extends Script>(type: Object, args?: object): T | null
Create a script instance of the specified class and attach it to the entity's script component. The result is typed as an instance of that class, so no cast is needed.
Parameters
type (Object): The script class.args (object, optional): Object with arguments for a script.
args.attributes (any, optional): Object with values for attributes (if any), where key is
name of an attribute.args.enabled (boolean, optional): If script instance is enabled after creation. Defaults to
true.args.ind (number, optional): The index where to insert the script instance at. Defaults to
-1, which means append it at the end.args.preloading (boolean, optional): If script instance is created during preload. If true,
script and attributes must be initialized manually. Defaults to false.args.properties (any, optional): Object with values that are assigned to the script
instance.Returns T | null: Returns an instance of the class if successfully attached to the entity,
or null if it failed because a script with the same name has already been added.
Example
const controller = entity.script.create(PlayerController, {
properties: {
speed: 4
}
}); // PlayerController | null
create(name: string, args?: object): Script | null
Create a script instance by name and attach it to the entity's script component. The name is looked up in the application's ScriptRegistry.
Parameters
name (string): The name of the script.args (object, optional): Object with arguments for a script.
args.attributes (any, optional): Object with values for attributes (if any), where key is
name of an attribute.args.enabled (boolean, optional): If script instance is enabled after creation. Defaults to
true.args.ind (number, optional): The index where to insert the script instance at. Defaults to
-1, which means append it at the end.args.preloading (boolean, optional): If script instance is created during preload. If true,
script and attributes must be initialized manually. Defaults to false.args.properties (any, optional): Object with values that are assigned to the script
instance.Returns Script | null: Returns the script instance if successfully attached to the entity,
or null if it failed because a script with the same name has already been added or if the
name cannot be found in the ScriptRegistry.
Example
entity.script.create('playerController', {
attributes: {
speed: 4
}
});
destroy(nameOrType: string | typeof Script): boolean
Destroy the script instance that is attached to an entity.
Parameters
Returns boolean: If it was successfully destroyed.
Example
entity.script.destroy('playerController');
get<T extends Script>(type: Object): T | null
Get a script instance (if attached) by its class. The result is typed as an instance of that class, so no cast is needed.
Parameters
type (Object): The script class.Returns T | null: If a script of the class is attached, the instance is returned. Otherwise
null is returned.
Example
const controller = entity.script.get(PlayerController); // PlayerController | null
get(name: string): Script | null
Get a script instance (if attached) by its name.
Parameters
name (string): The name of the script.Returns Script | null: If a script with the name is attached, the instance is returned.
Otherwise null is returned, including while a script declared by name is still awaiting its
class to be added to the ScriptRegistry.
Example
const controller = entity.script.get('playerController');
has(nameOrType: string | typeof Script): boolean
Detect if script is attached to an entity.
Parameters
Returns boolean: If script is attached to an entity.
Example
if (entity.script.has('playerController')) {
// entity has script
}
move(nameOrType: string | typeof Script, ind: number): boolean
Move script instance to different position to alter update order of scripts within entity.
Parameters
nameOrType (string | typeof Script): The name or class of the Script.ind (number): New position index.Returns boolean: If it was successfully moved.
Example
entity.script.move('playerController', 0);
static EVENT_CREATE: string = 'create'
Fired when a Script instance is created and attached to the script component. This event is available in two forms. They are as follows:
create - Fired when a script instance is created. The name of the script type and the
script type instance are passed as arguments.create:[name] - Fired when a script instance is created that has the specified script
type name. The script instance is passed as an argument to the handler.Example
entity.script.on('create', (name, scriptInstance) => {
console.log(`Instance of script '${name}' created`);
});
Example
entity.script.on('create:player', (scriptInstance) => {
console.log(`Instance of script 'player' created`);
});
static EVENT_DESTROY: string = 'destroy'
Fired when a Script instance is destroyed and removed from the script component. This event is available in two forms. They are as follows:
destroy - Fired when a script instance is destroyed. The name of the script type and
the script type instance are passed as arguments.destroy:[name] - Fired when a script instance is destroyed that has the specified
script type name. The script instance is passed as an argument.Example
entity.script.on('destroy', (name, scriptInstance) => {
console.log(`Instance of script '${name}' destroyed`);
});
Example
entity.script.on('destroy:player', (scriptInstance) => {
console.log(`Instance of script 'player' destroyed`);
});
static EVENT_DISABLE: string = 'disable'
Fired when the script component becomes disabled. This event does not take into account the enabled state of the entity or any of its ancestors.
Example
entity.script.on('disable', () => {
console.log(`Script component of entity '${entity.name}' has been disabled`);
});
static EVENT_ENABLE: string = 'enable'
Fired when the script component becomes enabled. This event does not take into account the enabled state of the entity or any of its ancestors.
Example
entity.script.on('enable', () => {
console.log(`Script component of entity '${entity.name}' has been enabled`);
});
static EVENT_ERROR: string = 'error'
Fired when a Script instance had an exception. The handler is passed the script instance, the exception and the method name that the exception originated from.
Example
entity.script.on('error', (scriptInstance, exception, methodName) => {
console.log(`Script error: ${exception} in method '${methodName}'`);
});
static EVENT_MOVE: string = 'move'
Fired when the index of a Script instance is changed in the script component. This event is available in two forms. They are as follows:
move - Fired when a script instance is moved. The name of the script type, the script
type instance, the new index and the old index are passed as arguments.move:[name] - Fired when a specifically named script instance is moved. The script
instance, the new index and the old index are passed as arguments.Example
entity.script.on('move', (name, scriptInstance, newIndex, oldIndex) => {
console.log(`Script '${name}' moved from index '${oldIndex}' to '${newIndex}'`);
});
Example
entity.script.on('move:player', (scriptInstance, newIndex, oldIndex) => {
console.log(`Script 'player' moved from index '${oldIndex}' to '${newIndex}'`);
});
static EVENT_REMOVE: string = 'remove'
Fired when the script component has been removed from its entity.
Example
entity.script.on('remove', () => {
console.log(`Script component removed from entity '${entity.name}'`);
});
static EVENT_STATE: string = 'state'
Fired when the script component changes state to enabled or disabled. The handler is passed the new boolean enabled state of the script component. This event does not take into account the enabled state of the entity or any of its ancestors.
Example
entity.script.on('state', (enabled) => {
console.log(`Script component of entity '${entity.name}' changed state to '${enabled}'`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Script
Manages the ScriptComponents of an application. Reach it through app.systems.script;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Script
Container for all Script classes that are available to this application. Note that PlayCanvas scripts can access the Script Registry from inside the application with AppBase#scripts.
new ScriptRegistry(app: AppBase)
Create a new ScriptRegistry instance.
Parameters
app (AppBase): Application to attach registry to.add(script: typeof Script): boolean
Add a script to the registry, keyed by its name. The name is taken from the script's static
scriptName property (for Script classes), or assigned by createScript /
registerScript. Note: when createScript or registerScript is called,
the script is added to the registry automatically, so calling this method directly is only
required when registering a Script class manually (e.g. in an engine-only project).
If a script with the same name already exists in the registry, and the new script has a
swap method defined, it will perform code hot swapping automatically in an async manner.
Parameters
script (typeof Script): The script class to add. Must have a
resolvable name (a static scriptName, an assigned __name, or an inferable class name).Returns boolean: True if the script was added for the first time. False if a script with
the same name already exists, or if the script has no resolvable name.
Example
var PlayerController = createScript('playerController');
// playerController Script Type will be added to ScriptRegistry automatically
console.log(app.scripts.has('playerController')); // outputs true
Example
// engine-only: register an ESM Script class manually
class Rotator extends Script {
static scriptName = 'rotator';
}
app.scripts.add(Rotator);
console.log(app.scripts.has('rotator')); // outputs true
addSchema(id: string, schema: AttributeSchema): void
Registers a schema against a script instance.
Parameters
id (string): The key to use to store the schemaschema (AttributeSchema): An schema definition for the scriptget(name: string): typeof Script | null
Get a Script class by name.
Parameters
name (string): Name of the Script.Returns typeof Script | null: The script class if it exists in the registry or null
otherwise.
Example
var PlayerController = app.scripts.get('playerController');
getSchema(id: string): AttributeSchema | undefined
Returns a schema for a given script name.
Parameters
id (string): The key to store the schema underReturns AttributeSchema | undefined: - The schema stored under the key
has(nameOrType: string | typeof Script): boolean
Check if a Script class with the specified name is in the registry.
Parameters
Returns boolean: True if the Script class is in the registry.
Example
if (app.scripts.has('playerController')) {
// playerController is in ScriptRegistry
}
list(): typeof Script[]
Get list of all Script classes from registry.
Returns typeof Script[]: list of all Script classes in registry.
Example
// logs array of all Script Type names available in registry
console.log(app.scripts.list().map(function (o) {
return o.name;
}));
remove(nameOrType: string | typeof Script): boolean
Remove a Script class from the registry.
Parameters
Returns boolean: True if removed or False if already not in registry.
Example
app.scripts.remove('playerController');
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Script · category: Script · deprecated
This is the legacy format for creating a PlayCanvas script returned when calling createScript().
Do not inherit from this class directly.
Deprecated: Use Script instead.
new ScriptType(args: object)
Create a new ScriptType instance.
Parameters
args (object): The input arguments object.
static get attributes(): ScriptAttributes
The interface to define attributes for Script Types. Refer to ScriptAttributes.
Example
var PlayerController = createScript('playerController');
PlayerController.attributes.add('speed', {
type: 'number',
title: 'Speed',
placeholder: 'km/h',
default: 22.2
});
protected initScript(args: any): void
Parameters
args (any): initialization argumentsprotected initScriptType(args: any): void
Expose initScript as initScriptType for backwards compatibility
Parameters
args (any): Initialization argumentsstatic extend(methods: any): void
Shorthand function to extend Script Type prototype with list of methods.
Parameters
methods (any): Object with methods, where key - is name of method, and value - is function.Example
var PlayerController = createScript('playerController');
PlayerController.extend({
initialize: function () {
// called once on initialize
},
update: function (dt) {
// called each tick
}
});
app: AppBaseentity: Entityget enabled(): boolean · set enabled(value: boolean)static get scriptName(): string | null · static set scriptName(value: string | null)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlestatic EVENT_ATTR: string = 'attr'static EVENT_DESTROY: string = 'destroy'static EVENT_DISABLE: string = 'disable'static EVENT_ENABLE: string = 'enable'static EVENT_ERROR: string = 'error'static EVENT_STATE: string = 'state'Function · category: Script
createScript(name: string, app?: AppBase): typeof ScriptType | null
Create and register a new ScriptType. It returns new class type (constructor function), which is auto-registered to ScriptRegistry using its name. This is the main interface to create Script Types, to define custom logic using JavaScript, that is used to create interaction for entities.
Parameters
name (string): Unique Name of a Script Type. If a Script Type with the same name has
already been registered and the new one has a swap method defined in its prototype, then it
will perform hot swapping of existing Script Instances on entities using this new Script Type.
Note: There is a reserved list of names that cannot be used, such as list below as well as some
starting from _ (underscore): system, entity, create, destroy, swap, move, scripts, onEnable,
onDisable, onPostStateChange, has, on, off, fire, once, hasEvent, worker.app (AppBase, optional): Optional application handler, to choose which ScriptRegistry
to add a script to. By default it will use Application.getApplication() to get current
AppBase.Returns typeof ScriptType | null: A class type (constructor function) that inherits ScriptType,
which the developer is meant to further extend by adding attributes and prototype methods.
Returns null if there was an error.
Example
var Turning = createScript('turn');
// define 'speed' attribute that is available in Editor UI
Turning.attributes.add('speed', {
type: 'number',
default: 180,
placeholder: 'deg/s'
});
// runs every tick
Turning.prototype.update = function (dt) {
this.entity.rotate(0, this.speed * dt, 0);
};
Function · category: Script
registerScript(script: typeof ScriptType, name?: string, app?: AppBase): void
Register an existing class type as a Script Type with ScriptRegistry. Useful when defining an ES6 script class that extends ScriptType (see example).
Parameters
script (typeof ScriptType): The existing class type (constructor function) to be
registered as a Script Type. Class must extend ScriptType (see example). Please note: A
class created using createScript is auto-registered, and should therefore not be passed
into registerScript (which would result in swapping out all related script instances).name (string, optional): Optional unique name of the Script Type. By default it will use the
same name as the existing class. If a Script Type with the same name has already been registered
and the new one has a swap method defined in its prototype, then it will perform hot swapping
of existing Script Instances on entities using this new Script Type. Note: There is a reserved
list of names that cannot be used, such as list below as well as some starting from _
(underscore): system, entity, create, destroy, swap, move, scripts, onEnable, onDisable,
onPostStateChange, has, on, off, fire, once, hasEvent.app (AppBase, optional): Optional application handler, to choose which ScriptRegistry
to register the script type with. By default it will use Application.getApplication() to get
the current AppBase.Example
// define an ES6 script class
class PlayerController extends ScriptType {
initialize() {
// called once on initialize
}
update(dt) {
// called each tick
}
}
// register the class as a script
registerScript(PlayerController);
// declare script attributes (Must be after registerScript())
PlayerController.attributes.add('attribute1', {type: 'number'});
Function · category: Script
createLoadingScreen(callback: CreateScreenCallback): void
Handles the creation of the loading screen of the application. A script can subscribe to the events of a AppBase to show a loading screen, progress bar etc. In order for this to work you need to set the project's loading screen script to the script that calls this method.
Parameters
callback (CreateScreenCallback): A function which can set up and tear down a
customized loading screen.Example
script.createLoadingScreen((app) => {
const showSplashScreen = () => {};
const hideSplashScreen = () => {};
const showProgress = (progress) => {};
app.on("preload:start", showSplashScreen);
app.on("preload:progress", showProgress);
app.on("start", hideSplashScreen);
});
Namespace · category: Script
The script namespace holds the createLoadingScreen function that is used to override the default PlayCanvas loading screen.
Class · extends Component · category: Sound
The AudioListenerComponent enables an Entity to represent the point from where positional SoundComponents are heard. This is typically the main camera Entity in your scene. And typically, you will only have one AudioListenerComponent in your scene.
You should never need to use the AudioListenerComponent constructor directly. To add a AudioListenerComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('audiolistener');
Once the AudioListenerComponent is added to the entity, you can access it via the Entity#audiolistener property:
entity.audiolistener.enabled = false; // Disable the audio listener
console.log(entity.audiolistener.enabled); // Get the enabled state and print it
Relevant Engine API examples:
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Sound
Manages the AudioListenerComponents of an application. Reach it through
app.systems.audiolistener; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: Sound
Represents the raw audio data of a playable sound. A Sound is the resource of an audio Asset. An audio asset can be assigned to a SoundSlot owned by a SoundComponent.
The buffer is the decoded Web Audio AudioBuffer, so duration is known as soon
as the asset has loaded. Playing a sound creates one SoundInstance per playback, normally
through a slot rather than by constructing the instance directly.
new Sound(buffer: AudioBuffer)
Create a new Sound instance.
Parameters
buffer (AudioBuffer): The decoded audio data.buffer: AudioBuffer
Contains the decoded audio data.
get duration(): number
Gets the duration of the sound. If the sound is not loaded it returns 0.
Class · extends Component · category: Sound
The SoundComponent enables an Entity to play audio. The SoundComponent can manage multiple SoundSlots, each of which can play a different audio asset with its own set of properties such as volume, pitch, and looping behavior.
The SoundComponent supports positional audio, meaning that the sound can be played relative to the Entity's position in 3D space. This is useful for creating immersive audio experiences where the sound's volume and panning are affected by the listener's position and orientation. Positional audio requires that an Entity with an AudioListenerComponent be added to the scene.
You should never need to use the SoundComponent constructor directly. To add a SoundComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('sound', {
volume: 0.8,
positional: true
});
Once the SoundComponent is added to the entity, you can access it via the Entity#sound property:
entity.sound.volume = 0.9; // Set the volume for all sounds
console.log(entity.sound.volume); // Get the volume and print it
Add individual sounds by creating sound slots on the component:
entity.sound.addSlot('beep', {
asset: asset
});
Relevant Engine API examples:
get distanceModel(): string
set distanceModel(value: string)
Gets which algorithm to use to reduce the volume of the sound as it moves away from the listener.
get maxDistance(): number
set maxDistance(value: number)
Gets the maximum distance from the listener at which audio falloff stops.
get pitch(): number
set pitch(value: number)
Gets the pitch modifier to play the audio with.
get positional(): boolean
set positional(newValue: boolean)
Gets whether the component plays positional sound.
get refDistance(): number
set refDistance(value: number)
Gets the reference distance for reducing volume as the sound source moves further from the listener.
get rollOffFactor(): number
set rollOffFactor(value: number)
Gets the factor used in the falloff equation.
get slots(): Readonly<Record<string, SoundSlot>>
set slots(newValue: Readonly<Record<string, SoundSlot>>)
Gets a dictionary that contains the SoundSlots managed by this SoundComponent. Use addSlot and removeSlot to change slots.
get volume(): number
set volume(value: number)
Gets the volume modifier to play the audio with.
addSlot(name: string, options?: object): SoundSlot | null
Creates a new SoundSlot with the specified name.
Parameters
name (string): The name of the slot.options (object, optional): Settings for the slot.
options.asset (number, optional): The asset id of the audio asset that is going to be played
by this slot.options.autoPlay (boolean, optional): If true, the slot will start playing as soon as its
audio asset is loaded. Defaults to false.options.duration (number, optional): The duration of the sound that the slot will play
starting from startTime. Defaults to null which means play to end of the sound.options.loop (boolean, optional): If true, the sound will restart when it reaches the end.
Defaults to false.options.overlap (boolean, optional): If true, then sounds played from slot will be played
independently of each other. Otherwise the slot will first stop the current sound before
starting the new one. Defaults to false.options.pitch (number, optional): The relative pitch. Defaults to 1 (plays at normal pitch).options.startTime (number, optional): The start time from which the sound will start playing.
Defaults to 0 to start at the beginning.options.volume (number, optional): The playback volume, between 0 and 1. Defaults to 1.Returns SoundSlot | null: The new slot or null if the slot already exists.
Example
// get an asset by id
const asset = app.assets.get(10);
// add a slot
this.entity.sound.addSlot('beep', {
asset: asset
});
// play
this.entity.sound.play('beep');
isLoaded(name: string): boolean
Returns true if the asset of the slot with the specified name is loaded..
Parameters
name (string): The name of the SoundSlot to look for.Returns boolean: True if the slot with the specified name exists and its asset is loaded.
isPaused(name: string): boolean
Returns true if the slot with the specified name is currently paused.
Parameters
name (string): The name of the SoundSlot to look for.Returns boolean: True if the slot with the specified name exists and is currently paused.
isPlaying(name: string): boolean
Returns true if the slot with the specified name is currently playing.
Parameters
name (string): The name of the SoundSlot to look for.Returns boolean: True if the slot with the specified name exists and is currently playing.
isStopped(name: string): boolean
Returns true if the slot with the specified name is currently stopped.
Parameters
name (string): The name of the SoundSlot to look for.Returns boolean: True if the slot with the specified name exists and is currently stopped.
pause(name?: string): void
Pauses playback of the slot with the specified name. If the name is undefined then all slots currently played will be paused. The slots can be resumed by calling resume.
Parameters
name (string, optional): The name of the slot to pause. Leave undefined to pause everything.Example
// pause all sounds
this.entity.sound.pause();
// pause a specific sound
this.entity.sound.pause('beep');
play(name: string): SoundInstance | null
Begins playing the sound slot with the specified name. The slot will restart playing if it is already playing unless the overlap field is true in which case a new sound will be created and played.
Parameters
name (string): The name of the SoundSlot to play.Returns SoundInstance | null: The sound instance that will be played. Returns null if the
component or its parent entity is disabled or if the SoundComponent has no slot with the
specified name.
Example
// get asset by id
const asset = app.assets.get(10);
// create a slot and play it
this.entity.sound.addSlot('beep', {
asset: asset
});
this.entity.sound.play('beep');
removeSlot(name: string): void
Removes the SoundSlot with the specified name.
Parameters
name (string): The name of the slot.Example
// remove a slot called 'beep'
this.entity.sound.removeSlot('beep');
resume(name?: string): void
Resumes playback of the sound slot with the specified name if it's paused. If no name is specified all slots will be resumed.
Parameters
name (string, optional): The name of the slot to resume. Leave undefined to resume everything.Example
// resume all sounds
this.entity.sound.resume();
// resume a specific sound
this.entity.sound.resume('beep');
slot(name: string): SoundSlot | undefined
Returns the slot with the specified name.
Parameters
name (string): The name of the slot.Returns SoundSlot | undefined: The slot.
Example
// get a slot and set its volume
this.entity.sound.slot('beep').volume = 0.5;
stop(name?: string): void
Stops playback of the sound slot with the specified name if it's paused. If no name is specified all slots will be stopped.
Parameters
name (string, optional): The name of the slot to stop. Leave undefined to stop everything.Example
// stop all sounds
this.entity.sound.stop();
// stop a specific sound
this.entity.sound.stop('beep');
static EVENT_END: string = 'end'
Fired when a sound instance stops playing because it reached its end. The handler is passed the SoundSlot and the SoundInstance that ended.
Example
entity.sound.on('end', (slot, instance) => {
console.log(`Sound ${slot.name} ended`);
});
static EVENT_PAUSE: string = 'pause'
Fired when a sound instance is paused. The handler is passed the SoundSlot and the SoundInstance that was paused.
Example
entity.sound.on('pause', (slot, instance) => {
console.log(`Sound ${slot.name} paused`);
});
static EVENT_PLAY: string = 'play'
Fired when a sound instance starts playing. The handler is passed the SoundSlot and the SoundInstance that started playing.
Example
entity.sound.on('play', (slot, instance) => {
console.log(`Sound ${slot.name} started playing`);
});
static EVENT_RESUME: string = 'resume'
Fired when a sound instance is resumed. The handler is passed the SoundSlot and the SoundInstance that was resumed.
Example
entity.sound.on('resume', (slot, instance) => {
console.log(`Sound ${slot.name} resumed`);
});
static EVENT_STOP: string = 'stop'
Fired when a sound instance is stopped. The handler is passed the SoundSlot and the SoundInstance that was stopped.
Example
entity.sound.on('stop', (slot, instance) => {
console.log(`Sound ${slot.name} stopped`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: Sound
Manages the SoundComponents of an application. Reach it through app.systems.sound;
components are created with Entity#addComponent, never by calling the system directly.
manager: SoundManager
Gets / sets the sound manager.
get context(): AudioContext | null
Gets the AudioContext currently used by the sound manager.
get volume(): number
set volume(volume: number)
Gets the volume for the entire Sound system.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Sound
A SoundInstance plays a Sound.
One instance is one playback. It wraps an AudioBufferSourceNode, available as source
once playing, with a gain for volume, and carries pitch, loop,
startTime and duration to select the region of the sound it plays. play,
pause, resume and stop drive it and fire the events of the same names,
with end fired when playback finishes on its own; isPlaying, isPaused and
isStopped report the state, and currentTime can be read or set to seek.
Instances are normally created by SoundSlot#play on a SoundComponent, which
returns the instance so a script can adjust or stop that one playback. setExternalNodes
inserts Web Audio nodes such as filters between the source and the destination.
Example
const instance = entity.sound.play('engine');
instance.pitch = 1.5;
instance.once('end', () => console.log('finished'));
new SoundInstance(manager: SoundManager, sound: Sound, options: object)
Create a new SoundInstance instance.
Parameters
manager (SoundManager): The sound manager.sound (Sound): The sound to play.options (object): Options for the instance.
options.duration (number, optional): The total time after the startTime in seconds when
playback will stop or restart if loop is true. Defaults to 0.options.loop (boolean, optional): Whether the sound should loop when it reaches the end or
not. Defaults to false.options.onEnd (Function, optional): Function called when the instance ends.options.onPause (Function, optional): Function called when the instance is paused.options.onPlay (Function, optional): Function called when the instance starts playing.options.onResume (Function, optional): Function called when the instance is resumed.options.onStop (Function, optional): Function called when the instance is stopped.options.pitch (number, optional): The relative pitch. Defaults to 1 (plays at normal pitch).options.startTime (number, optional): The time from which the playback will start in
seconds. Default is 0 to start at the beginning. Defaults to 0.options.volume (number, optional): The playback volume, between 0 and 1. Defaults to 1.source: AudioBufferSourceNode | null = null
Gets the source that plays the sound resource. Source is only available after calling play.
get currentTime(): number
set currentTime(value: number)
Gets the current time of the sound that is playing, relative to startTime.
get duration(): number
set duration(value: number)
Gets the duration of the sound that the instance will play starting from startTime. The returned value is clamped to the time available after the normalized start time.
get isPaused(): boolean
Gets whether the instance is currently paused.
get isPlaying(): boolean
Gets whether the instance is currently playing.
get isStopped(): boolean
Gets whether the instance is currently stopped.
get isSuspended(): boolean
Gets whether the instance is currently suspended because the window is not focused.
get loop(): boolean
set loop(value: boolean)
Gets whether the instance will restart when it finishes playing.
get pitch(): number
set pitch(pitch: number)
Gets the pitch modifier to play the sound with.
get sound(): Sound
set sound(value: Sound)
Gets the sound resource that the instance will play.
get startTime(): number
set startTime(value: number)
Gets the start time from which the sound will start playing.
get volume(): number
set volume(volume: number)
Gets the volume modifier to play the sound with. In range 0-1.
clearExternalNodes(): void
Clears any external nodes set by setExternalNodes.
getExternalNodes(): AudioNode[]
Gets any external nodes set by setExternalNodes.
Returns AudioNode[]: Returns an array that contains the two nodes set by
setExternalNodes.
pause(): boolean
Pauses playback of sound. Call resume() to resume playback from the same position.
Returns boolean: Returns true if the sound was paused.
play(): boolean
Attempt to begin playback the sound. If the AudioContext is suspended, the audio will only start once it's resumed. If the sound is already playing, this will restart the sound.
Returns boolean: True if the sound was started immediately.
resume(): boolean
Resumes playback of the sound. Playback resumes at the point that the audio was paused.
Returns boolean: Returns true if the sound was resumed.
setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void
Connects external Web Audio API nodes. You need to pass the first node of the node graph that you created externally and the last node of that graph. The first node will be connected to the audio source and the last node will be connected to the destination of the AudioContext (e.g. speakers). Requires Web Audio API support.
Parameters
firstNode (AudioNode): The first node that will be connected to the audio source of sound instances.lastNode (AudioNode, optional): The last node that will be connected to the destination of the AudioContext.
If unspecified then the firstNode will be connected to the destination instead.Example
const context = app.systems.sound.context;
const analyzer = context.createAnalyzer();
const distortion = context.createWaveShaper();
const filter = context.createBiquadFilter();
analyzer.connect(distortion);
distortion.connect(filter);
instance.setExternalNodes(analyzer, filter);
stop(): boolean
Stops playback of sound. Calling play() again will restart playback from the beginning of the sound.
Returns boolean: Returns true if the sound was stopped.
static EVENT_END: string = 'end'
Fired when the sound currently played by the instance ends.
Example
instance.on('end', () => {
console.log('Instance ended');
});
static EVENT_PAUSE: string = 'pause'
Fired when the instance is paused.
Example
instance.on('pause', () => {
console.log('Instance paused');
});
static EVENT_PLAY: string = 'play'
Fired when the instance starts playing its source.
Example
instance.on('play', () => {
console.log('Instance started playing');
});
static EVENT_RESUME: string = 'resume'
Fired when the instance is resumed.
Example
instance.on('resume', () => {
console.log('Instance resumed');
});
static EVENT_STOP: string = 'stop'
Fired when the instance is stopped.
Example
instance.on('stop', () => {
console.log('Instance stopped');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends SoundInstance · category: Sound
A SoundInstance3d plays a Sound in 3D.
It is what a positional SoundComponent creates. The sound is placed at position and its volume falls off with distance from the AudioListenerComponent according to distanceModel, one of DISTANCE_LINEAR, DISTANCE_INVERSE and DISTANCE_EXPONENTIAL, shaped by refDistance, maxDistance and rollOffFactor. The owning slot keeps position in step with its entity, so these properties are usually set on the component rather than on each instance.
new SoundInstance3d(manager: SoundManager, sound: Sound, options?: object)
Create a new SoundInstance3d instance.
Parameters
manager (SoundManager): The sound manager.sound (Sound): The sound to play.options (object, optional, default {}): Options for the instance.
options.distanceModel (string, optional): Determines which algorithm to use to reduce the
volume of the audio as it moves away from the listener. Can be:
Defaults to DISTANCE_LINEAR.
options.duration (number, optional): The total time after the startTime when playback will
stop or restart if loop is true.
options.loop (boolean, optional): Whether the sound should loop when it reaches the end or
not. Defaults to false.
options.maxDistance (number, optional): The maximum distance from the listener at which
audio falloff stops. Note the volume of the audio is not 0 after this distance, but just
doesn't fall off anymore. Defaults to 10000.
options.pitch (number, optional): The relative pitch. Defaults to 1 (plays at normal pitch).
options.position (Vec3, optional): The position of the sound in 3D space.
options.refDistance (number, optional): The reference distance for reducing volume as the
sound source moves further from the listener. Defaults to 1.
options.rollOffFactor (number, optional): The factor used in the falloff equation. Defaults
to 1.
options.startTime (number, optional): The time from which the playback will start. Default
is 0 to start at the beginning.
options.volume (number, optional): The playback volume, between 0 and 1. Defaults to 1.
get distanceModel(): string
set distanceModel(value: string)
Gets which algorithm to use to reduce the volume of the audio as it moves away from the listener.
get maxDistance(): number
set maxDistance(value: number)
Gets the maximum distance from the listener at which audio falloff stops.
get position(): Vec3
set position(value: Vec3)
Gets the position of the sound in 3D space.
get refDistance(): number
set refDistance(value: number)
Gets the reference distance for reducing volume as the sound source moves further from the listener.
get rollOffFactor(): number
set rollOffFactor(value: number)
Gets the factor used in the falloff equation.
source: AudioBufferSourceNode | null = nullget currentTime(): number · set currentTime(value: number)get duration(): number · set duration(value: number)get isPaused(): booleanget isPlaying(): booleanget isStopped(): booleanget isSuspended(): booleanget loop(): boolean · set loop(value: boolean)get pitch(): number · set pitch(pitch: number)get sound(): Sound · set sound(value: Sound)get startTime(): number · set startTime(value: number)get volume(): number · set volume(volume: number)clearExternalNodes(): voidfire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlergetExternalNodes(): AudioNode[]hasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandlepause(): booleanplay(): booleanresume(): booleansetExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): voidstop(): booleanstatic EVENT_END: string = 'end'static EVENT_PAUSE: string = 'pause'static EVENT_PLAY: string = 'play'static EVENT_RESUME: string = 'resume'static EVENT_STOP: string = 'stop'Class · extends EventHandler · category: Sound
The SoundManager is used to load and play audio. It also applies system-wide settings like global volume, suspend and resume.
There is one per application at app.soundManager. It owns the Web Audio context that
every SoundInstance plays through and the listener from which positional sounds are
heard, applies the master volume on top of each instance's own, and suspend and
resume silence and restart all audio at once, for example when the page loses focus.
new SoundManager()
Create a new SoundManager instance.
listener: Listener
The listener associated with this manager.
get volume(): number
set volume(volume: number)
Gets the global volume for the manager.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: Sound
The SoundSlot controls the playback of SoundInstances. SoundSlots are managed by SoundComponents. To add and remove SoundSlots on a SoundComponent, use SoundComponent#addSlot and SoundComponent#removeSlot respectively.
A slot holds one audio asset and the settings applied to every instance it creates:
volume, pitch, loop, startTime and duration, plus
autoPlay to start as soon as the asset has loaded and overlap to let several
instances play at once instead of stopping the previous one. play returns the new
SoundInstance and instances lists those currently playing. The slot forwards the
instances' play, pause, resume, stop and end events and fires load when its asset
is ready.
Example
const slot = entity.sound.slot('footsteps');
slot.overlap = true; // let quick steps overlap rather than cut each other off
slot.volume = 0.6;
slot.play();
@hideconstructor
instances: SoundInstance[] = []
An array that contains all the SoundInstances currently being played by the slot.
name: string
The name of the slot.
get asset(): number | null
set asset(value: number | null)
Gets the asset id.
get autoPlay(): boolean
set autoPlay(value: boolean)
Gets whether the slot will begin playing as soon as it is loaded.
get duration(): number
set duration(value: number)
Gets the duration of the sound that the slot will play starting from startTime. The returned value is clamped to the time available after the normalized start time.
get isLoaded(): boolean
Gets whether the asset of the slot is loaded.
get isPaused(): boolean
Gets whether the slot is currently paused.
get isPlaying(): boolean
Gets whether the slot is currently playing.
get isStopped(): boolean
Gets whether the slot is currently stopped.
get loop(): boolean
set loop(value: boolean)
Gets whether the slot will restart when it finishes playing.
get overlap(): boolean
set overlap(value: boolean)
Gets whether the sounds played from this slot will be played independently of each other.
get pitch(): number
set pitch(value: number)
Gets the pitch modifier to play the sound with.
get startTime(): number
set startTime(value: number)
Gets the start time from which the sound will start playing.
get volume(): number
set volume(value: number)
Gets the volume modifier to play the sound with.
clearExternalNodes(): void
Clears any external nodes set by setExternalNodes.
getExternalNodes(): AudioNode[]
Gets an array that contains the two external nodes set by setExternalNodes.
Returns AudioNode[]: An array of 2 elements that contains the first and last nodes set by
setExternalNodes.
load(): void
Loads the asset assigned to this slot.
pause(): boolean
Pauses all sound instances. To continue playback call resume.
Returns boolean: True if the sound instances paused successfully, false otherwise.
play(): SoundInstance
Plays a sound. If overlap is true the new sound instance will be played independently of any other instances already playing. Otherwise existing sound instances will stop before playing the new sound.
Returns SoundInstance: The new sound instance.
resume(): boolean
Resumes playback of all paused sound instances.
Returns boolean: True if any instances were resumed.
setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void
Connect external Web Audio API nodes. Any sound played by this slot will automatically attach the specified nodes to the source that plays the sound. You need to pass the first node of the node graph that you created externally and the last node of that graph. The first node will be connected to the audio source and the last node will be connected to the destination of the AudioContext (e.g. speakers).
Parameters
firstNode (AudioNode): The first node that will be connected to the audio source of
sound instances.lastNode (AudioNode, optional): The last node that will be connected to the destination of
the AudioContext. If unspecified then the firstNode will be connected to the destination
instead.Example
const context = app.systems.sound.context;
const analyzer = context.createAnalyzer();
const distortion = context.createWaveShaper();
const filter = context.createBiquadFilter();
analyzer.connect(distortion);
distortion.connect(filter);
slot.setExternalNodes(analyzer, filter);
stop(): boolean
Stops playback of all sound instances.
Returns boolean: True if any instances were stopped.
static EVENT_END: string = 'end'
Fired when a sound instance stops playing because it reached its end. The handler is passed the SoundInstance that ended.
Example
slot.on('end', (instance) => {
console.log('Sound instance playback ended');
});
static EVENT_LOAD: string = 'load'
Fired when the sound Asset assigned to the slot is loaded. The handler is passed the loaded Sound resource.
Example
slot.on('load', (sound) => {
console.log('Sound resource loaded');
});
static EVENT_PAUSE: string = 'pause'
Fired when a SoundInstance is paused on a slot. The handler is passed the sound instance that is paused.
Example
slot.on('pause', (instance) => {
console.log('Sound instance paused');
});
static EVENT_PLAY: string = 'play'
Fired when a SoundInstance starts playing on a slot. The handler is passed the sound instance that started playing.
Example
slot.on('play', (instance) => {
console.log('Sound instance started playing');
});
static EVENT_RESUME: string = 'resume'
Fired when a SoundInstance is resumed on a slot. The handler is passed the sound instance that is resumed.
Example
slot.on('resume', (instance) => {
console.log('Sound instance resumed');
});
static EVENT_STOP: string = 'stop'
Fired when a SoundInstance is stopped on a slot. The handler is passed the sound instance that is stopped.
Example
slot.on('stop', (instance) => {
console.log('Sound instance stopped');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
The ButtonComponent enables an Entity to behave like a button, with different visual states for hover and press interactions. It is designed to be used together with an ElementComponent on the same entity, which provides the button's visual appearance and input hit area. Set imageEntity, usually to the button's own entity, to choose the element that is tinted, or has its sprite changed, for each visual state.
You should never need to use the ButtonComponent constructor directly. To add a ButtonComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('element', {
type: ELEMENTTYPE_IMAGE,
useInput: true
});
entity.addComponent('button', {
imageEntity: entity
});
Once the ButtonComponent is added to the entity, you can access it via the Entity#button property:
entity.button.hoverTint = Color.YELLOW; // Set the hover tint color
console.log(entity.button.hoverTint); // Get the hover tint color and print it
Relevant Engine API examples:
get active(): boolean
set active(arg: boolean)
Gets the button's active state.
get fadeDuration(): number
set fadeDuration(arg: number)
Gets the duration to be used when fading between tints, in milliseconds.
get hitPadding(): Vec4
set hitPadding(arg: Vec4)
Gets the padding to be used in hit-test calculations.
get hoverSpriteAsset(): Asset<string> | null
set hoverSpriteAsset(arg: Asset<string> | null)
Gets the sprite to be used as the button image when the user hovers over it.
get hoverSpriteFrame(): number
set hoverSpriteFrame(arg: number)
Gets the frame to be used from the hover sprite.
get hoverTint(): Color
set hoverTint(arg: Color)
Gets the tint color to be used on the button image when the user hovers over it.
get imageEntity(): Entity | null
set imageEntity(arg: Entity | null)
Gets the entity to be used as the button background.
get inactiveSpriteAsset(): Asset<string> | null
set inactiveSpriteAsset(arg: Asset<string> | null)
Gets the sprite to be used as the button image when the button is not interactive.
get inactiveSpriteFrame(): number
set inactiveSpriteFrame(arg: number)
Gets the frame to be used from the inactive sprite.
get inactiveTint(): Color
set inactiveTint(arg: Color)
Gets the tint color to be used on the button image when the button is not interactive.
get pressedSpriteAsset(): Asset<string> | null
set pressedSpriteAsset(arg: Asset<string> | null)
Gets the sprite to be used as the button image when the user presses it.
get pressedSpriteFrame(): number
set pressedSpriteFrame(arg: number)
Gets the frame to be used from the pressed sprite.
get pressedTint(): Color
set pressedTint(arg: Color)
Gets the tint color to be used on the button image when the user presses it.
get transitionMode(): number
set transitionMode(arg: number)
Gets the button transition mode.
static EVENT_CLICK: string = 'click'
Fired when the mouse is pressed and released on the component or when a touch starts and ends on the component. The handler is passed a ElementMouseEvent or ElementTouchEvent.
Example
entity.button.on('click', (event) => {
console.log(`Clicked entity ${entity.name}`);
});
static EVENT_HOVEREND: string = 'hoverend'
Fired when the button changes state to be not hovered.
Example
entity.button.on('hoverend', () => {
console.log(`Entity ${entity.name} unhovered`);
});
static EVENT_HOVERSTART: string = 'hoverstart'
Fired when the button changes state to be hovered.
Example
entity.button.on('hoverstart', () => {
console.log(`Entity ${entity.name} hovered`);
});
static EVENT_MOUSEDOWN: string = 'mousedown'
Fired when the mouse is pressed while the cursor is on the component. The handler is passed a ElementMouseEvent.
Example
entity.button.on('mousedown', (event) => {
console.log(`Mouse down on entity ${entity.name}`);
});
static EVENT_MOUSEENTER: string = 'mouseenter'
Fired when the mouse cursor enters the component. The handler is passed a ElementMouseEvent.
Example
entity.button.on('mouseenter', (event) => {
console.log(`Mouse entered entity ${entity.name}`);
});
static EVENT_MOUSELEAVE: string = 'mouseleave'
Fired when the mouse cursor leaves the component. The handler is passed a ElementMouseEvent.
Example
entity.button.on('mouseleave', (event) => {
console.log(`Mouse left entity ${entity.name}`);
});
static EVENT_MOUSEUP: string = 'mouseup'
Fired when the mouse is released while the cursor is on the component. The handler is passed a ElementMouseEvent.
Example
entity.button.on('mouseup', (event) => {
console.log(`Mouse up on entity ${entity.name}`);
});
static EVENT_PRESSEDEND: string = 'pressedend'
Fired when the button changes state to be not pressed.
Example
entity.button.on('pressedend', () => {
console.log(`Entity ${entity.name} unpressed`);
});
static EVENT_PRESSEDSTART: string = 'pressedstart'
Fired when the button changes state to be pressed.
Example
entity.button.on('pressedstart', () => {
console.log(`Entity ${entity.name} pressed`);
});
static EVENT_SELECTEND: string = 'selectend'
Fired when a xr select ends on the component. The handler is passed a ElementSelectEvent.
Example
entity.button.on('selectend', (event) => {
console.log(`Select ended on entity ${entity.name}`);
});
static EVENT_SELECTENTER: string = 'selectenter'
Fired when a xr select now hovering over the component. The handler is passed a ElementSelectEvent.
Example
entity.button.on('selectenter', (event) => {
console.log(`Select entered entity ${entity.name}`);
});
static EVENT_SELECTLEAVE: string = 'selectleave'
Fired when a xr select not hovering over the component. The handler is passed a ElementSelectEvent.
Example
entity.button.on('selectleave', (event) => {
console.log(`Select left entity ${entity.name}`);
});
static EVENT_SELECTSTART: string = 'selectstart'
Fired when a xr select starts on the component. The handler is passed a ElementSelectEvent.
Example
entity.button.on('selectstart', (event) => {
console.log(`Select started on entity ${entity.name}`);
});
static EVENT_TOUCHCANCEL: string = 'touchcancel'
Fired when a touch is canceled on the component. The handler is passed a ElementTouchEvent.
Example
entity.button.on('touchcancel', (event) => {
console.log(`Touch canceled on entity ${entity.name}`);
});
static EVENT_TOUCHEND: string = 'touchend'
Fired when a touch ends on the component. The handler is passed a ElementTouchEvent.
Example
entity.button.on('touchend', (event) => {
console.log(`Touch ended on entity ${entity.name}`);
});
static EVENT_TOUCHLEAVE: string = 'touchleave'
Fired when a touch leaves the component. The handler is passed a ElementTouchEvent.
Example
entity.button.on('touchleave', (event) => {
console.log(`Touch left entity ${entity.name}`);
});
static EVENT_TOUCHSTART: string = 'touchstart'
Fired when a touch starts on the component. The handler is passed a ElementTouchEvent.
Example
entity.button.on('touchstart', (event) => {
console.log(`Touch started on entity ${entity.name}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the ButtonComponents of an application. Reach it through app.systems.button;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
ElementComponents are used to construct user interfaces. The type property can be configured in 3 main ways: as a text element, as an image element or as a group element. If the ElementComponent has a ScreenComponent ancestor in the hierarchy, it will be transformed with respect to the coordinate system of the screen. If there is no ScreenComponent ancestor, the ElementComponent will be transformed like any other entity.
You should never need to use the ElementComponent constructor directly. To add an ElementComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('element'); // This defaults to a 'group' element
To create a simple text-based element:
entity.addComponent('element', {
anchor: new Vec4(0.5, 0.5, 0.5, 0.5), // centered anchor
fontAsset: fontAsset,
fontSize: 128,
pivot: new Vec2(0.5, 0.5), // centered pivot
text: 'Hello World!',
type: ELEMENTTYPE_TEXT
});
Once the ElementComponent is added to the entity, you can access it via the Entity#element property:
entity.element.color = Color.RED; // Set the element's color to red
console.log(entity.element.color); // Get the element's color and print it
Relevant Engine API examples:
screen: Entity | null
The Entity with a ScreenComponent that this component belongs to. This is automatically set when the component is a child of a ScreenComponent.
get aabb(): BoundingBox | null
Gets the world space axis-aligned bounding box for this element component.
get alignment(): Vec2
set alignment(arg: Vec2)
Gets the horizontal and vertical alignment of the text.
get anchor(): Readonly<Vec4>
set anchor(value: Readonly<Vec4>)
Gets the anchor for this element component. Use the setter to update the anchor.
get autoFitHeight(): boolean
set autoFitHeight(arg: boolean)
Gets whether the font size and line height will scale so that the text fits inside the height of the Element.
get autoFitWidth(): boolean
set autoFitWidth(arg: boolean)
Gets whether the font size and line height will scale so that the text fits inside the width of the Element.
get autoHeight(): boolean
set autoHeight(arg: boolean)
Gets whether to automatically set the height of the component to be the same as the textHeight.
get autoWidth(): boolean
set autoWidth(arg: boolean)
Gets whether to automatically set the width of the component to be the same as the textWidth.
get batchGroupId(): number
set batchGroupId(value: number)
Gets the batch group (see BatchGroup) for this element.
get bottom(): number
set bottom(value: number)
Gets the distance from the bottom edge of the anchor.
get calculatedHeight(): number
set calculatedHeight(value: number)
Gets the height at which the element will be rendered.
get calculatedWidth(): number
set calculatedWidth(value: number)
Gets the width at which the element will be rendered.
get canvasCorners(): Vec2[]
Gets the array of 4 Vec2s that represent the bottom left, bottom right, top right and top left corners of the component in canvas pixels. Only works for screen space element components.
get color(): Readonly<Color>
set color(arg: Readonly<Color>)
Gets the color of the element. Use the setter to update the color.
get drawOrder(): number
set drawOrder(value: number)
Gets the draw order of the component.
get enableMarkup(): boolean
set enableMarkup(arg: boolean)
Gets whether markup processing is enabled for this element.
get fitMode(): string
set fitMode(value: string)
Gets the fit mode of the element.
get font(): Font | CanvasFont
set font(arg: Font | CanvasFont)
Gets the font used for rendering the text.
get fontAsset(): number | Asset<string> | null
set fontAsset(arg: number | Asset<string> | null)
Gets the id of the font asset used for rendering the text.
get fontSize(): number
set fontSize(arg: number)
Gets the size of the font.
get height(): number
set height(value: number)
Gets the height of the element.
get justify(): boolean
set justify(arg: boolean)
Gets whether wrapped lines are stretched to be flush with both edges of the element.
get key(): string
set key(arg: string)
Gets the localization key to use to get the localized text from Application#i18n.
get layers(): readonly number[]
set layers(value: readonly number[])
Gets the array of layer IDs (Layer#id) to which this element belongs.
get left(): number
set left(value: number)
Gets the distance from the left edge of the anchor.
get lineHeight(): number
set lineHeight(arg: number)
Gets the height of each line of text.
get lines(): string[]
Gets the lines of rendered text, split by line breaks and word wrapping. Only works for
ELEMENTTYPE_TEXT elements, and is populated when the text is laid out, so it reads as
undefined until the first update.
get margin(): Readonly<Vec4>
set margin(value: Readonly<Vec4>)
Gets the distance from the left, bottom, right and top edges of the anchor. Use the setter to update the margin.
get mask(): boolean
set mask(arg: boolean)
Gets whether the Image Element should be treated as a mask.
get material(): Material
set material(arg: Material)
Gets the material to use when rendering an image.
get materialAsset(): number | Asset<string> | null
set materialAsset(arg: number | Asset<string> | null)
Gets the id of the material asset to use when rendering an image.
get maxFontSize(): number
set maxFontSize(arg: number)
Gets the maximum size that the font can scale to when autoFitWidth or autoFitHeight are true.
get maxLines(): number | null
set maxLines(arg: number | null)
Gets the maximum number of lines that the Element can wrap to. Returns -1 if there is no limit.
get minFontSize(): number
set minFontSize(arg: number)
Gets the minimum size that the font can scale to when autoFitWidth or autoFitHeight are true.
get opacity(): number
set opacity(arg: number)
Gets the opacity of the element.
get outlineColor(): Color
set outlineColor(arg: Color)
Gets the text outline effect color and opacity.
get outlineThickness(): number
set outlineThickness(arg: number)
Gets the width of the text outline effect.
get pivot(): Readonly<Vec2>
set pivot(value: Readonly<Vec2>)
Gets the position of the pivot of the component relative to its anchor. Use the setter to update the pivot.
get pixelsPerUnit(): number | null
set pixelsPerUnit(arg: number | null)
Gets the number of pixels that map to one PlayCanvas unit.
get rangeEnd(): number
set rangeEnd(arg: number)
Gets the index of the last character to render.
get rangeStart(): number
set rangeStart(arg: number)
Gets the index of the first character to render.
get rect(): Readonly<Vec4> | null
set rect(arg: Readonly<Vec4> | null)
Gets the region of the texture to use in order to render an image. Use the setter to update the region.
get right(): number
set right(value: number)
Gets the distance from the right edge of the anchor.
get rtlReorder(): boolean
set rtlReorder(arg: boolean)
Gets whether to reorder the text for RTL languages.
get screenCorners(): Vec3[]
Gets the array of 4 Vec3s that represent the bottom left, bottom right, top right and top left corners of the component relative to its parent ScreenComponent.
get shadowColor(): Color
set shadowColor(arg: Color)
Gets the text shadow effect color and opacity.
get shadowOffset(): Vec2
set shadowOffset(arg: Vec2)
Gets the offset of the text shadow, relative to the text.
get spacing(): number
set spacing(arg: number)
Gets the spacing between the letters of the text.
get sprite(): Sprite
set sprite(arg: Sprite)
Gets the sprite to render.
get spriteAsset(): number | Asset<string> | null
set spriteAsset(arg: number | Asset<string> | null)
Gets the id of the sprite asset to render.
get spriteFrame(): number
set spriteFrame(arg: number)
Gets the frame of the sprite to render.
get text(): string
set text(arg: string)
Gets the text to render.
get textHeight(): number
Gets the height of the text rendered by the component. Only works for ELEMENTTYPE_TEXT elements.
get texture(): Texture
set texture(arg: Texture)
Gets the texture to render.
get textureAsset(): number | Asset<string> | null
set textureAsset(arg: number | Asset<string> | null)
Gets the id of the texture asset to render.
get textWidth(): number
Gets the width of the text rendered by the component. Only works for ELEMENTTYPE_TEXT elements.
get top(): number
set top(value: number)
Gets the distance from the top edge of the anchor.
get type(): string
set type(value: string)
Gets the type of the ElementComponent.
get unicodeConverter(): boolean
set unicodeConverter(arg: boolean)
Gets whether to convert unicode characters.
get useInput(): boolean
set useInput(value: boolean)
Gets whether the component will receive mouse and touch input events.
get width(): number
set width(value: number)
Gets the width of the element.
get worldCorners(): Vec3[]
Gets the array of 4 Vec3s that represent the bottom left, bottom right, top right and top left corners of the component in world space. Only works for 3D element components.
get wrapLines(): boolean
set wrapLines(arg: boolean)
Gets whether to automatically wrap lines based on the element width.
static EVENT_CLICK: string = 'click'
Fired when the mouse is pressed and released on the component, when a touch starts and ends on the component, or when an XR input source starts and ends a select action on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent, ElementTouchEvent or ElementSelectEvent.
Example
entity.element.on('click', (event) => {
console.log(`Click event on entity ${entity.name}`);
});
static EVENT_MOUSEDOWN: string = 'mousedown'
Fired when the mouse is pressed while the cursor is on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mousedown', (event) => {
console.log(`Mouse down event on entity ${entity.name}`);
});
static EVENT_MOUSEENTER: string = 'mouseenter'
Fired when the mouse cursor enters the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mouseenter', (event) => {
console.log(`Mouse enter event on entity ${entity.name}`);
});
static EVENT_MOUSELEAVE: string = 'mouseleave'
Fired when the mouse cursor leaves the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mouseleave', (event) => {
console.log(`Mouse leave event on entity ${entity.name}`);
});
static EVENT_MOUSEMOVE: string = 'mousemove'
Fired when the mouse cursor is moved on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mousemove', (event) => {
console.log(`Mouse move event on entity ${entity.name}`);
});
static EVENT_MOUSEUP: string = 'mouseup'
Fired when the mouse is released while the cursor is on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mouseup', (event) => {
console.log(`Mouse up event on entity ${entity.name}`);
});
static EVENT_MOUSEWHEEL: string = 'mousewheel'
Fired when the mouse wheel is scrolled on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.
Example
entity.element.on('mousewheel', (event) => {
console.log(`Mouse wheel event on entity ${entity.name}`);
});
static EVENT_SELECTEND: string = 'selectend'
Fired when an XR input source ends a select action that started on the component, even if its ray no longer points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.
Example
entity.element.on('selectend', (event) => {
console.log(`Select end event on entity ${entity.name}`);
});
static EVENT_SELECTENTER: string = 'selectenter'
Fired when the ray of an XR input source starts pointing at the component. Only fired when useInput is true and the input source's XrInputSource#elementInput is true. The handler is passed an ElementSelectEvent.
Example
entity.element.on('selectenter', (event) => {
console.log(`Select enter event on entity ${entity.name}`);
});
static EVENT_SELECTLEAVE: string = 'selectleave'
Fired when the ray of an XR input source stops pointing at the component, or when the input source is removed while its ray points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.
Example
entity.element.on('selectleave', (event) => {
console.log(`Select leave event on entity ${entity.name}`);
});
static EVENT_SELECTMOVE: string = 'selectmove'
Fired every XR frame while an XR input source holds a select action that started on the component, even if its ray no longer points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.
Example
entity.element.on('selectmove', (event) => {
console.log(`Select move event on entity ${entity.name}`);
});
static EVENT_SELECTSTART: string = 'selectstart'
Fired when an XR input source starts a select action, such as pulling a controller trigger or pinching, while its ray points at the component. Only fired when useInput is true and the input source's XrInputSource#elementInput is true. The handler is passed an ElementSelectEvent.
Example
entity.element.on('selectstart', (event) => {
console.log(`Select start event on entity ${entity.name}`);
});
static EVENT_TOUCHCANCEL: string = 'touchcancel'
Fired when a touch is canceled on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.
Example
entity.element.on('touchcancel', (event) => {
console.log(`Touch cancel event on entity ${entity.name}`);
});
static EVENT_TOUCHEND: string = 'touchend'
Fired when a touch ends on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.
Example
entity.element.on('touchend', (event) => {
console.log(`Touch end event on entity ${entity.name}`);
});
static EVENT_TOUCHMOVE: string = 'touchmove'
Fired when a touch moves after it started touching the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.
Example
entity.element.on('touchmove', (event) => {
console.log(`Touch move event on entity ${entity.name}`);
});
static EVENT_TOUCHSTART: string = 'touchstart'
Fired when a touch starts on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.
Example
entity.element.on('touchstart', (event) => {
console.log(`Touch start event on entity ${entity.name}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the ElementComponents of an application. Reach it through app.systems.element;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: User Interface
Helper class that makes it easy to create Elements that can be dragged by the mouse or touch.
Relevant Engine API examples:
new ElementDragHelper(element: ElementComponent, axis?: string)
Create a new ElementDragHelper instance.
Parameters
element (ElementComponent): The Element that should become draggable.axis (string, optional): Optional axis to constrain to, either 'x', 'y' or null.static EVENT_DRAGEND: string = 'drag:end'
Fired when the current new drag operation ends.
Example
elementDragHelper.on('drag:end', () => {
console.log('Drag ended');
});
static EVENT_DRAGMOVE: string = 'drag:move'
Fired whenever the position of the dragged element changes. The handler is passed the current Vec3 position of the dragged element.
Example
elementDragHelper.on('drag:move', (position) => {
console.log(`Dragged element position is ${position}`);
});
static EVENT_DRAGSTART: string = 'drag:start'
Fired when a new drag operation starts.
Example
elementDragHelper.on('drag:start', () => {
console.log('Drag started');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: User Interface
Handles mouse and touch events for ElementComponents. When input events occur on an ElementComponent this fires the appropriate events on the ElementComponent.
Relevant Engine API examples:
new ElementInput(domElement: Element, options?: object)
Create a new ElementInput instance.
Parameters
domElement (Element): The DOM element.options (object, optional): Optional arguments.
options.useMouse (boolean, optional): Whether to allow mouse input. Defaults to true.options.useTouch (boolean, optional): Whether to allow touch input. Defaults to true.options.useXr (boolean, optional): Whether to allow XR input sources. Defaults to true.addElement(element: ElementComponent): void
Add a ElementComponent to the internal list of ElementComponents that are being checked for input.
Parameters
element (ElementComponent): The
ElementComponent.attach(domElement: Element): void
Attach mouse and touch events to a DOM element.
Parameters
domElement (Element): The DOM element.detach(): void
Remove mouse and touch events from the DOM element that it is attached to.
removeElement(element: ElementComponent): void
Remove a ElementComponent from the internal list of ElementComponents that are being checked for input.
Parameters
element (ElementComponent): The
ElementComponent.Class · category: User Interface
Represents an input event fired on a ElementComponent. When an event is raised on an ElementComponent it bubbles up to its parent ElementComponents unless we call stopPropagation().
new ElementInputEvent(event: MouseEvent | TouchEvent | XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent)
Create a new ElementInputEvent instance.
Parameters
event (MouseEvent | TouchEvent | XRInputSourceEvent | null): The
browser event that was originally raised, or null if there was none.element (ElementComponent): The ElementComponent that this event was originally
raised on.camera (CameraComponent): The CameraComponent that this event was originally raised
via.camera: CameraComponent
The CameraComponent that this event was originally raised via.
element: ElementComponent
The ElementComponent that this event was originally raised on.
event: MouseEvent | TouchEvent | XRInputSourceEvent | null
The browser event that was originally raised: a MouseEvent, TouchEvent or
XRInputSourceEvent. It is null when no browser event caused this one, as for
selectmove.
stopPropagation(): void
Stop propagation of the event to parent ElementComponents. This also stops propagation of the event to other event listeners of the original DOM Event.
Class · extends ElementInputEvent · category: User Interface
Represents a Mouse event fired on a ElementComponent.
new ElementMouseEvent(event: MouseEvent | WheelEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, lastX: number, lastY: number)
Create an instance of an ElementMouseEvent.
Parameters
event (MouseEvent | WheelEvent): The browser MouseEvent or
WheelEvent that was originally raised.element (ElementComponent): The
ElementComponent that this event was originally raised on.camera (CameraComponent): The
CameraComponent that this event was originally raised via.x (number): The x coordinate.y (number): The y coordinate.lastX (number): The last x coordinate.lastY (number): The last y coordinate.altKey: boolean
Whether the alt key was pressed.
button: number
The mouse button.
ctrlKey: boolean
Whether the ctrl key was pressed.
dx: number
The amount of horizontal movement of the cursor.
dy: number
The amount of vertical movement of the cursor.
metaKey: boolean
Whether the meta key was pressed.
shiftKey: boolean
Whether the shift key was pressed.
wheelDelta: number
The amount of the wheel movement.
camera: CameraComponentelement: ElementComponentevent: MouseEvent | TouchEvent | XRInputSourceEvent | nullstopPropagation(): voidClass · extends ElementInputEvent · category: User Interface
Represents a XRInputSourceEvent fired on a ElementComponent.
new ElementSelectEvent(event: XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent, inputSource: XrInputSource)
Create an instance of an ElementSelectEvent.
Parameters
event (XRInputSourceEvent | null): The XRInputSourceEvent that was originally raised,
or null if there was none.element (ElementComponent): The
ElementComponent that this event was originally raised on.camera (CameraComponent): The
CameraComponent that this event was originally raised via.inputSource (XrInputSource): The XR input source
that this event was originally raised from.inputSource: XrInputSource
The XR input source that this event was originally raised from.
camera: CameraComponentelement: ElementComponentevent: MouseEvent | TouchEvent | XRInputSourceEvent | nullstopPropagation(): voidClass · extends ElementInputEvent · category: User Interface
Represents a TouchEvent fired on a ElementComponent. It carries the browser's own TouchEvent and Touch objects.
new ElementTouchEvent(event: TouchEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, touch: Touch)
Create an instance of an ElementTouchEvent.
Parameters
event (TouchEvent): The browser TouchEvent that was originally raised.element (ElementComponent): The
ElementComponent that this event was originally raised on.camera (CameraComponent): The
CameraComponent that this event was originally raised via.x (number): The x coordinate of the touch that triggered the event.y (number): The y coordinate of the touch that triggered the event.touch (Touch): The browser Touch that triggered the event.changedTouches: TouchList
The Touch objects representing individual points of contact whose states changed between the previous touch event and this one.
touch: Touch
The browser Touch that triggered the event. Match a touch across events by its
identifier.
touches: TouchList
The Touch objects representing all current points of contact with the surface, regardless of target or changed status.
camera: CameraComponentelement: ElementComponentevent: MouseEvent | TouchEvent | XRInputSourceEvent | nullstopPropagation(): voidClass · category: User Interface
Represents the resource of a font asset.
new Font(textures: Texture[], data: any)
Create a new Font instance.
Parameters
textures (Texture[]): The font textures.data (any): The font data.intensity: number
The font intensity.
textures: Texture[]
The font textures.
destroy(): void
Frees the GPU textures owned by the font and removes them from the resource loader cache. Called automatically when the owning font asset is unloaded (see Asset#unload).
Class · extends Component · category: User Interface
The LayoutChildComponent enables an Entity to control the sizing and fitting behavior applied to it by its parent LayoutGroupComponent. It allows per-child overrides of minimum and maximum dimensions as well as fit proportions.
You should never need to use the LayoutChildComponent constructor directly. To add a LayoutChildComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('element', {
type: ELEMENTTYPE_IMAGE
});
entity.addComponent('layoutchild', {
minWidth: 50,
maxWidth: 200,
fitWidthProportion: 1
});
Once the LayoutChildComponent is added to the entity, you can access it via the Entity#layoutchild property:
entity.layoutchild.minWidth = 80; // Increase the minimum width
console.log(entity.layoutchild.minWidth); // Get the minimum width and print it
get excludeFromLayout(): boolean
set excludeFromLayout(value: boolean)
Gets whether the child will be excluded from all layout calculations.
get fitHeightProportion(): number
set fitHeightProportion(value: number)
Gets the amount of additional vertical space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation.
get fitWidthProportion(): number
set fitWidthProportion(value: number)
Gets the amount of additional horizontal space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation.
get maxHeight(): number | null
set maxHeight(value: number | null)
Gets the maximum height the element should be rendered at.
get maxWidth(): number | null
set maxWidth(value: number | null)
Gets the maximum width the element should be rendered at.
get minHeight(): number
set minHeight(value: number)
Gets the minimum height the element should be rendered at.
get minWidth(): number
set minWidth(value: number)
Gets the minimum width the element should be rendered at.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the LayoutChildComponents of an application. Reach it through
app.systems.layoutchild; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
The LayoutGroupComponent enables an Entity to position and scale its child ElementComponents according to configurable layout rules. It supports horizontal and vertical orientations and a variety of alignment, spacing, wrapping and sizing options.
You should never need to use the LayoutGroupComponent constructor directly. To add a LayoutGroupComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('element', {
type: ELEMENTTYPE_GROUP
});
entity.addComponent('layoutgroup', {
orientation: ORIENTATION_HORIZONTAL,
spacing: new Vec2(10, 0)
});
Once the LayoutGroupComponent is added to the entity, you can access it via the Entity#layoutgroup property:
entity.layoutgroup.spacing = new Vec2(20, 0); // Increase spacing between children
console.log(entity.layoutgroup.spacing); // Get the spacing and print it
Relevant Engine API examples:
get alignment(): Vec2
set alignment(value: Vec2)
Gets the horizontal and vertical alignment of child elements.
get heightFitting(): number
set heightFitting(value: number)
Gets the height fitting mode to be applied when positioning and scaling child elements.
get orientation(): number
set orientation(value: number)
Gets whether the layout should run horizontally or vertically.
get padding(): Vec4
set padding(value: Vec4)
Gets the padding to be applied inside the container before positioning any children.
get reverseX(): boolean
set reverseX(value: boolean)
Gets whether to reverse the order of children along the x axis.
get reverseY(): boolean
set reverseY(value: boolean)
Gets whether to reverse the order of children along the y axis.
get spacing(): Vec2
set spacing(value: Vec2)
Gets the spacing to be applied between each child element.
get widthFitting(): number
set widthFitting(value: number)
Gets the width fitting mode to be applied when positioning and scaling child elements.
get wrap(): boolean
set wrap(value: boolean)
Gets whether or not to wrap children onto a new row/column when the size of the container is exceeded.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the LayoutGroupComponents of an application. Reach it through
app.systems.layoutgroup; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
A ScreenComponent defines a rectangular area where user interfaces can be constructed. Screens can either be 2D (screen space) or 3D (world space) - see screenSpace. It is possible to create an Entity hierarchy underneath an Entity with a ScreenComponent to create complex user interfaces using the following components:
You should never need to use the ScreenComponent constructor directly. To add a ScreenComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('screen', {
referenceResolution: new Vec2(1280, 720),
screenSpace: false
});
Once the ScreenComponent is added to the entity, you can access it via the Entity#screen property:
entity.screen.scaleBlend = 0.6; // Set the screen's scale blend to 0.6
console.log(entity.screen.scaleBlend); // Get the screen's scale blend and print it
Relevant Engine API examples:
cull: boolean = false
If true, then elements inside this screen will not be rendered when outside of the screen (only valid when screenSpace is true).
get priority(): number
set priority(value: number)
Gets the screen's render priority.
get referenceResolution(): Vec2
set referenceResolution(value: Vec2)
Gets the resolution that the ScreenComponent is designed for.
get resolution(): Vec2
set resolution(value: Vec2)
Gets the width and height of the ScreenComponent.
get scaleBlend(): number
set scaleBlend(value: number)
Gets the scale blend.
get scaleMode(): string
set scaleMode(value: string)
Gets the scale mode.
get screenSpace(): boolean
set screenSpace(value: boolean)
Gets whether the ScreenComponent will render its child ElementComponents in screen space instead of world space.
syncDrawOrder(): void
Set the drawOrder of each child ElementComponent so that ElementComponents which are last in the hierarchy are rendered on top. Draw Order sync is queued and will be updated by the next update loop.
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the ScreenComponents of an application. Reach it through app.systems.screen;
components are created with Entity#addComponent, never by calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
The ScrollbarComponent enables an Entity to behave like a draggable scrollbar. It is typically used together with a ScrollViewComponent to allow the user to scroll the contents of a scroll view area.
You should never need to use the ScrollbarComponent constructor directly. To add a ScrollbarComponent to an Entity, use Entity#addComponent. A draggable scrollbar requires a child handle entity with an input-enabled ElementComponent, wired up via the scrollbar's handleEntity property:
// Create a child handle entity that the user can drag
const handle = new Entity();
handle.addComponent('element', {
type: ELEMENTTYPE_IMAGE,
useInput: true
});
// Create the scrollbar entity and wire in the handle
const entity = new Entity();
entity.addChild(handle);
entity.addComponent('element', {
type: ELEMENTTYPE_IMAGE
});
entity.addComponent('scrollbar', {
orientation: ORIENTATION_VERTICAL,
value: 0,
handleSize: 0.5,
handleEntity: handle
});
Once the ScrollbarComponent is added to the entity, you can access it via the Entity#scrollbar property:
entity.scrollbar.value = 0.25; // Scroll the bar to 25%
console.log(entity.scrollbar.value); // Get the scroll value and print it
Relevant Engine API examples:
get handleEntity(): Entity | null
set handleEntity(arg: Entity | null)
Gets the entity to be used as the scrollbar handle.
get handleSize(): number
set handleSize(arg: number)
Gets the size of the handle relative to the size of the track.
get orientation(): number
set orientation(arg: number)
Gets whether the scrollbar moves horizontally or vertically.
get value(): number
set value(arg: number)
Gets the current position value of the scrollbar.
static EVENT_SETVALUE: string = 'set:value'
Fired whenever the scroll value changes. The handler is passed a number representing the current scroll value.
Example
entity.scrollbar.on('set:value', (value) => {
console.log(`Scroll value is now ${value}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the ScrollbarComponents of an application. Reach it through
app.systems.scrollbar; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends Component · category: User Interface
The ScrollViewComponent enables an Entity to behave like a masked scrolling area, with optional horizontal and vertical scroll bars. The component exposes references to child entities that represent the viewport, the content, and the (optional) horizontal and vertical ScrollbarComponents.
You should never need to use the ScrollViewComponent constructor directly. To add a ScrollViewComponent to an Entity, use Entity#addComponent:
const entity = new Entity();
entity.addComponent('element', {
type: ELEMENTTYPE_GROUP,
useInput: true
});
entity.addComponent('scrollview', {
horizontal: false,
vertical: true,
bounceAmount: 0.1
});
Once the ScrollViewComponent is added to the entity, you can access it via the Entity#scrollview property:
entity.scrollview.scroll = new Vec2(0, 1); // Scroll to the bottom
console.log(entity.scrollview.scroll); // Get the scroll position and print it
Relevant Engine API examples:
get bounceAmount(): number
set bounceAmount(arg: number)
Gets how far the content should move before bouncing back.
get contentEntity(): Entity | null
set contentEntity(arg: Entity | null)
Gets the entity which contains the scrolling content itself.
get friction(): number
set friction(arg: number)
Gets how freely the content should move if thrown.
get horizontal(): boolean
set horizontal(arg: boolean)
Gets whether horizontal scrolling is enabled.
get horizontalScrollbarEntity(): Entity | null
set horizontalScrollbarEntity(arg: Entity | null)
Gets the entity to be used as the horizontal scrollbar.
get horizontalScrollbarVisibility(): number
set horizontalScrollbarVisibility(arg: number)
Gets whether the horizontal scrollbar should be visible all the time, or only visible when the content exceeds the size of the viewport.
get mouseWheelSensitivity(): Vec2
set mouseWheelSensitivity(arg: Vec2)
Gets the mouse wheel horizontal and vertical sensitivity.
get scroll(): Vec2
set scroll(value: Vec2)
Gets the scroll value.
get scrollMode(): number
set scrollMode(arg: number)
Gets the scroll mode of the scroll viewer.
get useMouseWheel(): boolean
set useMouseWheel(arg: boolean)
Gets whether to use mouse wheel for scrolling (horizontally and vertically).
get vertical(): boolean
set vertical(arg: boolean)
Gets whether vertical scrolling is enabled.
get verticalScrollbarEntity(): Entity | null
set verticalScrollbarEntity(arg: Entity | null)
Gets the entity to be used as the vertical scrollbar.
get verticalScrollbarVisibility(): number
set verticalScrollbarVisibility(arg: number)
Gets whether the vertical scrollbar should be visible all the time, or only visible when the content exceeds the size of the viewport.
get viewportEntity(): Entity | null
set viewportEntity(arg: Entity | null)
Gets the entity to be used as the masked viewport area, within which the content will scroll.
static EVENT_SETSCROLL: string = 'set:scroll'
Fired whenever the scroll position changes. The handler is passed a Vec2 containing the horizontal and vertical scroll values in the range 0..1.
Example
entity.scrollview.on('set:scroll', (scroll) => {
console.log(`Horizontal scroll position: ${scroll.x}`);
console.log(`Vertical scroll position: ${scroll.y}`);
});
entity: Entitysystem: ComponentSystemget enabled(): boolean · set enabled(value: boolean)fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends ComponentSystem · category: User Interface
Manages the ScrollViewComponents of an application. Reach it through
app.systems.scrollview; components are created with Entity#addComponent, never by
calling the system directly.
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
An anchor keeps track of a position and rotation that is fixed relative to the real world. This allows the application to adjust the location of virtual objects placed in the scene in a way that helps with maintaining the illusion that the placed objects are really present in the user's environment.
get persistent(): boolean
Gets whether an anchor is persistent.
get uuid(): string | null
Gets the UUID string of a persisted anchor or null if the anchor is not persisted.
destroy(): void
Destroy an anchor.
forget(callback?: XrAnchorForgetCallback): void
Removes the persistent UUID of an anchor from the underlying system. This effectively makes the anchor non-persistent, so it will not be restored in future WebXR sessions.
Parameters
callback (XrAnchorForgetCallback, optional): Optional callback function to be called when
the anchor has been forgotten or if an error occurs.Example
// Forget the anchor and log the result or error
anchor.forget((err) => {
if (err) {
console.error('Failed to forget anchor:', err);
} else {
console.log('Anchor has been forgotten');
}
});
getPosition(): Vec3
Get the world space position of an anchor.
Returns Vec3: The world space position of an anchor.
getRotation(): Quat
Get the world space rotation of an anchor.
Returns Quat: The world space rotation of an anchor.
persist(callback?: XrAnchorPersistCallback): void
Persists the anchor between WebXR sessions by generating a universally unique identifier (UUID) for the anchor. This UUID can be used later to restore the anchor from the underlying system. Note that the underlying system may have a limit on the number of anchors that can be persisted per origin.
Parameters
callback (XrAnchorPersistCallback, optional): Optional callback function to be called when
the persistent UUID has been generated or if an error occurs.Example
// Persist the anchor and log the UUID or error
anchor.persist((err, uuid) => {
if (err) {
console.error('Failed to persist anchor:', err);
} else {
console.log('Anchor persisted with UUID:', uuid);
}
});
static EVENT_CHANGE: string = 'change'
Fired when an anchor's position and/or rotation is changed.
Example
anchor.on('change', () => {
// anchor has been updated
entity.setPosition(anchor.getPosition());
entity.setRotation(anchor.getRotation());
});
static EVENT_DESTROY: string = 'destroy'
Fired when an anchor is destroyed.
Example
// once anchor is destroyed
anchor.once('destroy', () => {
// destroy its related entity
entity.destroy();
});
static EVENT_FORGET: string = 'forget'
Fired when an anchor has been forgotten.
Example
anchor.on('forget', () => {
// anchor has been forgotten
});
static EVENT_PERSIST: string = 'persist'
Fired when an anchor has been persisted. The handler is passed the UUID string that can be used to restore this anchor.
Example
anchor.on('persist', (uuid) => {
// anchor has been persisted
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Anchors provide an ability to specify a point in the world that needs to be updated to correctly reflect the evolving understanding of the world by the underlying AR system, such that the anchor remains aligned with the same place in the physical world. Anchors tend to persist better relative to the real world, especially during a longer session with lots of movement.
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
anchors: true
});
get available(): boolean
True if Anchors are available. This information is available only when session has started.
get list(): XrAnchor[]
List of available XrAnchors.
get persistence(): boolean
True if Anchors support persistence.
get supported(): boolean
True if Anchors are supported.
get uuids(): string[] | null
Array of UUID strings of persistent anchors, or null if not available.
create(position: XRHitTestResult | Vec3, rotation?: Quat | XrAnchorCreateCallback, callback?: XrAnchorCreateCallback): void
Create an anchor using position and rotation, or from hit test result.
Parameters
position (XRHitTestResult | Vec3): Position for an anchor or a hit test result.rotation (Quat | XrAnchorCreateCallback, optional): Rotation for an anchor or a callback if
creating from a hit test result.callback (XrAnchorCreateCallback, optional): Callback to fire when anchor was created or
failed to be created.Example
// create an anchor using a position and rotation
app.xr.anchors.create(position, rotation, (err, anchor) => {
if (!err) {
// new anchor has been created
}
});
Example
// create an anchor from a hit test result
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
app.xr.anchors.create(hitTestResult, (err, anchor) => {
if (!err) {
// new anchor has been created
}
});
});
forget(uuid: string, callback?: XrAnchorForgetCallback): void
Forget an anchor by removing its UUID from underlying systems.
Parameters
uuid (string): UUID string associated with persistent anchor.callback (XrAnchorForgetCallback, optional): Callback to fire when anchor persistent data
was removed or error if failed.Example
// forget all available anchors
const uuids = app.xr.anchors.uuids;
for (let i = 0; i < uuids.length; i++) {
app.xr.anchors.forget(uuids[i]);
}
restore(uuid: string, callback?: XrAnchorCreateCallback): void
Restore anchor using persistent UUID.
Parameters
uuid (string): UUID string associated with persistent anchor.callback (XrAnchorCreateCallback, optional): Callback to fire when anchor was created or
failed to be created.Example
// restore an anchor using uuid string
app.xr.anchors.restore(uuid, (err, anchor) => {
if (!err) {
// new anchor has been created
}
});
Example
// restore all available persistent anchors
const uuids = app.xr.anchors.uuids;
for(let i = 0; i < uuids.length; i++) {
app.xr.anchors.restore(uuids[i]);
}
static EVENT_ADD: string = 'add'
Fired when a new XrAnchor is added. The handler is passed the XrAnchor that was added.
Example
app.xr.anchors.on('add', (anchor) => {
console.log('Anchor added');
});
static EVENT_AVAILABLE: string = 'available'
Fired when anchors become available.
Example
app.xr.anchors.on('available', () => {
console.log('Anchors are available');
});
static EVENT_DESTROY: string = 'destroy'
Fired when an XrAnchor is destroyed. The handler is passed the XrAnchor that was destroyed.
Example
app.xr.anchors.on('destroy', (anchor) => {
console.log('Anchor destroyed');
});
static EVENT_ERROR: string = 'error'
Fired when an anchor failed to be created. The handler is passed an Error object.
Example
app.xr.anchors.on('error', (err) => {
console.error(err.message);
});
static EVENT_UNAVAILABLE: string = 'unavailable'
Fired when anchors become unavailable.
Example
app.xr.anchors.on('unavailable', () => {
console.log('Anchors are unavailable');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: XR
DOM Overlay provides the ability to use DOM elements as an overlay in a WebXR AR session. It
requires that the root DOM element is provided for session start. That way, input source
select events are first tested against DOM Elements and then propagated down to the XR
Session. If this propagation is not desirable, use the beforexrselect event on a DOM element
and the preventDefault function to stop propagation.
app.xr.domOverlay.root = element;
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR);
// Disable input source firing `select` event when some descendant element of DOM overlay root
// is touched/clicked. This is useful when the user interacts with UI elements and there should
// not be `select` events behind UI.
someElement.addEventListener('beforexrselect', (evt) => {
evt.preventDefault();
});
get available(): boolean
True if DOM Overlay is available. This information becomes available only when the session has started and a valid root DOM element has been provided.
get root(): Element | null
set root(value: Element | null)
Gets the DOM element to be used as the root for DOM Overlay.
get state(): "screen" | "floating" | "head-locked" | null
State of the DOM Overlay, which defines how the root DOM element is rendered. Can be:
screen - indicates that the DOM element is covering the whole physical screen, matching
XR viewports.floating - indicates that the underlying platform renders the DOM element as floating in
space, which can move during the WebXR session or allow the application to move the element.head-locked - indicates that the DOM element follows the user's head movement
consistently, appearing similar to a helmet heads-up display.get supported(): boolean
True if DOM Overlay is supported.
Class · category: XR
Represents a finger of a tracked XrHand with related joints and index.
get hand(): XrHand
Gets the hand that the finger belongs to.
get index(): number
Gets the index of the finger. Enumeration is: thumb, index, middle, ring, little.
get joints(): XrJoint[]
Array of joints that belong to this finger, starting from joint closest to wrist all the way to the tip of a finger.
get tip(): XrJoint | null
Tip joint of the finger, or null if not available.
Class · extends EventHandler · category: XR
Represents a hand with fingers and joints.
get fingers(): XrFinger[]
Array of fingers of the hand.
get joints(): XrJoint[]
Array of joints in the hand.
get tips(): XrJoint[]
Array of joints that are fingertips.
get tracking(): boolean
True if tracking is available, otherwise tracking might be lost.
get wrist(): XrJoint | null
Wrist of a hand, or null if it is not available by WebXR underlying system.
getJointById(id: string): XrJoint | null
Returns joint by its XRHand id.
Parameters
id (string): Id of a joint based on specs ID's in XRHand: https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section.Returns XrJoint | null: Joint or null if not available.
static EVENT_TRACKING: string = 'tracking'
Fired when tracking becomes available.
Example
hand.on('tracking', () => {
console.log('Hand tracking is available');
});
static EVENT_TRACKINGLOST: string = 'trackinglost'
Fired when tracking is lost.
Example
hand.on('trackinglost', () => {
console.log('Hand tracking is lost');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
The Hit Test interface allows initiating hit testing against real-world geometry from various sources: the view, input sources, or an arbitrary ray in space. Results reflect the underlying AR system's understanding of the real world.
sources: XrHitTestSource[] = []
List of active XrHitTestSource.
get available(): boolean
True if Hit Test is available. This information is available only when the session has started.
get supported(): boolean
True if AR Hit Test is supported.
start(options?: object): void
Attempts to start hit test with provided reference space.
Parameters
options (object, optional, default {}): Optional object for passing arguments.
options.callback (XrHitTestStartCallback, optional): Optional callback function called once
hit test source is created or failed.
options.entityTypes (string[], optional): Optional list of underlying entity types against
which hit tests will be performed. Defaults to [ XRTRACKABLE_PLANE ]. Can be any
combination of the following:
options.offsetRay (Ray, optional): Optional ray by which
hit test ray can be offset.
options.profile (string, optional): if hit test source meant to match input source instead
of reference space, then name of profile of the XrInputSource should be provided.
options.spaceType (string, optional): Reference space type. Defaults to
XRSPACE_VIEWER. Can be one of the following:
Example
// start hit testing from viewer position facing forwards
app.xr.hitTest.start({
spaceType: XRSPACE_VIEWER,
callback: (err, hitTestSource) => {
if (err) return;
hitTestSource.on('result', (position, rotation) => {
// position and rotation of hit test result
});
}
});
Example
// start hit testing using an arbitrary ray
const ray = new Ray(new Vec3(0, 0, 0), new Vec3(0, -1, 0));
app.xr.hitTest.start({
spaceType: XRSPACE_LOCAL,
offsetRay: ray,
callback: (err, hitTestSource) => {
// hit test source that will sample real world geometry straight down
// from the position where AR session started
}
});
Example
// start hit testing for touch screen taps
app.xr.hitTest.start({
profile: 'generic-touchscreen',
callback: (err, hitTestSource) => {
if (err) return;
hitTestSource.on('result', (position, rotation, inputSource) => {
// position and rotation of hit test result
// that will be created from touch on mobile devices
});
}
});
static EVENT_ADD: string = 'add'
Fired when new XrHitTestSource is added to the list. The handler is passed the XrHitTestSource object that has been added.
Example
app.xr.hitTest.on('add', (hitTestSource) => {
// new hit test source is added
});
static EVENT_AVAILABLE: string = 'available'
Fired when hit test becomes available.
Example
app.xr.hitTest.on('available', () => {
console.log('Hit Testing is available');
});
static EVENT_ERROR: string = 'error'
Fired when failed create hit test source. The handler is passed the Error object.
Example
app.xr.hitTest.on('error', (err) => {
console.error(err.message);
});
static EVENT_REMOVE: string = 'remove'
Fired when XrHitTestSource is removed to the list. The handler is passed the XrHitTestSource object that has been removed.
Example
app.xr.hitTest.on('remove', (hitTestSource) => {
// hit test source is removed
});
static EVENT_RESULT: string = 'result'
Fired when hit test source receives new results. It provides transform information that tries to match real world picked geometry. The handler is passed the XrHitTestSource that produced the hit result, the Vec3 position, the Quat rotation and the XrInputSource (if it is a transient hit test source).
Example
app.xr.hitTest.on('result', (hitTestSource, position, rotation, inputSource) => {
target.setPosition(position);
target.setRotation(rotation);
});
static EVENT_UNAVAILABLE: string = 'unavailable'
Fired when hit test becomes unavailable.
Example
app.xr.hitTest.on('unavailable', () => {
console.log('Hit Testing is unavailable');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Represents XR hit test source, which provides access to hit results of real world geometry from AR session.
// start a hit test from a viewer origin forward
app.xr.hitTest.start({
spaceType: XRSPACE_VIEWER,
callback: (err, hitTestSource) => {
if (err) return;
// subscribe to hit test results
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
// position and rotation of hit test result
});
}
});
remove(): void
Stop and remove hit test source.
static EVENT_REMOVE: string = 'remove'
Fired when XrHitTestSource is removed.
Example
hitTestSource.once('remove', () => {
// hit test source has been removed
});
static EVENT_RESULT: string = 'result'
Fired when the hit test source receives new results. It provides transform information that tries to match real world geometry. Callback provides the Vec3 position, the Quat rotation, the XrInputSource (if it is a transient hit test source) and the XRHitTestResult object that is created by WebXR API.
Example
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
target.setPosition(position);
target.setRotation(rotation);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Image Tracking provides the ability to track real world images using provided image samples and their estimated sizes. The underlying system will assume that the tracked image can move and rotate in the real world and will try to provide transformation estimates and its tracking state.
get available(): boolean
True if Image Tracking is available. This information is only available when the XR session has started, and will be true if image tracking is supported and images were provided and they have been processed successfully.
get images(): XrTrackedImage[]
List of XrTrackedImage that contain tracking information.
get supported(): boolean
True if Image Tracking is supported.
add(image: Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData, width: number): XrTrackedImage | null
Add an image for image tracking. A width can also be provided to help the underlying system estimate the appropriate transformation. Modifying the tracked images list is only possible before an AR session is started.
Parameters
image (Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData): Image that is matching real world image as close as possible. Resolution of images should be
at least 300x300. High resolution does not improve tracking performance. The color of the
image is irrelevant, so grayscale images can be used. Images with too many geometric
features or repeating patterns will reduce tracking stability.width (number): Width (in meters) of image in the real world. Providing this value
as close to the real value will improve tracking quality.Returns XrTrackedImage | null: Tracked image object that will contain tracking information.
Returns null if image tracking is not supported or if the XR manager is not active.
Example
// image of a book cover that has width of 20cm (0.2m)
app.xr.imageTracking.add(bookCoverImg, 0.2);
remove(trackedImage: XrTrackedImage): void
Remove an image from image tracking.
Parameters
trackedImage (XrTrackedImage): Tracked image to be removed. Modifying the tracked
images list is only possible before an AR session is started.static EVENT_ERROR: string = 'error'
Fired when the XR session is started, but image tracking failed to process the provided images. The handler is passed the Error object.
Example
app.xr.imageTracking.on('error', (err) => {
console.error(err.message);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Provides access to input sources for WebXR.
Input sources represent:
get inputSources(): XrInputSource[]
List of active XrInputSource instances.
static EVENT_ADD: string = 'add'
Fired when a new XrInputSource is added to the list. The handler is passed the XrInputSource that has been added.
Example
app.xr.input.on('add', (inputSource) => {
// new input source is added
});
static EVENT_REMOVE: string = 'remove'
Fired when an XrInputSource is removed from the list. The handler is passed the XrInputSource that has been removed.
Example
app.xr.input.on('remove', (inputSource) => {
// input source is removed
});
static EVENT_SELECT: string = 'select'
Fired when XrInputSource has triggered primary action. This could be pressing a
trigger button, or touching a screen. The handler is passed the XrInputSource that
triggered the select event and the XRInputSourceEvent event from the WebXR API.
Example
const ray = new Ray();
app.xr.input.on('select', (inputSource, evt) => {
ray.set(inputSource.getOrigin(), inputSource.getDirection());
if (obj.intersectsRay(ray)) {
// selected an object with input source
}
});
static EVENT_SELECTEND: string = 'selectend'
Fired when XrInputSource has ended triggering primary action. The handler is passed
the XrInputSource that triggered the selectend event and the XRInputSourceEvent
event from the WebXR API.
Example
app.xr.input.on('selectend', (inputSource, evt) => {
console.log('Select ended');
});
static EVENT_SELECTSTART: string = 'selectstart'
Fired when XrInputSource has started to trigger primary action. The handler is
passed the XrInputSource that triggered the selectstart event and the
XRInputSourceEvent event from the WebXR API.
Example
app.xr.input.on('selectstart', (inputSource, evt) => {
console.log('Select started');
});
static EVENT_SQUEEZE: string = 'squeeze'
Fired when XrInputSource has triggered squeeze action. This is associated with
"grabbing" action on the controllers. The handler is passed the XrInputSource that
triggered the squeeze event and the XRInputSourceEvent event from the WebXR API.
Example
app.xr.input.on('squeeze', (inputSource, evt) => {
console.log('Squeeze');
});
static EVENT_SQUEEZEEND: string = 'squeezeend'
Fired when XrInputSource has ended triggering squeeze action. The handler is passed
the XrInputSource that triggered the squeezeend event and the XRInputSourceEvent
event from the WebXR API.
Example
app.xr.input.on('squeezeend', (inputSource, evt) => {
console.log('Squeeze ended');
});
static EVENT_SQUEEZESTART: string = 'squeezestart'
Fired when XrInputSource has started to trigger squeeze action. The handler is
passed the XrInputSource that triggered the squeezestart event and the
XRInputSourceEvent event from the WebXR API.
Example
app.xr.input.on('squeezestart', (inputSource, evt) => {
if (obj.containsPoint(inputSource.getPosition())) {
// grabbed an object
}
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Represents XR input source, which is any input mechanism which allows the user to perform targeted actions in the same virtual space as the viewer. Example XR input sources include, but are not limited to: handheld controllers, optically tracked hands, touch screen taps, and gaze-based input methods that operate on the viewer's pose.
get elementEntity(): Entity | null
If elementInput is true, this property will hold entity with Element component at which this input source is hovering, or null if not hovering over any element.
get elementInput(): boolean
set elementInput(value: boolean)
Gets whether the input source can interact with ElementComponents.
get gamepad(): Gamepad | null
If input source has buttons, triggers, thumbstick or touchpad, then this object provides access to its states.
get grip(): boolean
If input source can be held, then it will have node with its world transformation, that can be used to position and rotate visual object based on it.
get hand(): XrHand | null
If input source is a tracked hand, then it will point to XrHand otherwise it is null.
get handedness(): string
Describes which hand input source is associated with. Can be one of the following:
get hitTestSources(): XrHitTestSource[]
List of active XrHitTestSource instances associated with this input source.
get id(): number
Unique number associated with instance of input source. Same physical devices when reconnected will not share this ID.
get inputSource(): XRInputSource
XRInputSource object that is associated with this input source.
get profiles(): string[]
List of input profile names indicating both the preferred visual representation and behavior of the input source.
get selecting(): boolean
True if input source is in active primary action between selectstart and selectend events.
get squeezing(): boolean
True if input source is in active squeeze action between squeezestart and squeezeend events.
get targetRayMode(): string
Type of ray Input Device is based on. Can be one of the following:
getDirection(): Vec3
Get the world space direction of input source ray.
Returns Vec3: The world space direction of input source ray.
getLinearVelocity(): Vec3 | null
Get the linear velocity (units per second) of the input source if it is handheld (grip is true). Otherwise it will return null. The velocity is relative to the parent of the XR camera, so it does not include the motion of the parent.
Returns Vec3 | null: The world space linear velocity of the handheld input source.
getLocalPosition(): Vec3 | null
Get the local space position of input source if it is handheld (grip is true). Local space is relative to parent of the XR camera. Otherwise it will return null.
Returns Vec3 | null: The local space position of handheld input source.
getLocalRotation(): Quat | null
Get the local space rotation of input source if it is handheld (grip is true). Local space is relative to parent of the XR camera. Otherwise it will return null.
Returns Quat | null: The local space rotation of handheld input source.
getOrigin(): Vec3
Get the world space origin of input source ray.
Returns Vec3: The world space origin of input source ray.
getPosition(): Vec3 | null
Get the world space position of input source if it is handheld (grip is true). Otherwise it will return null.
Returns Vec3 | null: The world space position of handheld input source.
getRotation(): Quat | null
Get the world space rotation of input source if it is handheld (grip is true). Otherwise it will return null.
Returns Quat | null: The world space rotation of handheld input source.
hitTestStart(options?: object): void
Attempts to start hit test source based on this input source.
Parameters
options (object, optional, default {}): Object for passing optional arguments.
options.callback (XrHitTestStartCallback, optional): Optional callback function called once
hit test source is created or failed.
options.entityTypes (string[], optional): Optional list of underlying entity types against
which hit tests will be performed. Defaults to [XRTRACKABLE_PLANE]. Can be any
combination of the following:
options.offsetRay (Ray, optional): Optional ray by which hit test ray can be offset.
Example
app.xr.input.on('add', (inputSource) => {
inputSource.hitTestStart({
callback: (err, hitTestSource) => {
if (err) return;
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
// position and rotation of hit test result
// that will be created from touch on mobile devices
});
}
});
});
static EVENT_HITTESTADD: string = 'hittest:add'
Fired when new XrHitTestSource is added to the input source. The handler is passed the XrHitTestSource object that has been added.
Example
inputSource.on('hittest:add', (hitTestSource) => {
// new hit test source is added
});
static EVENT_HITTESTREMOVE: string = 'hittest:remove'
Fired when XrHitTestSource is removed from the input source. The handler is passed the XrHitTestSource object that has been removed.
Example
inputSource.on('hittest:remove', (hitTestSource) => {
// hit test source is removed
});
static EVENT_HITTESTRESULT: string = 'hittest:result'
Fired when hit test source receives new results. It provides transform information that tries to match real world picked geometry. The handler is passed the XrHitTestSource object that produced the hit result, the Vec3 position, the Quat rotation and the XRHitTestResult object that is created by the WebXR API.
Example
inputSource.on('hittest:result', (hitTestSource, position, rotation, hitTestResult) => {
target.setPosition(position);
target.setRotation(rotation);
});
static EVENT_REMOVE: string = 'remove'
Fired when XrInputSource is removed.
Example
inputSource.once('remove', () => {
// input source is not available anymore
});
static EVENT_SELECT: string = 'select'
Fired when input source has triggered primary action. This could be pressing a trigger button, or touching a screen. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
const ray = new Ray();
inputSource.on('select', (evt) => {
ray.set(inputSource.getOrigin(), inputSource.getDirection());
if (obj.intersectsRay(ray)) {
// selected an object with input source
}
});
static EVENT_SELECTEND: string = 'selectend'
Fired when input source has ended triggering primary action. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
inputSource.on('selectend', (evt) => {
console.log('Select ended');
});
static EVENT_SELECTSTART: string = 'selectstart'
Fired when input source has started to trigger primary action. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
inputSource.on('selectstart', (evt) => {
console.log('Select started');
});
static EVENT_SQUEEZE: string = 'squeeze'
Fired when input source has triggered squeeze action. This is associated with "grabbing" action on the controllers. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
inputSource.on('squeeze', (evt) => {
console.log('Squeeze');
});
static EVENT_SQUEEZEEND: string = 'squeezeend'
Fired when input source has ended triggering squeeze action. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
inputSource.on('squeezeend', (evt) => {
console.log('Squeeze ended');
});
static EVENT_SQUEEZESTART: string = 'squeezestart'
Fired when input source has started to trigger squeeze action. The handler is passed an XRInputSourceEvent object from the WebXR API.
Example
inputSource.on('squeezestart', (evt) => {
if (obj.containsPoint(inputSource.getPosition())) {
// grabbed an object
}
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · category: XR
Represents the joint of a finger.
get finger(): XrFinger | null
Finger that joint relates to.
get hand(): XrHand
Hand that joint relates to.
get id(): XRHandJoint
Id of a joint based on WebXR Hand Input Specs.
get index(): number
Index of a joint within a finger, starting from 0 (root of a finger) all the way to tip of the finger.
get radius(): number
The radius of a joint, which is a distance from joint to the edge of a skin.
get tip(): boolean
True if joint is a tip of a finger.
get wrist(): boolean
True if joint is a wrist.
getPosition(): Vec3
Get the world space position of a joint.
Returns Vec3: The world space position of a joint.
getRotation(): Quat
Get the world space rotation of a joint.
Returns Quat: The world space rotation of a joint.
Class · extends EventHandler · category: XR
Light Estimation provides illumination data from the real world, which is estimated by the underlying AR system. It provides a reflection Cube Map, that represents the reflection estimation from the viewer position. A more simplified approximation of light is provided by L2 Spherical Harmonics data. And the most simple level of light estimation is the most prominent directional light, its rotation, intensity and color.
get available(): boolean
True if estimated light information is available.
Example
if (app.xr.lightEstimation.available) {
entity.light.intensity = app.xr.lightEstimation.intensity;
}
get color(): Color | null
Color of what is estimated to be the most prominent directional light. Or null if data is not available.
get intensity(): number | null
Intensity of what is estimated to be the most prominent directional light. Or null if data is not available.
get rotation(): Quat | null
Rotation of what is estimated to be the most prominent directional light. Or null if data is not available.
get sphericalHarmonics(): Float32Array<ArrayBufferLike> | null
Spherical harmonic coefficients of estimated ambient light. Or null if data is not available.
get supported(): boolean
True if Light Estimation is supported. This information is available only during an active AR session.
end(): void
End estimation of illumination data.
start(): void
Start estimation of illumination data. Availability of such data will come later and an
available event will be fired. If it failed to start estimation, an error event will be
fired.
Example
app.xr.on('start', () => {
if (app.xr.lightEstimation.supported) {
app.xr.lightEstimation.start();
}
});
static EVENT_AVAILABLE: string = 'available'
Fired when light estimation data becomes available.
Example
app.xr.lightEstimation.on('available', () => {
console.log('Light estimation is available');
});
static EVENT_ERROR: string = 'error'
Fired when light estimation has failed to start. The handler is passed the Error object related to failure of light estimation start.
Example
app.xr.lightEstimation.on('error', (error) => {
console.error(error.message);
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
XrManager provides a comprehensive interface for WebXR integration in PlayCanvas applications. It manages the full lifecycle of XR sessions (VR/AR), handles device capabilities, and provides access to various XR features through specialized subsystems.
In order for XR to be available, ensure that your application is served over HTTPS or localhost.
The AppBase class automatically creates an instance of this class and makes it available as AppBase#xr.
Ready-made XR building blocks ship under playcanvas/scripts/esm/xr/: xr-session.mjs for
session lifecycle and camera rig transforms, xr-controllers.mjs for WebXR controller and hand
models, xr-navigation.mjs for teleportation, smooth locomotion and turning,
xr-manipulation.mjs for two-handed drag, rotate and scale of the world, and xr-menu.mjs for
hand-tracked and controller-driven 3D menus.
anchors: XrAnchors
Provides access to Anchors.
domOverlay: XrDomOverlay
Provides access to DOM overlay capabilities.
hitTest: XrHitTest
Provides the ability to perform hit tests on the representation of real world geometry of the underlying AR system.
imageTracking: XrImageTracking
Provides access to image tracking capabilities.
input: XrInput
Provides access to Input Sources.
lightEstimation: XrLightEstimation
Provides access to light estimation capabilities.
meshDetection: XrMeshDetection
Provides access to mesh detection capabilities.
planeDetection: XrPlaneDetection
Provides access to plane detection capabilities.
views: XrViews
Provides access to views and their capabilities.
get active(): boolean
True if XR session is running.
get camera(): Entity | null
Active camera for which XR session is running or null.
get fixedFoveation(): number | null
set fixedFoveation(value: number | null)
Gets the current fixed foveation level, which is between 0 and 1. 0 is no foveation and 1 is highest foveation. If fixed foveation is not supported, this value returns null.
get framebufferScaleFactor(): number
Framebuffer scale factor. This value is read-only and can only be set when starting a new XR session.
get frameRate(): number | null
XR session frameRate or null if this information is not available. This value can change during an active XR session.
get graphicsBinding(): any
Backend-specific XR binding for GPU camera/depth paths when available (for example WebGL
XRWebGLBinding or WebGPU XRGPUBinding when exposed by the user agent).
get session(): XRSession | null
Provides access to XRSession of WebXR.
get spaceType(): string | null
Returns reference space type of currently running XR session or null if no session is running. Can be any of XRSPACE_*.
get supported(): boolean
True if XR is supported.
get supportedFrameRates(): number[] | null
List of supported frame rates, or null if this data is not available.
get type(): string | null
Returns type of currently running XR session or null if no session is running. Can be any of XRTYPE_*.
end(callback?: XrErrorCallback): void
Attempts to end XR session and optionally fires callback when session is ended or failed to end.
Parameters
callback (XrErrorCallback, optional): Optional callback function called once session is
ended. The callback has one argument Error - it is null if successfully ended XR session.Example
app.keyboard.on('keydown', (evt) => {
if (evt.key === KEY_ESCAPE && app.xr.active) {
app.xr.end();
}
});
initiateRoomCapture(callback: XrRoomCaptureCallback): void
Initiate manual room capture. If the underlying XR system supports manual capture of the room, it will start the capturing process, which can affect plane and mesh detection, and improve hit-test quality against real-world geometry.
Parameters
callback (XrRoomCaptureCallback): Callback that will be fired once capture is complete
or failed.Example
this.app.xr.initiateRoomCapture((err) => {
if (err) {
// capture failed
return;
}
// capture was successful
});
isAvailable(type: string): boolean
Check if the specified type of session is available.
Parameters
type (string): Session type. Can be one of the following:
Returns boolean: True if the specified session type is available.
Example
if (app.xr.isAvailable(XRTYPE_VR)) {
// VR is available
}
start(camera: CameraComponent, type: string, spaceType: string, options?: object): void
Attempts to start XR session for provided CameraComponent and optionally fires callback when session is created or failed to create. Integrated XR APIs need to be enabled by providing relevant options.
Note that the start method needs to be called in response to user action, such as a button click. It will not work if called in response to a timer or other event.
Parameters
camera (CameraComponent): It will be used to render XR session and manipulated based
on pose tracking.
type (string): Session type. Can be one of the following:
spaceType (string): Reference space type. Can be one of the following:
options (object, optional): Object with additional options for XR session initialization.
options.anchors (boolean, optional): Set to true to attempt to enable
XrAnchors.options.callback (XrErrorCallback, optional): Optional callback function called once session
is started. The callback has one argument Error - it is null if successfully started XR
session.options.depthSensing (object, optional): Optional object with parameters to attempt to enable
depth sensing.
options.depthSensing.dataFormatPreference (string, optional): Optional data format
preference for depth sensing, can be 'luminance-alpha' or 'float32'
(XRDEPTHSENSINGFORMAT_*), defaults to 'luminance-alpha'. Most preferred and supported will
be chosen by the underlying depth sensing system.options.depthSensing.usagePreference (string, optional): Optional usage preference for depth
sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to
'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing
system.options.framebufferScaleFactor (number, optional): Framebuffer scale factor should
be higher than 0.0, by default 1.0 (no scaling). A value of 0.5 will reduce the resolution
of an XR session in half, and a value of 2.0 will double the resolution.options.imageTracking (boolean, optional): Set to true to attempt to enable
XrImageTracking.options.meshDetection (boolean, optional): Set to true to attempt to enable
XrMeshDetection.options.optionalFeatures (string[], optional): Optional features for XRSession start. It is
used for getting access to additional WebXR spec extensions.options.planeDetection (boolean, optional): Set to true to attempt to enable
XrPlaneDetection.Example
button.on('click', () => {
app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR);
});
Example
button.on('click', () => {
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
anchors: true,
imageTracking: true,
depthSensing: { }
});
});
updateTargetFrameRate(frameRate: number, callback?: Function): void
Update target frame rate of an XR session to one of supported value provided by supportedFrameRates list.
Parameters
frameRate (number): Target frame rate. It should be any value from the list
of supportedFrameRates.callback (Function, optional): Callback that will be called when frameRate has been
updated or failed to update with error provided.static isDeviceSupported(deviceType: string, type: string): Promise<boolean>
Tests whether an immersive WebXR session of the given type can run on the specified graphics backend. Unlike XrManager#isAvailable, this is a static method that can be called before a graphics device (or the AppBase) is created, which makes it useful for deciding which device type to create for XR - for example WebGPU vs WebGL2.
This is a best-effort preflight check. The only authoritative test remains a successful XrManager#start, so a fallback path should always be kept.
Parameters
deviceType (string): The graphics device type the session would run on. Can be
DEVICETYPE_WEBGPU or DEVICETYPE_WEBGL2.
type (string): The session type. Can be:
Returns Promise<boolean>: Promise that resolves to true if a session of the given type is
reported supported on the given backend, false otherwise.
Example
const supported = await XrManager.isDeviceSupported(DEVICETYPE_WEBGPU, XRTYPE_VR);
if (supported) {
// a WebGPU device can be created and used to offer VR
}
static EVENT_AVAILABLE: string = 'available'
Fired when availability of the XR type is changed. This event is available in two forms. They are as follows:
available - Fired when availability of any XR type is changed. The handler is passed
the session type that has changed availability and a boolean representing the availability.available:[type] - Fired when availability of specific XR type is changed. The handler
is passed a boolean representing the availability.Example
app.xr.on('available', (type, available) => {
console.log(`XR type ${type} is now ${available ? 'available' : 'unavailable'}`);
});
Example
app.xr.on(`available:${XRTYPE_VR}`, (available) => {
console.log(`XR type VR is now ${available ? 'available' : 'unavailable'}`);
});
static EVENT_END: string = 'end'
Fired when XR session is ended. While the handlers run, XrManager#camera, XrManager#type and XrManager#spaceType still describe the session that has ended, and they are reset once all handlers have run.
Example
app.xr.on('end', () => {
// XR session has ended
});
static EVENT_ERROR: string = 'error'
Fired when XR session is failed to start or failed to check for session type support. The handler is passed the Error object related to failure of session start or check of session type support.
Example
app.xr.on('error', (error) => {
console.error(error.message);
});
static EVENT_START: string = 'start'
Fired when XR session is started.
Example
app.xr.on('start', () => {
// XR session has started
});
static EVENT_UPDATE: string = 'update'
Fired when XR session is updated, providing relevant XRFrame object. The handler is passed XRFrame object that can be used for interfacing directly with WebXR APIs.
Example
app.xr.on('update', (frame) => {
console.log('XR frame updated');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Detected Mesh instance that provides its transform (position, rotation), triangles (vertices, indices) and its semantic label. Any of its properties can change during its lifetime.
get indices(): Uint32Array<ArrayBufferLike>
Array of mesh indices.
get label(): string
Semantic Label of a mesh that is provided by underlying system. Current list includes (but not limited to): https://github.com/immersive-web/semantic-labels/blob/master/labels.json
get vertices(): Float32Array<ArrayBufferLike>
Array of mesh vertices. This array contains 3 components per vertex (x, y, z).
getPosition(): Vec3
Get the world space position of a mesh.
Returns Vec3: The world space position of a mesh.
getRotation(): Quat
Get the world space rotation of a mesh.
Returns Quat: The world space rotation of a mesh.
static EVENT_CHANGE: string = 'change'
Fired when XrMesh attributes such as vertices, indices and/or label have been
changed. Position and rotation can change at any time without triggering a change event.
Example
mesh.on('change', () => {
// mesh attributes have been changed
});
static EVENT_REMOVE: string = 'remove'
Fired when an XrMesh is removed. Its attributes, such as its vertices and label, keep their last values.
Example
mesh.once('remove', () => {
// mesh is no longer available
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Mesh Detection provides the ability to detect real world meshes based on the scanning and reconstruction by the underlying AR system.
// start session with plane detection enabled
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
meshDetection: true
});
app.xr.meshDetection.on('add', (mesh) => {
// new mesh been added
});
get available(): boolean
True if Mesh Detection is available. This information is available only when session has started.
get meshes(): XrMesh[]
Array of XrMesh instances that contain transform, vertices and label information.
get supported(): boolean
True if Mesh Detection is supported.
static EVENT_ADD: string = 'add'
Fired when new XrMesh is added to the list. The handler is passed the XrMesh instance that has been added.
Example
app.xr.meshDetection.on('add', (mesh) => {
// a new XrMesh has been added
});
static EVENT_AVAILABLE: string = 'available'
Fired when mesh detection becomes available.
Example
app.xr.meshDetection.on('available', () => {
console.log('Mesh detection is available');
});
static EVENT_REMOVE: string = 'remove'
Fired when a XrMesh is removed from the list. The handler is passed the XrMesh instance that has been removed.
Example
app.xr.meshDetection.on('remove', (mesh) => {
// XrMesh has been removed
});
static EVENT_UNAVAILABLE: string = 'unavailable'
Fired when mesh detection becomes unavailable.
Example
app.xr.meshDetection.on('unavailable', () => {
console.log('Mesh detection is unavailable');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Represents a detected plane in the real world, providing its position, rotation, polygon points, and semantic label. The plane data may change over time as the system updates its understanding of the environment. Instances of this class are created and managed by the XrPlaneDetection system.
get id(): number
Unique identifier of a plane.
get label(): string
Gets the semantic label of the plane provided by the underlying system. The label describes the type of surface the plane represents, such as "floor", "wall", "ceiling", etc. The list of possible labels can be found in the semantic labels repository.
Example
if (plane.label === 'floor') {
console.log('This plane represents the floor.');
} else if (plane.label === 'wall') {
console.log('This plane represents a wall.');
}
get orientation(): "horizontal" | "vertical" | null
Gets the plane's specific orientation. This can be "horizontal" for planes that are parallel
to the ground, "vertical" for planes that are perpendicular to the ground, or null if the
orientation is different or unknown.
Example
if (plane.orientation === 'horizontal') {
console.log('This plane is horizontal.');
} else if (plane.orientation === 'vertical') {
console.log('This plane is vertical.');
} else {
console.log('Orientation of this plane is unknown or different.');
}
get points(): DOMPointReadOnly[]
Gets the array of points that define the polygon of the plane in its local coordinate space.
Each point is represented as a DOMPointReadOnly object with x, y, and z properties.
These points can be transformed to world coordinates using the plane's position and
rotation.
Example
// prepare reusable objects
const transform = new Mat4();
const vecA = new Vec3();
const vecB = new Vec3();
// update Mat4 to plane position and rotation
transform.setTRS(plane.getPosition(), plane.getRotation(), Vec3.ONE);
// draw lines between points
for (let i = 0; i < plane.points.length; i++) {
vecA.copy(plane.points[i]);
vecB.copy(plane.points[(i + 1) % plane.points.length]);
// transform points to world space
transform.transformPoint(vecA, vecA);
transform.transformPoint(vecB, vecB);
// render line
app.drawLine(vecA, vecB, Color.WHITE);
}
getPosition(): Vec3
Get the world space position of a plane.
Returns Vec3: The world space position of a plane.
getRotation(): Quat
Get the world space rotation of a plane.
Returns Quat: The world space rotation of a plane.
static EVENT_CHANGE: string = 'change'
Fired when XrPlane attributes such as: orientation and/or points have been changed.
Position and rotation can change at any time without triggering a change event.
Example
plane.on('change', () -> {
// plane has been changed
});
static EVENT_REMOVE: string = 'remove'
Fired when an XrPlane is removed. Its attributes, such as its points and label, keep their last values.
Example
plane.once('remove', () => {
// plane is not available anymore
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Plane Detection provides the ability to detect real world surfaces based on estimations of the underlying AR system.
// start session with plane detection enabled
app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR, {
planeDetection: true
});
app.xr.planeDetection.on('add', (plane) => {
// new plane been added
});
get available(): boolean
True if Plane Detection is available. This information is available only when the session has started.
get planes(): XrPlane[]
Array of XrPlane instances that contain individual plane information.
get supported(): boolean
True if Plane Detection is supported.
static EVENT_ADD: string = 'add'
Fired when new XrPlane is added to the list. The handler is passed the XrPlane instance that has been added.
Example
app.xr.planeDetection.on('add', (plane) => {
// new plane is added
});
static EVENT_AVAILABLE: string = 'available'
Fired when plane detection becomes available.
Example
app.xr.planeDetection.on('available', () => {
console.log('Plane detection is available');
});
static EVENT_REMOVE: string = 'remove'
Fired when a XrPlane is removed from the list. The handler is passed the XrPlane instance that has been removed.
Example
app.xr.planeDetection.on('remove', (plane) => {
// new plane is removed
});
static EVENT_UNAVAILABLE: string = 'unavailable'
Fired when plane detection becomes unavailable.
Example
app.xr.planeDetection.on('unavailable', () => {
console.log('Plane detection is unavailable');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
The tracked image interface that is created by the Image Tracking system and is provided as a list from XrImageTracking#images. It contains information about the tracking state as well as the position and rotation of the tracked image.
get emulated(): boolean
True if image was recently tracked but currently is not actively tracked due to inability of identifying the image by the underlying AR system. Position and rotation will be based on the previously known transformation assuming the tracked image has not moved.
get image(): Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData
Image that is used for tracking.
get trackable(): boolean
True if image is trackable. A too small resolution or invalid images can be untrackable by the underlying AR system.
get tracking(): boolean
True if image is in tracking state and being tracked in real world by the underlying AR system.
get width(): number
set width(value: number)
Get the width (in meters) of image in real world.
getPosition(): Vec3
Get the world position of the tracked image.
Returns Vec3: Position in world space.
Example
// update entity position to match tracked image position
entity.setPosition(trackedImage.getPosition());
getRotation(): Quat
Get the world rotation of the tracked image.
Returns Quat: Rotation in world space.
Example
// update entity rotation to match tracked image rotation
entity.setRotation(trackedImage.getRotation());
static EVENT_TRACKED: string = 'tracked'
Fired when image becomes actively tracked.
Example
trackedImage.on('tracked', () => {
console.log('Image is now tracked');
});
static EVENT_UNTRACKED: string = 'untracked'
Fired when image is no longer actively tracked.
Example
trackedImage.on('untracked', () => {
console.log('Image is no longer tracked');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends RenderView · category: XR
Represents an XR View which represents a screen (monoscopic scenario such as a mobile phone) or an eye (stereoscopic scenario such as an HMD context). It provides access to the view's color and depth information based on the capabilities of underlying AR system.
get depthUvMatrix(): Mat4
4x4 matrix that should be used to transform depth texture UVs to normalized UVs in a shader. It is updated when the depth texture is resized. Refer to EVENT_DEPTHRESIZE.
Example
material.setParameter('matrix_depth_uv', view.depthUvMatrix.data);
get depthValueToMeters(): number
Multiply this coefficient number by raw depth value to get depth in meters.
Example
material.setParameter('depth_to_meters', view.depthValueToMeters);
get eye(): string
An eye with which this view is associated. Can be any of:
get textureColor(): Texture | null
Texture associated with this view's camera color. Equals to null if camera color is not available or is not supported.
get textureDepth(): Texture | null
Texture that contains packed depth information which is reconstructed using the underlying
AR system. This texture can be used (not limited to) for reconstructing real world
geometry, virtual object placement, occlusion of virtual object by the real world geometry,
and more.
The format of this texture is any of PIXELFORMAT_LA8, PIXELFORMAT_DEPTH, or
PIXELFORMAT_R32F based on XrViews#depthPixelFormat. It is UV transformed
based on the underlying AR system which can be normalized using depthUvMatrix.
Equals to null if camera depth is not supported.
Example
// GPU path, attaching texture to material
material.setParameter('texture_depthSensingMap', view.textureDepth);
material.setParameter('matrix_depth_uv', view.depthUvMatrix.data);
material.setParameter('depth_to_meters', view.depthValueToMeters);
Example
// GLSL shader to unpack depth texture
// when depth information is provided in form of LA8
varying vec2 vUv0;
uniform sampler2D texture_depthSensingMap;
uniform mat4 matrix_depth_uv;
uniform float depth_to_meters;
void main(void) {
// transform UVs using depth matrix
vec2 texCoord = (matrix_depth_uv * vec4(vUv0.xy, 0.0, 1.0)).xy;
// get luminance alpha components from depth texture
vec2 packedDepth = texture2D(texture_depthSensingMap, texCoord).ra;
// unpack into single value in millimeters
float depth = dot(packedDepth, vec2(255.0, 256.0 * 255.0)) * depth_to_meters; // m
// normalize: 0m to 8m distance
depth = min(depth / 8.0, 1.0); // 0..1 = 0m..8m
// paint scene from black to white based on distance
gl_FragColor = vec4(depth, depth, depth, 1.0);
}
getDepth(u: number, v: number): number | null
Get a depth value from depth information in meters. The specified UV is in the range 0..1, with the origin in the top-left corner of the depth texture.
Parameters
u (number): U coordinate of pixel in depth texture, which is in range from 0.0 to
1.0 (left to right).v (number): V coordinate of pixel in depth texture, which is in range from 0.0 to
1.0 (top to bottom).Returns number | null: Depth in meters or null if depth information is currently not
available.
Example
const depth = view.getDepth(u, v);
if (depth !== null) {
// depth in meters
}
static EVENT_DEPTHRESIZE: string = 'depth:resize'
Fired when the depth sensing texture has been resized. The depthUvMatrix needs to be updated for relevant shaders. The handler is passed the new width and height of the depth texture in pixels.
Example
view.on('depth:resize', () => {
material.setParameter('matrix_depth_uv', view.depthUvMatrix);
});
get viewport(): Vec4fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleClass · extends EventHandler · category: XR
Provides access to list of XrViews and information about their capabilities, such as support and availability of view's camera color texture, depth texture and other parameters.
get availableColor(): boolean
Check if Camera Color is available. This information becomes available only after session has started.
get availableDepth(): boolean
Check if Camera Depth is available. This information becomes available only after session has started.
get depthGpuOptimized(): boolean
Whether the depth sensing is GPU optimized.
get depthPixelFormat(): 2 | 15 | null
The depth sensing pixel format. Can be:
PIXELFORMAT_LA8get list(): XrView[]
An array of XrViews of this session. Views are not available straight away on
session start, and can be added/removed mid-session. So use of add/remove events is
required for accessing views.
get supportedColor(): boolean
Check if Camera Color is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions.
get supportedDepth(): boolean
Check if Camera Depth is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions.
get(eye: string): XrView | null
Get an XrView by its associated eye constant.
Parameters
eye (string): An XREYE_* view is associated with. Can be 'none' for monoscope views.Returns XrView | null: View or null if view of such eye is not available.
static EVENT_ADD: string = 'add'
Fired when a view has been added. Views are not available straight away on session start and are added mid-session. They can be added/removed mid session by the underlying system. The handler is passed the XrView that has been added.
Example
xr.views.on('add', (view) => {
console.log('View added');
});
static EVENT_REMOVE: string = 'remove'
Fired when a view has been removed. They can be added/removed mid session by the underlying system. The handler is passed the XrView that has been removed.
Example
xr.views.on('remove', (view) => {
console.log('View removed');
});
fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandlerhasEvent(name: string): booleanoff(name?: string, callback?: HandleEventCallback, scope?: any): EventHandleron(name: string, callback: HandleEventCallback, scope?: any): EventHandleonce(name: string, callback: HandleEventCallback, scope?: any): EventHandleInterface · category: Other
component: string
The name of the component that owns the property, or graph
for a transform on the entity itself.
entityPath: string[]
The names of the entities from the animation root down to the target entity.
propertyPath: string[]
The property name segments, for example
['localPosition'] or ['weight.Smile'].
Interface · category: Other
ringRadius?: number
The ring radius.
sectorAngle?: number
The sector angle.
tubeRadius?: number
The tube radius.
Interface · category: Other
arrowLength?: number
The length of the arrow head
arrowThickness?: number
The thickness of the arrow head
gap?: number
The gap between the arrow base and the center
lineLength?: number
The length of the line
lineThickness?: number
The thickness of the line
tolerance?: number
The tolerance for intersection tests
Interface · category: Other
animation: Animation | AnimTrack
An animation: an AnimTrack when loaded from a glTF or GLB file, or a legacy Animation when loaded from JSON.
animclip: AnimTrack
An animation clip.
animstategraph: AnimStateGraph
An animation state graph.
audio: Sound
A sound.
binary: ArrayBuffer
The raw contents of the file.
bundle: Bundle
A bundle: an archive whose files back other assets.
container: ContainerResource
The renders, materials, textures, animations and gsplats of a glTF or GLB file.
css: string
The CSS text.
cubemap: Texture | null
The cube map, or null when the asset provides only prefiltered levels. Asset#resources holds the cube map followed by its six prefiltered levels, with null for each level the asset does not provide.
folder: null
Folders hold no resource.
font: Font | CanvasFont
A Font loaded from a font file.
gsplat: GSplatResourceBase | GSplatOctreeResource
A Gaussian splat resource, or the octree resource of a level-of-detail splat scene.
hierarchy: Entity
The root entity of an instantiated scene hierarchy.
html: string
The HTML text.
json: unknown
The parsed JSON data.
material: Material
A material, a StandardMaterial unless a custom parser creates another kind.
model: Model
A model.
render: Render
The meshes of one glTF mesh, created when a container asset loads.
scene: Scene
A scene.
scenesettings: any
The settings block of a scene file.
script: Record<string, typeof Script>
The script classes declared by a script file, keyed by class name.
shader: string
The shader source text.
sprite: Sprite
A sprite.
template: Template
A template.
text: string
The text of the file.
texture: Texture
A texture.
textureatlas: TextureAtlas
A texture atlas.
Interface · category: Other
asInt?: boolean
If true, vertex attribute data will be accessible as integer numbers in shader code. Defaults to false, which means that vertex attribute data will be accessible as floating point numbers. Can be only used with INT and UINT data types.
components: number
The number of components of the vertex attribute. Can be 1, 2, 3 or 4.
normalize?: boolean
If true, vertex attribute data will be mapped from a 0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data is left unchanged. If this property is unspecified, false is assumed. This property is ignored when asInt is true.
semantic: string
The meaning of the vertex element. This is used to link the vertex data to a shader input. Can be:
If vertex data has a meaning other that one of those listed above, use the user-defined semantics: SEMANTIC_ATTR0 to SEMANTIC_ATTR15.
type: number
The data type of the attribute. Can be:
Interface · category: Other
array?: boolean
True if this attribute is an array of type
type: "string" | "number" | "boolean" | "rgb" | "curve" | "json" | "vec2" | "vec3" | "vec4" | "entity" | "asset" | "rgba"
The Attribute type
Interface · category: Other
Properties related to the HDR bloom effect, a postprocessing technique that simulates the natural glow of bright light sources by spreading their intensity beyond their boundaries, creating a soft and realistic blooming effect.
blurLevel: number
The number of iterations for blurring the bloom effect, with each level doubling the blur size. Once the blur size matches the dimensions of the render target, further blur passes are skipped. The default value is 16.
intensity: number
The intensity of the bloom effect, 0-0.1 range. Defaults to 0, making it disabled.
threshold: number
The brightness below which the scene does not contribute to bloom. Zero, the default, blooms the whole scene, which is the physically based behaviour; raising it restricts the glow to the brightest parts, with a soft transition below the threshold. The value is in the scene-referred units the scene is rendered in, before the exposure and tone mapping applied when the bloom is composited, so a scene lit for an exposure far from 1 needs the threshold scaled to match.
Interface · category: Other
boxSize?: number
The size of the box
gap?: number
The gap between the box and the line
lineLength?: number
The length of the line
lineThickness?: number
The thickness of the line
tolerance?: number
The tolerance for intersection tests
Interface · category: Other
size?: number
The size of the box.
Interface · category: Other
callback?: (arg0: string, arg1: string) => void
Validation callback receiving chunk name and code.
defaultCodeGLSL?: string
Default GLSL code. If matches, no warning.
defaultCodeWGSL?: string
Default WGSL code. If matches, no warning.
message?: string
Deprecation message to display.
Interface · category: Other
Properties related to the color enhancement effect, a postprocessing technique that provides HDR-aware adjustments for shadows, highlights, vibrance, and dehaze. Shadows and highlights allow selective adjustment of dark and bright areas of the image, vibrance is a smart saturation that boosts less-saturated colors more than already-saturated ones, and dehaze removes atmospheric haze to increase clarity and contrast.
dehaze: number
The dehaze adjustment, -1 to 1 range. Positive values remove atmospheric haze, increasing clarity and contrast. Negative values add a haze effect. Defaults to 0.
enabled: boolean
Whether color enhancement is enabled. Defaults to false.
highlights: number
The highlight adjustment, -3 to 3 range. Uses an exponential curve where -3 gives 0.125x, 0 gives 1x, and +3 gives 8x brightness on bright areas. Defaults to 0.
midtones: number
The midtone adjustment, -1 to 1 range. Positive values brighten midtones, negative values darken midtones, with shadows and highlights more strongly preserved than by a linear exposure change. Defaults to 0.
shadows: number
The shadow adjustment, -3 to 3 range. Uses an exponential curve where -3 gives 0.125x, 0 gives 1x, and +3 gives 8x brightness on dark areas. Defaults to 0.
vibrance: number
The vibrance (smart saturation), -1 to 1 range. Positive values boost saturation of less-saturated colors more than already-saturated ones. Negative values desaturate. Defaults to 0.
Interface · category: Other
Properties related to the color lookup table (LUT) effect, a postprocessing technique used to apply a color transformation to the image. Two LUT slots are supported, which makes it easy to crossfade between two graded looks.
blend: number
Crossfade between the two graded results, 0-1 range. 0 shows only the
primary LUT, 1 shows only the secondary LUT, intermediate values produce a linear-space mix.
Only used when texture2 is set. Defaults to 0.
intensity: number
The strength of the primary LUT, blended against the original color, 0-1 range. Defaults to 1.
intensity2: number
The strength of the secondary LUT, blended against the original
color, 0-1 range. Only used when texture2 is set. Defaults to 1.
texture: Texture | null
The primary LUT texture. This must be a 256×16 2D "horizontal
strip" texture representing an unwrapped 16×16×16 3D LUT in Unreal Engine layout: 16 horizontal
slices along the blue axis, with each slice mapping red to the X-axis and green to the Y-axis.
Note that HALD LUTs (e.g. from ImageMagick) and Unity LUTs use different layouts and are not
compatible. The texture must be loaded with srgb: true (LUTs are authored in sRGB display
space — the Unreal / Photoshop workflow stores sRGB-encoded values indexed by sRGB-encoded
coordinates), mipmaps: false (sampled at LOD 0 only), and minFilter: FILTER_LINEAR /
magFilter: FILTER_LINEAR (bilinear filtering between LUT entries is required to avoid
visible banding). The engine emits a debug-build warning if any of these are misconfigured.
Defaults to null.
texture2: Texture | null
The optional secondary LUT texture, same format and
requirements as texture. When set, both LUTs are sampled and the two graded results are
crossfaded according to blend. Defaults to null.
Interface · category: Other
Properties related to Depth of Field (DOF), a technique used to simulate the optical effect where objects at certain distances appear sharp while others are blurred, enhancing the perception of focus and depth in the rendered scene.
blurRadius: number
The radius of the blur effect, typically 2-10 range. Defaults to 3.
blurRingPoints: number
The number of points in each ring of the blur effect, typically 3-8 range. Defaults to 5.
blurRings: number
The number of rings in the blur effect, typically 3-8 range. Defaults to 4.
enabled: boolean
Whether DoF is enabled. Defaults to false.
focusDistance: number
The distance at which the focus is set. Defaults to 100.
focusRange: number
The range around the focus distance where the focus is sharp. Defaults to 10.
highQuality: boolean
Whether the high quality implementation is used. This will have a higher performance cost, but will produce better quality results. Defaults to true.
nearBlur: boolean
Whether the near blur is enabled. Defaults to false.
Interface · category: Other
Properties related to the fringing effect, a chromatic aberration phenomenon where the red, green, and blue color channels diverge increasingly with greater distance from the center of the screen.
intensity: number
The intensity of the fringing effect, 0-100 range. Defaults to 0, making it disabled.
Interface · category: Other
disabled: Color
The disabled color.
guideBase: { x: Color; y: Color; z: Color }
The guide line colors.
Properties
guideOcclusion: number
The guide occlusion value. Defaults to 0.8.
shapeBase: { f: Color; x: Color; xyz: Color; y: Color; z: Color }
The axis colors.
Properties
shapeHover: { f: Color; x: Color; xyz: Color; y: Color; z: Color }
The hover colors.
Properties
Interface · category: Other
Properties related to the color grading effect, a postprocessing technique used to adjust and the visual tone of an image. This effect modifies brightness, contrast, saturation, and overall color balance to achieve a specific aesthetic or mood.
brightness: number
The brightness of the grading effect, 0-3 range. Defaults to 1.
contrast: number
The contrast of the grading effect, 0.5-1.5 range. Defaults to 1.
enabled: boolean
Whether grading is enabled. Defaults to false.
saturation: number
The saturation of the grading effect, 0-2 range. Defaults to 1.
tint: Color
The tint color of the grading effect. Defaults to white.
Interface · category: Other
Configuration object specifying a data binding for GSplatProcessor. Defines where to read from (source) or write to (destination) including the resource, component for instance textures, and which streams to access.
component?: GSplatComponent
Component for instance textures. If provided, resource is automatically resolved from the component.
resource?: GSplatResourceBase
Resource to read/write from.
streams?: string[]
Names of streams to read/write. For destination, this is required. For source, if omitted, all format streams except destination streams are used automatically, providing getCenter/getColor/etc functions. Specify explicitly to limit which streams are bound.
Interface · category: Other
format: number
The pixel format of the texture (e.g. PIXELFORMAT_RGBA32F). When used as an extra stream for work buffers or as a destination stream for GSplatProcessor, the format must be renderable as these textures are used as render targets. Ensure the format is renderable on all target devices. See Texture for details on renderable formats and device capabilities.
name: string
The name of the stream (used as texture uniform name).
storage?: number
Storage type: GSPLAT_STREAM_RESOURCE (default, shared across
instances) or GSPLAT_STREAM_INSTANCE (per-component instance). Note: Work buffer formats
(accessed via app.scene.gsplat.format) do not support GSPLAT_STREAM_INSTANCE.
Interface · category: Other
components: number
The number of components, 1 to 4.
name: string
The varying name. Must be a valid shader identifier.
type: number
The component data type: TYPE_FLOAT32, TYPE_INT32 or TYPE_UINT32.
Interface · category: Other
decimalPlaces?: number
Number of decimal places (defaults to none).
multiplier?: number
Multiplier applied to sampled values, for example to convert bytes to megabytes.
name: string
Display name.
stats: string[]
Path to data inside Application.stats.
unitsName?: string
Units (defaults to "").
watermark?: number
Watermark - shown as a line on the graph, useful for displaying a budget.
Interface · category: Other
cpu: MiniStatsProcessorOptions
CPU graph options.
cpuTimingMinSize?: number
Minimum size index at which to show CPU sub-timing graphs (script, anim, physics, render). Defaults to 1.
gpu: MiniStatsProcessorOptions
GPU graph options.
gpuTimingMinSize?: number
Minimum size index at which to show GPU pass timing graphs. Defaults to 1.
resourcesCollapsed?: boolean
Initially collapse the Resources section.
resourcesEnabled?: boolean
Show tracked resource counts in detailed views.
sizes: MiniStatsSizeOptions[]
Sizes of area to render individual graphs in and spacing between individual graphs.
startSizeIndex: number
Index into sizes array for initial setting.
stats: MiniStatsGraphOptions[]
Array of options to render additional graphs based on stats collected into Application.stats. Counters sourced exclusively from AppStats.user are displayed in a collapsible User section in the detailed views. Other additional counters are grouped under Engine, including DrawCalls and Frame. VRAM keeps its own category.
textRefreshRate: number
Text update interval and averaging window in ms (500 in the default options). Each update shows the arithmetic mean and peak of the frame samples collected since the previous update, then starts a new window. Graph history samples every frame.
vramTimingMinSize?: number
Minimum size index at which to show VRAM subcategory graphs. Defaults to 1.
Interface · category: Other
enabled: boolean
Whether to show the graph.
watermark: number
Watermark - shown as a line on the graph, useful for displaying a budget.
Interface · category: Other
detailed?: boolean
Show category headers and sub-counters. Defaults to true for sizes after the first, or when graphs are enabled.
graphs: boolean
Whether to show graphs.
height: number
Height of the graph area.
peak?: boolean
Show a peak column in the detailed view. Defaults to the graphs setting.
spacing: number
Spacing between graphs.
width: number
Width of the graph area.
Interface · category: Other
app: AppBase
The running AppBase.
asset: Asset<string> | undefined
The asset being loaded, if any.
basename: string
The lower-cased file name (for example 'lod-meta.json'), or an empty
string.
ext: string
The lower-cased file extension without a leading dot (for example 'json'),
or an empty string if there is none.
url: string | null
The original resource URL with any query string removed, or null.
Interface · category: Other
gap?: number
The gap between the plane and the center
size?: number
The size of the plane
Interface · category: Other
count: number
Given count.
name: string
E.g. 'vertex'.
properties: PlyProperty[]
The properties.
Interface · category: Other
byteSize: number
BYTES_PER_ELEMENT of given data type.
name: string
E.g. 'x', 'y', 'z', 'f_dc_0' etc.
storage: DataType
Data type, e.g. instance of Float32Array.
type: string
E.g. 'float'.
Interface · category: Other
Properties related to scene rendering, encompassing settings that control the rendering resolution, pixel format, multi-sampling for anti-aliasing, tone-mapping and similar.
renderFormats: number[]
The preferred render formats of the frame buffer, in order of preference. First format from this list that is supported by the hardware is used. When none of the formats are supported, PIXELFORMAT_RGBA8 is used, but this automatically disables bloom effect, which requires HDR format. The list can contain the following formats: PIXELFORMAT_111110F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F and PIXELFORMAT_RGBA8. Typically the default option should be used, which prefers the faster formats, but if higher dynamic range is needed, the list can be adjusted to prefer higher precision formats. Defaults to [PIXELFORMAT_111110F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F].
renderTargetScale: number
The scale of the render target, 0.1-1 range. This allows the scene to be rendered to a lower resolution render target as an optimization. The post-processing is also applied at this lower resolution. The image is then up-scaled to the full resolution and any UI rendering that follows is applied at the full resolution. Defaults to 1 which represents full resolution rendering.
samples: number
The number of samples of the RenderTarget used for the scene rendering, in 1-4 range. Value of 1 disables multisample anti-aliasing, other values enable anti-aliasing, Typically set to 1 when TAA is used, even though both anti-aliasing options can be used together at a higher cost. Defaults to 1.
sceneColorMap: boolean
Whether rendering generates a scene color map. Defaults to false.
sceneDepthMap: boolean
Whether rendering generates a scene depth map. Defaults to false.
sharpness: number
The sharpening intensity, 0-1 range. This can be used to increase the sharpness of the rendered image. Often used to counteract the blurriness of the TAA effect, but also blurriness caused by rendering to a lower resolution render target by using rendering.renderTargetScale property. Defaults to 0.
stencil: boolean
Whether the render buffer has a stencil buffer. Defaults to false.
toneMapping: number
The tone mapping. Can be:
Defaults to TONEMAP_LINEAR.
Interface · category: Other
canParse: (context: ParserContext) => boolean
Returns true if this parser can handle the described resource. Parsers are consulted newest-first; the first to return true is used.
handler?: ResourceHandler
Assigned by the owning handler on registration; available in
load/open (for example this.handler.fetch(...)).
load: (url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>) => void
Fetches (typically via this.handler.fetch) and produces the resource, then invokes the callback.
open?: (url: string, data: any, asset?: Asset<string>) => any
Optional. Called by the default
ResourceHandler#open when parsers are registered. Handlers that override open may call
it with an extended signature - for example the texture handler calls
open(url, data, device, textureOptions) on its parsers.
Interface · category: Other
app: AppBase
The AppBase that is running the script.
enabled?: boolean
True if the script instance is in running state.
entity: Entity
The Entity that the script is attached to.
Interface · category: Other
Defines the vertex and fragment shader source for ShaderMaterial, supporting both GLSL and WGSL formats. WebGL always uses the GLSL code. WebGPU prefers the WGSL code if available, otherwise it automatically transpiles the provided GLSL code at runtime.
attributes?: {}
Object detailing the mapping of vertex shader attribute names to semantics SEMANTIC_*. This enables the engine to match vertex buffer data as inputs to the shader. Defaults to undefined, which generates the default attributes.
fragmentGLSL?: string
The fragment shader code in GLSL.
fragmentOutputTypes?: string | string[]
Fragment shader output types, which default to vec4. Passing a string will set the output type for all color attachments. Passing an array will set the output type for each color attachment.
fragmentWGSL?: string
The fragment shader code in WGSL.
uniqueName: string
Unique name for the shader. If a shader with this name already exists, it will be returned instead of a new shader instance.
vertexGLSL?: string
The vertex shader code in GLSL.
vertexWGSL?: string
The vertex shader code in WGSL.
Interface · category: Other
axis?: string
The axis of the shape (e.g., 'x', 'y', 'z').
cull?: number
The culling mode of the shape.
defaultColor?: Color
The default color of the shape.
depth?: number
The depth of the shape. -1 = interpolated depth.
disabled?: boolean
Whether the shape is disabled.
disabledColor?: Color
The disabled color of the shape.
hoverColor?: Color
The hover color of the shape.
layers?: number[]
The layers the shape belongs to.
position?: Vec3
The position of the shape.
rotation?: Vec3
The rotation of the shape.
scale?: Vec3
The scale of the shape.
visible?: boolean
Whether the shape is visible.
Interface · category: Other
radius?: number
The radius of the sphere.
Interface · category: Other
Properties related to the Screen Space Ambient Occlusion (SSAO) effect, a postprocessing technique that approximates ambient occlusion by calculating how exposed each point in the screen space is to ambient light, enhancing depth perception and adding subtle shadowing in crevices and between objects.
blurEnabled: boolean
Whether the SSAO effect is blurred. Defaults to true.
intensity: number
The intensity of the SSAO effect, 0-1 range. Defaults to 0.5.
minAngle: number
The minimum angle of the SSAO effect, 1-90 range. Defaults to 10.
power: number
The power of the SSAO effect, 0.1-10 range. Defaults to 6.
radius: number
The radius of the SSAO effect, 0-100 range. Defaults to 30.
randomize: boolean
Whether the SSAO sampling is randomized. Useful when used instead of blur effect together with TAA. Defaults to false.
samples: number
The number of samples of the SSAO effect, 1-64 range. Defaults to 12.
scale: number
The scale of the SSAO effect, 0.5-1 range. Defaults to 1.
type: string
The type of the SSAO determines how it is applied in the rendering process. Defaults to SSAOTYPE_NONE. Can be:
Interface · category: Other
Properties related to temporal anti-aliasing (TAA), which is a technique used to reduce aliasing in the rendered image by blending multiple frames together over time.
enabled: boolean
Whether TAA is enabled. Defaults to false.
jitter: number
The intensity of the camera jitter, 0-1 range. The larger the value, the more jitter is applied to the camera, making the anti-aliasing effect more pronounced. This also makes the image more blurry, and rendering.sharpness parameter can be used to counteract. Defaults to 1.
Interface · category: Other
input?: VertexBuffer
A buffer read by the shader as a vertex stream.
output?: VertexBuffer
A buffer written by transform feedback.
Interface · category: Other
Properties related to the vignette effect, a postprocessing technique that darkens the image edges, creating a gradual falloff in brightness from the center outward. The effect can be also reversed, making the center of the image darker than the edges, by specifying the outer distance smaller than the inner distance.
color: Color
The color of the vignette effect. Defaults to black.
curvature: number
The curvature of the vignette effect, 0.01-10 range. The vignette is rendered using a rectangle with rounded corners, and this parameter controls the curvature of the corners. Value of 1 represents a circle. Smaller values make the corners more square, while larger values make them more rounded. Defaults to 0.5.
inner: number
The inner distance of the vignette effect measured from the center of the screen, 0-3 range. This is where the vignette effect starts. Value larger than 1 represents the value off screen, which allows more control. Defaults to 0.5, representing half the distance from center.
intensity: number
The intensity of the vignette effect, 0-1 range. Defaults to 0, making it disabled.
outer: number
The outer distance of the vignette effect measured from the center of the screen, 0-3 range. This is where the vignette reaches full intensity. Value larger than 1 represents the value off screen, which allows more control. Defaults to 1, representing the full screen.
Interface · category: Other
Properties related to volumetric fog, a raymarched height fog lit by a directional light. The
fog samples the light's cascaded shadow map along each view ray, forming visible shafts of
light. The raymarch runs at a reduced resolution and is blended into the scene before TAA, so
when TAA is enabled, its noise is temporally resolved to a smooth result. Optionally the
clustered omni and spot lights scatter light in the fog as well, see localOmniLights and
localSpotLights.
ambientColor: Color
The color of the ambient in-scattered light, which keeps the fog in shadowed areas visible. Defaults to white.
ambientIntensity: number
The intensity of the ambient in-scattered light. Defaults to 0.02.
anisotropy: number
The anisotropy of the scattering, 0-0.95 range. Larger values scatter more light forward, making the fog brighter when looking towards the light. Defaults to 0.6.
density: number
The fog density at the base height. Defaults to 0.01.
enabled: boolean
Whether the volumetric fog is enabled. Defaults to false.
extinction: number
A scale of how quickly the fog absorbs the light passing through it, without affecting how much light it scatters. A value of 1 is physically consistent, where the fog absorbs as much as it scatters, and distant fog and light shafts fade out exponentially with the density. Lower values keep them visible over a longer distance while the fog itself stays as bright, which is not physically correct but is often preferable. Defaults to 1.
heightBase: number
The world space height at which the fog density starts to fall off. Below it the density is constant. Defaults to 0.
heightFalloff: number
The exponential falloff of the fog density with height above the base height. Value of 0 makes the fog uniform. Defaults to 0.05.
intensity: number
The intensity of the light scattering. Defaults to 1.
light: LightComponent | null
The directional light providing the scattered light, or null when the fog is lit by the local lights and the ambient term only. When a light of a type other than directional is assigned, the effect is disabled. Defaults to null.
localIntensity: number
The intensity of the light scattering of the local lights. Defaults to 1.
localOmniLights: boolean
Whether the clustered omni lights scatter light in the fog. Each light adds a raymarch over the part of the view rays inside its volume, sampling the shadow and the cookie atlas of the clustered lighting, and so the cost scales with the screen space size of the light volumes. As an omni light fills its whole bounding sphere, its volume is typically much larger on the screen than the volume of a spot light. Requires clustered lighting, which is enabled by default. Individual lights can scatter more or less light using LightComponent#volumetricScattering. Defaults to false.
localSpotLights: boolean
Whether the clustered spot lights scatter light in the fog,
forming visible beams. See localOmniLights for details, both types are rendered the same way and
share the localIntensity and localSteps settings. Defaults to false.
localSteps: number
The number of raymarching steps taken inside the volume of each local light, 2-64 range. Defaults to 12.
maxDistance: number
The maximum world space distance the fog is raymarched to. Defaults to 300.
scale: number
The resolution scale of the fog texture relative to the scene render target, 0.25-1 range. Defaults to 0.5.
steps: number
The number of raymarching steps, 4-128 range. Higher values improve the quality at a higher performance cost. Defaults to 24.
tint: Color
The albedo of the fog. Defaults to white.
Type alias · category: Other
Callback used by Asset#ready and called when an asset is ready.
type AssetReadyCallback<K extends AssetType | string & {}> = (asset: Asset<K>) => void
Type alias · category: Other
type AssetResource<K extends AssetType | string & {}> = K extends AssetType ? AssetMap[K] : unknown
Type alias · category: Other
type AssetType = keyof AssetMap & string
Type alias · category: Other
Callback used by ResourceLoader#load and called when an asset is choosing a bundle to load from. Return a single bundle to ensure asset is loaded from it.
type BundlesFilterCallback = (bundles: Asset[]) => Asset
Type alias · category: Other
Callback used by CameraComponent#calculateTransform and CameraComponent#calculateProjection.
type CalculateMatrixCallback = (transformMatrix: Mat4, view: number) => void
Type alias · category: Other
Callback used by Layer to calculate the "sort distance" for a MeshInstance, which determines its place in the render order.
type CalculateSortDistanceCallback = (meshInstance: MeshInstance, cameraPosition: Vec3, cameraForward: Vec3) => number
Type alias · category: Other
Callback used by SceneRegistry#changeScene.
type ChangeSceneCallback = (err: string | null, entity?: Entity) => void
Type alias · category: Other
type ComponentMap = { [K in keyof Entity as NonNullable<Entity[K]> extends Component ? K : never]: NonNullable<Entity[K]> }
Type alias · category: Other
type ComponentName = keyof ComponentMap & string
Type alias · category: Other
type ComponentOptions<K extends ComponentName> = { [P in keyof MergedComponentOptions<K>]: MergedComponentOptions<K>[P] }
Type alias · category: Other
Callback used by AppBase#configure when configuration file is loaded and parsed (or an error occurs).
type ConfigureAppCallback = Object
Type alias · category: Other
Callback used by script.createLoadingScreen.
type CreateScreenCallback = (app: AppBase) => void
Type alias · category: Other
type DataType = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array
Type alias · category: Other
Callback used by AssetRegistry#filter to filter assets.
type FilterAssetCallback = (asset: Asset) => boolean
Type alias · category: Other
Callback used by GraphNode#find and GraphNode#findOne to search through a graph node and all of its descendants.
type FindNodeCallback = (node: GraphNode) => boolean
Type alias · category: Other
Callback used by GraphNode#forEach to iterate through a graph node and all of its descendants.
type ForEachNodeCallback = (node: GraphNode) => void
Type alias · category: Other
type GizmoAxis = "x" | "y" | "z" | "yz" | "xz" | "xy" | "xyz" | "f"
Type alias · category: Other
type GizmoDragMode = "show" | "hide" | "selected"
Type alias · category: Other
type GizmoSpace = "local" | "world"
Type alias · category: Other
Callback used by EventHandler functions. Note the callback is limited to 8 arguments.
type HandleEventCallback = (arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any) => void
Type alias · category: Other
Callback used by Http#get, Http#post, Http#put, Http#del, and Http#request.
type HttpResponseCallback = (err: number | string | Error | null, response?: any) => void
Type alias · category: Other
Callback used by AssetRegistry#loadFromUrl and called when an asset is loaded (or an error occurs).
type LoadAssetCallback<K extends AssetType | string & {}> = (err: string | null, asset?: Asset<K>) => void
Type alias · category: Other
Callback used by SceneRegistry#loadSceneHierarchy.
type LoadHierarchyCallback = (err: string | null, entity?: Entity) => void
Type alias · category: Other
Callback used by SceneRegistry#loadScene.
type LoadSceneCallback = (err: string | null, entity?: Entity) => void
Type alias · category: Other
Callback used by SceneRegistry#loadSceneData.
type LoadSceneDataCallback = (err: string | null, sceneItem?: SceneRegistryItem) => void
Type alias · category: Other
Callback used by SceneRegistry#loadSceneSettings.
type LoadSettingsCallback = (err: string | null) => void
Type alias · category: Other
Callback used by Mouse#enablePointerLock and Mouse#disablePointerLock.
type LockMouseCallback = () => void
Type alias · category: Other
Callback used by WasmModule.setConfig.
type ModuleErrorCallback = (error: string) => void
Type alias · category: Other
Callback used by WasmModule.getInstance.
type ModuleInstanceCallback = (moduleInstance: any) => void
Type alias · category: Other
type NumericArray = number[] | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array
Type alias · category: Other
Callback used by AppBase#preload when all assets (marked as 'preload') are loaded.
type PreloadAppCallback = Object
Type alias · category: Other
Callback used by ResourceHandler#load when a resource is loaded (or an error occurs).
type ResourceHandlerCallback = (err: string | null, response?: any) => void
Type alias · category: Other
Callback used by ResourceLoader#load when a resource is loaded (or an error occurs).
type ResourceLoaderCallback = (err: string | null, resource?: any) => void
Type alias · category: Other
Callback used by StandardMaterial#onUpdateShader.
type UpdateShaderCallback = (options: StandardMaterialOptions) => StandardMaterialOptions
Type alias · category: Other
Callback used by XrAnchors#create.
type XrAnchorCreateCallback = (err: Error | null, anchor: XrAnchor | null) => void
Type alias · category: Other
Callback used by XrAnchor#forget.
type XrAnchorForgetCallback = (err: Error | null) => void
Type alias · category: Other
Callback used by XrAnchor#persist.
type XrAnchorPersistCallback = (err: Error | null, uuid: string | null) => void
Type alias · category: Other
Callback used by XrManager#start and XrManager#end.
type XrErrorCallback = (err: Error | null) => void
Type alias · category: Other
Callback used by XrHitTest#start and XrInputSource#hitTestStart.
type XrHitTestStartCallback = (err: Error | null, hitTestSource: XrHitTestSource | null) => void
Type alias · category: Other
Callback used by XrManager#initiateRoomCapture.
type XrRoomCaptureCallback = (err: Error | null) => void
Function · category: Other
basisInitialize(config?: object): void
Initialize the Basis transcode worker.
Parameters
config (object, optional): The Basis configuration.
config.eagerWorkers (boolean, optional): Use eager workers (default is true). When enabled, jobs
are assigned to workers immediately, independent of their work load. This can result in
unbalanced workloads, however there is no delay between jobs. If disabled, new jobs are assigned
to workers only when their previous job has completed. This will result in balanced workloads
across workers, however workers can be idle for a short time between jobs.config.fallbackUrl (string, optional): URL of the fallback script to use when wasm modules
aren't supported.config.glueUrl (string, optional): URL of glue script.config.lazyInit (boolean, optional): Wait for first transcode request before initializing Basis
(default is false). Otherwise initialize Basis immediately.config.maxRetries (number, optional): Number of http load retry attempts. Defaults to 5.config.numWorkers (number, optional): Number of workers to use for transcoding (default is 1).
While it is possible to improve transcode performance using multiple workers, this will likely
depend on the runtime platform. For example, desktop will likely benefit from more workers
compared to mobile. Also keep in mind that it takes time to initialize workers and increasing
this value could impact application startup time. Make sure to test your application performance
on all target platforms when changing this parameter.config.rgbaPriority (string[], optional): Array of texture compression formats in priority order
for textures with alpha. The supported compressed formats are: 'astc', 'atc', 'dxt', 'etc1',
'etc2', 'pvr'.config.rgbPriority (string[], optional): Array of texture compression formats in priority order
for textures without alpha. The supported compressed formats are: 'astc', 'atc', 'dxt', 'etc1',
'etc2', 'pvr'.config.wasmUrl (string, optional): URL of the wasm module.Function · category: Other
dracoDecode(buffer: ArrayBuffer, callback: Function): boolean
Enqueue a buffer for decoding.
Parameters
buffer (ArrayBuffer): The draco data to decode.callback (Function): Callback function to receive decoded result.Returns boolean: True if the draco worker was initialized and false otherwise.
Function · category: Other
dracoInitialize(config?: object): void
Initialize the Draco mesh decoder.
Parameters
config (object, optional): The Draco decoder configuration.
config.jsUrl (string, optional): URL of glue script.config.lazyInit (boolean, optional): Wait for first decode request before initializing workers
(default is false). Otherwise initialize workers immediately.config.numWorkers (number, optional): Number of workers to use for decoding (default is 1).config.wasmUrl (string, optional): URL of the wasm module.Function · category: Other
create(): string
Create an RFC4122 version 4 compliant GUID.
Returns string: A new GUID.
Function · category: Other
extractPath(pathname: string): string
Return the path without file name. If path is relative path, start with period.
Parameters
pathname (string): The full path to process.Returns string: The path without a last element from list split by slash.
Example
path.extractPath("path/to/file.txt"); // returns "./path/to"
path.extractPath("./path/to/file.txt"); // returns "./path/to"
path.extractPath("../path/to/file.txt"); // returns "../path/to"
path.extractPath("/path/to/file.txt"); // returns "/path/to"
Function · category: Other
getBasename(pathname: string): string
Return the basename of the path. That is the second element of the pair returned by passing path into path.split.
Parameters
pathname (string): The path to process.Returns string: The basename.
Example
path.getBasename("/path/to/file.txt"); // returns "file.txt"
path.getBasename("/path/to/dir"); // returns "dir"
Function · category: Other
getDirectory(pathname: string): string
Get the directory name from the path. This is everything up to the final instance of path.delimiter.
Parameters
pathname (string): The path to get the directory from.Returns string: The directory part of the path.
Function · category: Other
getExtension(pathname: string): string
Return the extension of the path. Pop the last value of a list after path is split by question mark and comma.
Parameters
pathname (string): The path to process.Returns string: The extension.
Example
path.getExtension("/path/to/file.txt"); // returns ".txt"
path.getExtension("/path/to/file.jpg"); // returns ".jpg"
path.getExtension("/path/to/file.txt?function=getExtension"); // returns ".txt"
Function · category: Other
isRelativePath(pathname: string): boolean
Check if a string s is relative path.
Parameters
pathname (string): The path to process.Returns boolean: True if s doesn't start with slash and doesn't include colon and double
slash.
Example
path.isRelativePath("file.txt"); // returns true
path.isRelativePath("path/to/file.txt"); // returns true
path.isRelativePath("./path/to/file.txt"); // returns true
path.isRelativePath("../path/to/file.jpg"); // returns true
path.isRelativePath("/path/to/file.jpg"); // returns false
path.isRelativePath("http://path/to/file.jpg"); // returns false
Function · category: Other
join(...sections: string[]): string
Join two or more sections of file path together, inserting a delimiter if needed.
Parameters
sections (string[]): Sections of the path to join.Returns string: The joined file path.
Example
const joinedPath = path.join('foo', 'bar');
console.log(joinedPath); // Prints 'foo/bar'
Example
const joinedPath = path.join('alpha', 'beta', 'gamma');
console.log(joinedPath); // Prints 'alpha/beta/gamma'
Function · category: Other
normalize(pathname: string): string
Normalize the path by removing '.' and '..' instances.
Parameters
pathname (string): The path to normalize.Returns string: The normalized path.
Function · category: Other
split(pathname: string): string[]
Split the pathname path into a pair [head, tail] where tail is the final part of the path after the last delimiter and head is everything leading up to that. tail will never contain a slash.
Parameters
pathname (string): The path to split.Returns string[]: The split path which is an array of two strings, the path and the
filename.
Function · category: Other
format(s: string, ...args: any[]): string
Return a string with {n} replaced with the n-th argument.
Parameters
s (string): The string to format.args (any[]): All other arguments are substituted into the string.Returns string: The formatted string.
Example
const s = string.format("Hello {0}", "world");
console.log(s); // Prints "Hello world"
Function · category: Other
getCodePoint(string: string, i?: number): number
Get the code point number for a character in a string. Polyfill for
[codePointAt]https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt.
Parameters
string (string): The string to get the code point from.i (number, optional): The index in the string.Returns number: The code point value for the character in the string.
Function · category: Other
getCodePoints(string: string): number[]
Gets an array of all code points in a string.
Parameters
string (string): The string to get code points from.Returns number[]: The code points in the string.
Function · category: Other
getSymbols(string: string): string[]
Gets an array of all grapheme clusters (visible symbols) in a string. This is needed because some symbols (such as emoji or accented characters) are actually made up of multiple character codes. See here for more info.
Parameters
string (string): The string to break into symbols.Returns string[]: The symbols in the string.
Variable · category: Other
The character that separates path segments.
const delimiter: string = '/'
Variable · category: Other
True if running on an Android device.
const android: boolean
Variable · category: Other
Convenience boolean indicating whether we're running in the browser.
const browser: boolean
Variable · category: Other
True if running on a desktop or laptop device.
const desktop: boolean
Variable · category: Other
String identifying the current runtime environment. Either 'browser', 'node' or 'worker'.
const environment: "worker" | "browser" | "node" = environment
Variable · category: Other
True if the platform supports gamepads.
const gamepads: boolean = gamepads
Variable · category: Other
The global object. This will be the window object when running in a browser and the global object when running in nodejs and self when running in a worker.
const global: any
Variable · category: Other
True if running on an iOS device.
const ios: boolean
Variable · category: Other
True if running on a mobile or tablet device.
const mobile: boolean
Variable · category: Other
True if the platform supports touch input.
const touch: boolean = touch
Variable · category: Other
True if the platform supports Web Workers.
const workers: boolean = workers
Variable · category: Other
True if running on an Xbox device.
const xbox: boolean = xbox
Variable · category: Other
The engine revision number. This is the Git hash of the last commit made to the branch from which the engine was built.
const revision: "$_CURRENT_SDK_REVISION" = '$_CURRENT_SDK_REVISION'
Variable · category: Other
The engine version number. This is in semantic versioning format (MAJOR.MINOR.PATCH).
const version: "$_CURRENT_SDK_VERSION" = '$_CURRENT_SDK_VERSION'
Namespace · category: Other
Basically a very large random number (128-bit) which means the probability of creating two that clash is vanishingly small. GUIDs are used as the unique identifiers for Entities.
Namespace · category: Other
File path API.
Namespace · category: Other
Global namespace that stores flags regarding platform environment and features support.
Example
if (platform.touch) {
// touch is supported
}
Namespace · category: Other
Extended String API.
78 interfaces and type aliases without a category, mostly the types of other symbols' parameters and results.
679 constants by category, grouped by prefix, with their values. The page of each constant, with its description, is at https://api.playcanvas.com/engine/variables/<NAME>.md.
ANIM_*: ANIM_BLEND_1D = '1D', ANIM_BLEND_2D_CARTESIAN = '2D_CARTESIAN', ANIM_BLEND_2D_DIRECTIONAL = '2D_DIRECTIONAL', ANIM_BLEND_DIRECT = 'DIRECT', ANIM_EQUAL_TO = 'EQUAL_TO', ANIM_GREATER_THAN = 'GREATER_THAN', ANIM_GREATER_THAN_EQUAL_TO = 'GREATER_THAN_EQUAL_TO', ANIM_INTERRUPTION_NEXT = 'NEXT_STATE', ANIM_INTERRUPTION_NEXT_PREV = 'NEXT_STATE_PREV_STATE', ANIM_INTERRUPTION_NONE = 'NONE', ANIM_INTERRUPTION_PREV = 'PREV_STATE', ANIM_INTERRUPTION_PREV_NEXT = 'PREV_STATE_NEXT_STATE', ANIM_LAYER_ADDITIVE = 'ADDITIVE', ANIM_LAYER_OVERWRITE = 'OVERWRITE', ANIM_LESS_THAN = 'LESS_THAN', ANIM_LESS_THAN_EQUAL_TO = 'LESS_THAN_EQUAL_TO', ANIM_NOT_EQUAL_TO = 'NOT_EQUAL_TO', ANIM_PARAMETER_BOOLEAN = 'BOOLEAN', ANIM_PARAMETER_FLOAT = 'FLOAT', ANIM_PARAMETER_INTEGER = 'INTEGER', ANIM_PARAMETER_TRIGGER = 'TRIGGER', ANIM_STATE_ANY = 'ANY', ANIM_STATE_END = 'END', ANIM_STATE_START = 'START'INTERPOLATION_*: INTERPOLATION_CUBIC = 2, INTERPOLATION_LINEAR = 1, INTERPOLATION_STEP = 0ASSET_*: ASSET_ANIMATION = 'animation', ASSET_AUDIO = 'audio', ASSET_CONTAINER = 'container', ASSET_CSS = 'css', ASSET_CUBEMAP = 'cubemap', ASSET_HTML = 'html', ASSET_IMAGE = 'image', ASSET_JSON = 'json', ASSET_MATERIAL = 'material', ASSET_MODEL = 'model', ASSET_SCRIPT = 'script', ASSET_SHADER = 'shader', ASSET_TEXT = 'text', ASSET_TEXTURE = 'texture', ASSET_TEXTUREATLAS = 'textureatlas'TRACEID_*: TRACEID_ASSETS = 'Assets', TRACEID_BINDGROUP_ALLOC = 'BindGroupAlloc', TRACEID_BINDGROUPFORMAT_ALLOC = 'BindGroupFormatAlloc', TRACEID_BUFFERS = 'Buffers', TRACEID_COMPUTEPIPELINE_ALLOC = 'ComputePipelineAlloc', TRACEID_ELEMENT = 'Element', TRACEID_GPU_TIMINGS = 'GpuTimings', TRACEID_MATERIAL_UPDATE = 'MaterialUpdate', TRACEID_OCTREE_RESOURCES = 'OctreeResources', TRACEID_PIPELINELAYOUT_ALLOC = 'PipelineLayoutAlloc', TRACEID_RENDER_ACTION = 'RenderAction', TRACEID_RENDER_FRAME = 'RenderFrame', TRACEID_RENDER_FRAME_TIME = 'RenderFrameTime', TRACEID_RENDER_PASS = 'RenderPass', TRACEID_RENDER_PASS_DETAIL = 'RenderPassDetail', TRACEID_RENDER_QUEUE = 'RenderQueue', TRACEID_RENDER_TARGET_ALLOC = 'RenderTargetAlloc', TRACEID_RENDERPIPELINE_ALLOC = 'RenderPipelineAlloc', TRACEID_SHADER_ALLOC = 'ShaderAlloc', TRACEID_SHADER_COMPILE = 'ShaderCompile', TRACEID_TEXTURE_ALLOC = 'TextureAlloc', TRACEID_TEXTURES = 'Textures', TRACEID_VRAM_IB = 'VRAM.Ib', TRACEID_VRAM_SB = 'VRAM.Sb', TRACEID_VRAM_TEXTURE = 'VRAM.Texture', TRACEID_VRAM_VB = 'VRAM.Vb'ADDRESS_*: ADDRESS_CLAMP_TO_EDGE = 1, ADDRESS_MIRRORED_REPEAT = 2, ADDRESS_REPEAT = 0ASPECT_*: ASPECT_AUTO = 0, ASPECT_MANUAL = 1BAKE_*: BAKE_COLOR = 0, BAKE_COLORDIR = 1BLEND_*: BLEND_ADDITIVE = 1, BLEND_ADDITIVEALPHA = 6, BLEND_MAX = 10, BLEND_MIN = 9, BLEND_MULTIPLICATIVE = 5, BLEND_MULTIPLICATIVE2X = 7, BLEND_NONE = 3, BLEND_NORMAL = 2, BLEND_PREMULTIPLIED = 4, BLEND_SCREEN = 8, BLEND_SUBTRACTIVE = 0BLENDEQUATION_*: BLENDEQUATION_ADD = 0, BLENDEQUATION_MAX = 4, BLENDEQUATION_MIN = 3, BLENDEQUATION_REVERSE_SUBTRACT = 2, BLENDEQUATION_SUBTRACT = 1BLENDMODE_*: BLENDMODE_CONSTANT = 11, BLENDMODE_DST_ALPHA = 9, BLENDMODE_DST_COLOR = 4, BLENDMODE_ONE = 1, BLENDMODE_ONE_MINUS_CONSTANT = 12, BLENDMODE_ONE_MINUS_DST_ALPHA = 10, BLENDMODE_ONE_MINUS_DST_COLOR = 5, BLENDMODE_ONE_MINUS_SRC_ALPHA = 8, BLENDMODE_ONE_MINUS_SRC_COLOR = 3, BLENDMODE_ONE_MINUS_SRC1_ALPHA = 16, BLENDMODE_ONE_MINUS_SRC1_COLOR = 14, BLENDMODE_SRC_ALPHA = 6, BLENDMODE_SRC_ALPHA_SATURATE = 7, BLENDMODE_SRC_COLOR = 2, BLENDMODE_SRC1_ALPHA = 15, BLENDMODE_SRC1_COLOR = 13, BLENDMODE_ZERO = 0BLUR_*: BLUR_BOX = 0, BLUR_GAUSSIAN = 1BUFFER_*: BUFFER_DYNAMIC = 1, BUFFER_GPUDYNAMIC = 3, BUFFER_STATIC = 0, BUFFER_STREAM = 2BUFFERUSAGE_*: BUFFERUSAGE_COPY_DST = 0x0008, BUFFERUSAGE_COPY_SRC = 0x0004, BUFFERUSAGE_INDEX = 0x0010, BUFFERUSAGE_READ = 0x0001, BUFFERUSAGE_UNIFORM = 0x0040, BUFFERUSAGE_VERTEX = 0x0020, BUFFERUSAGE_WRITE = 0x0002CLEARFLAG_*: CLEARFLAG_COLOR = 1, CLEARFLAG_DEPTH = 2, CLEARFLAG_STENCIL = 4CUBEFACE_*: CUBEFACE_NEGX = 1, CUBEFACE_NEGY = 3, CUBEFACE_NEGZ = 5, CUBEFACE_POSX = 0, CUBEFACE_POSY = 2, CUBEFACE_POSZ = 4CUBEPROJ_*: CUBEPROJ_BOX = 1, CUBEPROJ_NONE = 0CULLFACE_*: CULLFACE_BACK = 1, CULLFACE_FRONT = 2, CULLFACE_NONE = 0DEPTHRESOLVE_*: DEPTHRESOLVE_MAX = 'max', DEPTHRESOLVE_MIN = 'min', DEPTHRESOLVE_SAMPLE0 = 'sample0'DETAILMODE_*: DETAILMODE_ADD = 'add', DETAILMODE_MAX = 'max', DETAILMODE_MIN = 'min', DETAILMODE_MUL = 'mul', DETAILMODE_OVERLAY = 'overlay', DETAILMODE_SCREEN = 'screen'DEVICETYPE_*: DEVICETYPE_NULL = 'null', DEVICETYPE_WEBGL2 = 'webgl2', DEVICETYPE_WEBGL2_BARE = 'webgl2:bare', DEVICETYPE_WEBGPU = 'webgpu', DEVICETYPE_WEBGPU_BARE = 'webgpu:bare'DISPLAYFORMAT_*: DISPLAYFORMAT_HDR = 'hdr', DISPLAYFORMAT_LDR = 'ldr', DISPLAYFORMAT_LDR_SRGB = 'ldr_srgb'DITHER_*: DITHER_BAYER16 = 'bayer16', DITHER_BAYER2 = 'bayer2', DITHER_BAYER4 = 'bayer4', DITHER_BAYER8 = 'bayer8', DITHER_BLUENOISE = 'bluenoise', DITHER_IGNNOISE = 'ignnoise', DITHER_NONE = 'none'EMITTERSHAPE_*: EMITTERSHAPE_BOX = 0, EMITTERSHAPE_SPHERE = 1FILTER_*: FILTER_LINEAR = 1, FILTER_LINEAR_MIPMAP_LINEAR = 5, FILTER_LINEAR_MIPMAP_NEAREST = 4, FILTER_NEAREST = 0, FILTER_NEAREST_MIPMAP_LINEAR = 3, FILTER_NEAREST_MIPMAP_NEAREST = 2FOG_*: FOG_EXP = 'exp', FOG_EXP2 = 'exp2', FOG_LINEAR = 'linear', FOG_NONE = 'none'FRESNEL_*: FRESNEL_NONE = 0, FRESNEL_SCHLICK = 2FRONTFACE_*: FRONTFACE_CCW = 0, FRONTFACE_CW = 1FUNC_*: FUNC_ALWAYS = 7, FUNC_EQUAL = 2, FUNC_GREATER = 4, FUNC_GREATEREQUAL = 6, FUNC_LESS = 1, FUNC_LESSEQUAL = 3, FUNC_NEVER = 0, FUNC_NOTEQUAL = 5GAMMA_*: GAMMA_NONE = 0, GAMMA_SRGB = 1GSPLAT_*: GSPLAT_BUDGET_LIMIT = 'limit', GSPLAT_BUDGET_TARGET = 'target', GSPLAT_DEBUG_AABBS = 4, GSPLAT_DEBUG_LOD = 1, GSPLAT_DEBUG_NODE_AABBS = 5, GSPLAT_DEBUG_NONE = 0, GSPLAT_DEBUG_SH_UPDATE = 2, GSPLAT_RENDERER_AUTO = 0, GSPLAT_RENDERER_RASTER_CPU_SORT = 1, GSPLAT_RENDERER_RASTER_GPU_SORT = 2, GSPLAT_STREAM_INSTANCE = 1, GSPLAT_STREAM_RESOURCE = 0GSPLATDATA_*: GSPLATDATA_COMPACT = 'compact', GSPLATDATA_LARGE = 'large'INDEXFORMAT_*: INDEXFORMAT_UINT16 = 1, INDEXFORMAT_UINT32 = 2, INDEXFORMAT_UINT8 = 0LAYERID_*: LAYERID_DEPTH = 1, LAYERID_IMMEDIATE = 3, LAYERID_SKYBOX = 2, LAYERID_UI = 4, LAYERID_WORLD = 0LIGHTFALLOFF_*: LIGHTFALLOFF_INVERSESQUARED = 1, LIGHTFALLOFF_LINEAR = 0LIGHTSHAPE_*: LIGHTSHAPE_DISK = 2, LIGHTSHAPE_PUNCTUAL = 0, LIGHTSHAPE_RECT = 1, LIGHTSHAPE_SPHERE = 3LIGHTTYPE_*: LIGHTTYPE_DIRECTIONAL = 0, LIGHTTYPE_OMNI = 1, LIGHTTYPE_SPOT = 2ORIENTATION_*: ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1PARALLAX_*: PARALLAX_OCCLUSION = 'occlusion', PARALLAX_OFFSET = 'offset'PARTICLEORIENTATION_*: PARTICLEORIENTATION_EMITTER = 2, PARTICLEORIENTATION_SCREEN = 0, PARTICLEORIENTATION_WORLD = 1PARTICLESORT_*: PARTICLESORT_DISTANCE = 1, PARTICLESORT_NEWER_FIRST = 2, PARTICLESORT_NONE = 0, PARTICLESORT_OLDER_FIRST = 3PIXELFORMAT_*: PIXELFORMAT_111110F = 18, PIXELFORMAT_ATC_RGB = 29, PIXELFORMAT_ATC_RGBA = 30, PIXELFORMAT_BC6F = 65, PIXELFORMAT_BC6UF = 66, PIXELFORMAT_BC7 = 67, PIXELFORMAT_BC7_SRGBA = 68, PIXELFORMAT_DEPTH = 16, PIXELFORMAT_DEPTH16 = 69, PIXELFORMAT_DEPTHSTENCIL = 17, PIXELFORMAT_DXT1 = 8, PIXELFORMAT_DXT1_SRGB = 54, PIXELFORMAT_DXT3 = 9, PIXELFORMAT_DXT3_SRGBA = 55, PIXELFORMAT_DXT5 = 10, PIXELFORMAT_DXT5_SRGBA = 56, PIXELFORMAT_ETC1 = 21, PIXELFORMAT_ETC2_RGB = 22, PIXELFORMAT_ETC2_RGBA = 23, PIXELFORMAT_ETC2_SRGB = 61, PIXELFORMAT_ETC2_SRGBA = 62, PIXELFORMAT_PVRTC_2BPP_RGB_1 = 24, PIXELFORMAT_PVRTC_2BPP_RGBA_1 = 25, PIXELFORMAT_PVRTC_4BPP_RGB_1 = 26, PIXELFORMAT_PVRTC_4BPP_RGBA_1 = 27, PIXELFORMAT_R16F = 50, PIXELFORMAT_R16I = 34, PIXELFORMAT_R16U = 35, PIXELFORMAT_R32F = 15, PIXELFORMAT_R32I = 36, PIXELFORMAT_R32U = 37, PIXELFORMAT_R8 = 52, PIXELFORMAT_R8I = 32, PIXELFORMAT_R8U = 33, PIXELFORMAT_RG16F = 51, PIXELFORMAT_RG16I = 40, PIXELFORMAT_RG16U = 41, PIXELFORMAT_RG32F = 70, PIXELFORMAT_RG32I = 42, PIXELFORMAT_RG32U = 43, PIXELFORMAT_RG8 = 53, PIXELFORMAT_RG8I = 38, PIXELFORMAT_RG8S = 72, PIXELFORMAT_RG8U = 39, PIXELFORMAT_RGB10A2 = 74, PIXELFORMAT_RGB10A2U = 75, PIXELFORMAT_RGB16F = 11, PIXELFORMAT_RGB32F = 13, PIXELFORMAT_RGB565 = 3, PIXELFORMAT_RGB8 = 6, PIXELFORMAT_RGB9E5 = 71, PIXELFORMAT_RGBA16F = 12, PIXELFORMAT_RGBA16I = 46, PIXELFORMAT_RGBA16U = 47, PIXELFORMAT_RGBA32F = 14, PIXELFORMAT_RGBA32I = 48, PIXELFORMAT_RGBA32U = 49, PIXELFORMAT_RGBA4 = 5, PIXELFORMAT_RGBA5551 = 4, PIXELFORMAT_RGBA8 = 7, PIXELFORMAT_RGBA8I = 44, PIXELFORMAT_RGBA8S = 73, PIXELFORMAT_RGBA8U = 45, PIXELFORMAT_SRGB8 = 19, PIXELFORMAT_SRGBA8 = 20PRIMITIVE_*: PRIMITIVE_LINELOOP = 2, PRIMITIVE_LINES = 1, PRIMITIVE_LINESTRIP = 3, PRIMITIVE_POINTS = 0, PRIMITIVE_TRIANGLES = 4, PRIMITIVE_TRIFAN = 6, PRIMITIVE_TRISTRIP = 5PROJECTION_*: PROJECTION_ORTHOGRAPHIC = 1, PROJECTION_PERSPECTIVE = 0RENDERSTYLE_*: RENDERSTYLE_POINTS = 2, RENDERSTYLE_SOLID = 0, RENDERSTYLE_WIREFRAME = 1RENDERTARGET_*: RENDERTARGET_ORIGIN_BOTTOM = 'bottom', RENDERTARGET_ORIGIN_NATIVE = 'native', RENDERTARGET_ORIGIN_TOP = 'top'SAMPLETYPE_*: SAMPLETYPE_DEPTH = 2, SAMPLETYPE_FLOAT = 0, SAMPLETYPE_INT = 3, SAMPLETYPE_UINT = 4, SAMPLETYPE_UNFILTERABLE_FLOAT = 1SEMANTIC_*: SEMANTIC_ATTR0 = 'ATTR0', SEMANTIC_ATTR1 = 'ATTR1', SEMANTIC_ATTR10 = 'ATTR10', SEMANTIC_ATTR11 = 'ATTR11', SEMANTIC_ATTR12 = 'ATTR12', SEMANTIC_ATTR13 = 'ATTR13', SEMANTIC_ATTR14 = 'ATTR14', SEMANTIC_ATTR15 = 'ATTR15', SEMANTIC_ATTR2 = 'ATTR2', SEMANTIC_ATTR3 = 'ATTR3', SEMANTIC_ATTR4 = 'ATTR4', SEMANTIC_ATTR5 = 'ATTR5', SEMANTIC_ATTR6 = 'ATTR6', SEMANTIC_ATTR7 = 'ATTR7', SEMANTIC_ATTR8 = 'ATTR8', SEMANTIC_ATTR9 = 'ATTR9', SEMANTIC_BLENDINDICES = 'BLENDINDICES', SEMANTIC_BLENDWEIGHT = 'BLENDWEIGHT', SEMANTIC_COLOR = 'COLOR', SEMANTIC_NORMAL = 'NORMAL', SEMANTIC_POSITION = 'POSITION', SEMANTIC_TANGENT = 'TANGENT', SEMANTIC_TEXCOORD0 = 'TEXCOORD0', SEMANTIC_TEXCOORD1 = 'TEXCOORD1', SEMANTIC_TEXCOORD2 = 'TEXCOORD2', SEMANTIC_TEXCOORD3 = 'TEXCOORD3', SEMANTIC_TEXCOORD4 = 'TEXCOORD4', SEMANTIC_TEXCOORD5 = 'TEXCOORD5', SEMANTIC_TEXCOORD6 = 'TEXCOORD6', SEMANTIC_TEXCOORD7 = 'TEXCOORD7'SHADER_FORWARD = 0SHADERLANGUAGE_*: SHADERLANGUAGE_GLSL = 'glsl', SHADERLANGUAGE_WGSL = 'wgsl'SHADERPASS_*: SHADERPASS_ALBEDO = 'debug_albedo', SHADERPASS_AO = 'debug_ao', SHADERPASS_EMISSION = 'debug_emission', SHADERPASS_FORWARD = 'forward', SHADERPASS_GLOSS = 'debug_gloss', SHADERPASS_LIGHTING = 'debug_lighting', SHADERPASS_METALNESS = 'debug_metalness', SHADERPASS_OPACITY = 'debug_opacity', SHADERPASS_SPECULARITY = 'debug_specularity', SHADERPASS_UV0 = 'debug_uv0', SHADERPASS_WORLDNORMAL = 'debug_world_normal'SHADERSTAGE_*: SHADERSTAGE_COMPUTE = 4, SHADERSTAGE_FRAGMENT = 2, SHADERSTAGE_VERTEX = 1SHADOW_*: SHADOW_CASCADE_0 = 1, SHADOW_CASCADE_1 = 2, SHADOW_CASCADE_2 = 4, SHADOW_CASCADE_3 = 8, SHADOW_CASCADE_ALL = 255, SHADOW_PCF1_16F = 7, SHADOW_PCF1_32F = 5, SHADOW_PCF3_16F = 8, SHADOW_PCF3_32F = 0, SHADOW_PCF5_16F = 9, SHADOW_PCF5_32F = 4, SHADOW_PCSS_32F = 6, SHADOW_VSM_16F = 2, SHADOW_VSM_32F = 3SHADOWUPDATE_*: SHADOWUPDATE_NONE = 0, SHADOWUPDATE_REALTIME = 2, SHADOWUPDATE_THISFRAME = 1SKYTYPE_*: SKYTYPE_BOX = 'box', SKYTYPE_DOME = 'dome', SKYTYPE_INFINITE = 'infinite'SORTMODE_*: SORTMODE_BACK2FRONT = 3, SORTMODE_FRONT2BACK = 4, SORTMODE_MANUAL = 1, SORTMODE_MATERIALMESH = 2, SORTMODE_NONE = 0SPECOCC_*: SPECOCC_AO = 1, SPECOCC_GLOSSDEPENDENT = 2, SPECOCC_NONE = 0SPRITE_*: SPRITE_RENDERMODE_SIMPLE = 0, SPRITE_RENDERMODE_SLICED = 1, SPRITE_RENDERMODE_TILED = 2SPRITETYPE_*: SPRITETYPE_ANIMATED = 'animated', SPRITETYPE_SIMPLE = 'simple'SSAOTYPE_*: SSAOTYPE_COMBINE = 'combine', SSAOTYPE_LIGHTING = 'lighting', SSAOTYPE_NONE = 'none'STENCILOP_*: STENCILOP_DECREMENT = 5, STENCILOP_DECREMENTWRAP = 6, STENCILOP_INCREMENT = 3, STENCILOP_INCREMENTWRAP = 4, STENCILOP_INVERT = 7, STENCILOP_KEEP = 0, STENCILOP_REPLACE = 2, STENCILOP_ZERO = 1TEXTUREDIMENSION_*: TEXTUREDIMENSION_1D = '1d', TEXTUREDIMENSION_2D = '2d', TEXTUREDIMENSION_2D_ARRAY = '2d-array', TEXTUREDIMENSION_3D = '3d', TEXTUREDIMENSION_CUBE = 'cube', TEXTUREDIMENSION_CUBE_ARRAY = 'cube-array'TEXTURELOCK_*: TEXTURELOCK_NONE = 0, TEXTURELOCK_READ = 1, TEXTURELOCK_WRITE = 2TEXTUREPROJECTION_*: TEXTUREPROJECTION_CUBE = 'cube', TEXTUREPROJECTION_EQUIRECT = 'equirect', TEXTUREPROJECTION_NONE = 'none', TEXTUREPROJECTION_OCTAHEDRAL = 'octahedral'TEXTURETYPE_*: TEXTURETYPE_DEFAULT = 'default', TEXTURETYPE_RGBE = 'rgbe', TEXTURETYPE_RGBM = 'rgbm', TEXTURETYPE_RGBP = 'rgbp', TEXTURETYPE_SWIZZLEGGGR = 'swizzleGGGR'TONEMAP_*: TONEMAP_ACES = 3, TONEMAP_ACES2 = 4, TONEMAP_FILMIC = 1, TONEMAP_HEJL = 2, TONEMAP_LINEAR = 0, TONEMAP_NEUTRAL = 5, TONEMAP_NONE = 6TRANSFORM_*: TRANSFORM_FEEDBACK_INTERLEAVED = 0, TRANSFORM_FEEDBACK_SEPARATE = 1TYPE_*: TYPE_FLOAT16 = 7, TYPE_FLOAT32 = 6, TYPE_INT16 = 2, TYPE_INT32 = 4, TYPE_INT8 = 0, TYPE_UINT16 = 3, TYPE_UINT32 = 5, TYPE_UINT8 = 1UNIFORMTYPE_*: UNIFORMTYPE_BOOL = 0, UNIFORMTYPE_BVEC2 = 9, UNIFORMTYPE_BVEC3 = 10, UNIFORMTYPE_BVEC4 = 11, UNIFORMTYPE_FLOAT = 2, UNIFORMTYPE_INT = 1, UNIFORMTYPE_IVEC2 = 6, UNIFORMTYPE_IVEC3 = 7, UNIFORMTYPE_IVEC4 = 8, UNIFORMTYPE_MAT2 = 12, UNIFORMTYPE_MAT3 = 13, UNIFORMTYPE_MAT4 = 14, UNIFORMTYPE_UINT = 26, UNIFORMTYPE_UVEC2 = 27, UNIFORMTYPE_UVEC3 = 28, UNIFORMTYPE_UVEC4 = 29, UNIFORMTYPE_VEC2 = 3, UNIFORMTYPE_VEC3 = 4, UNIFORMTYPE_VEC4 = 5VIEW_*: VIEW_CENTER = 0, VIEW_LEFT = 1, VIEW_RIGHT = 2WORKBUFFER_*: WORKBUFFER_UPDATE_ALWAYS = 2, WORKBUFFER_UPDATE_AUTO = 0, WORKBUFFER_UPDATE_ONCE = 1KEY_*: KEY_0 = 48, KEY_1 = 49, KEY_2 = 50, KEY_3 = 51, KEY_4 = 52, KEY_5 = 53, KEY_6 = 54, KEY_7 = 55, KEY_8 = 56, KEY_9 = 57, KEY_A = 65, KEY_ADD = 107, KEY_ALT = 18, KEY_B = 66, KEY_BACK_SLASH = 220, KEY_BACKSPACE = 8, KEY_C = 67, KEY_CAPS_LOCK = 20, KEY_CLOSE_BRACKET = 221, KEY_COMMA = 188, KEY_CONTEXT_MENU = 93, KEY_CONTROL = 17, KEY_D = 68, KEY_DECIMAL = 110, KEY_DELETE = 46, KEY_DIVIDE = 111, KEY_DOWN = 40, KEY_E = 69, KEY_END = 35, KEY_ENTER = 13, KEY_EQUAL = 61, KEY_ESCAPE = 27, KEY_F = 70, KEY_F1 = 112, KEY_F10 = 121, KEY_F11 = 122, KEY_F12 = 123, KEY_F2 = 113, KEY_F3 = 114, KEY_F4 = 115, KEY_F5 = 116, KEY_F6 = 117, KEY_F7 = 118, KEY_F8 = 119, KEY_F9 = 120, KEY_G = 71, KEY_H = 72, KEY_HOME = 36, KEY_I = 73, KEY_INSERT = 45, KEY_J = 74, KEY_K = 75, KEY_L = 76, KEY_LEFT = 37, KEY_M = 77, KEY_META = 224, KEY_MULTIPLY = 106, KEY_N = 78, KEY_NUMPAD_0 = 96, KEY_NUMPAD_1 = 97, KEY_NUMPAD_2 = 98, KEY_NUMPAD_3 = 99, KEY_NUMPAD_4 = 100, KEY_NUMPAD_5 = 101, KEY_NUMPAD_6 = 102, KEY_NUMPAD_7 = 103, KEY_NUMPAD_8 = 104, KEY_NUMPAD_9 = 105, KEY_O = 79, KEY_OPEN_BRACKET = 219, KEY_P = 80, KEY_PAGE_DOWN = 34, KEY_PAGE_UP = 33, KEY_PAUSE = 19, KEY_PERIOD = 190, KEY_PRINT_SCREEN = 44, KEY_Q = 81, KEY_R = 82, KEY_RETURN = 13, KEY_RIGHT = 39, KEY_S = 83, KEY_SEMICOLON = 59, KEY_SEPARATOR = 108, KEY_SHIFT = 16, KEY_SLASH = 191, KEY_SPACE = 32, KEY_SUBTRACT = 109, KEY_T = 84, KEY_TAB = 9, KEY_U = 85, KEY_UP = 38, KEY_V = 86, KEY_W = 87, KEY_WINDOWS = 91, KEY_X = 88, KEY_Y = 89, KEY_Z = 90MOUSEBUTTON_*: MOUSEBUTTON_LEFT = 0, MOUSEBUTTON_MIDDLE = 1, MOUSEBUTTON_NONE = -1, MOUSEBUTTON_RIGHT = 2PAD_*: PAD_1 = 0, PAD_2 = 1, PAD_3 = 2, PAD_4 = 3, PAD_DOWN = 13, PAD_FACE_1 = 0, PAD_FACE_2 = 1, PAD_FACE_3 = 2, PAD_FACE_4 = 3, PAD_L_SHOULDER_1 = 4, PAD_L_SHOULDER_2 = 6, PAD_L_STICK_BUTTON = 10, PAD_L_STICK_X = 0, PAD_L_STICK_Y = 1, PAD_LEFT = 14, PAD_R_SHOULDER_1 = 5, PAD_R_SHOULDER_2 = 7, PAD_R_STICK_BUTTON = 11, PAD_R_STICK_X = 2, PAD_R_STICK_Y = 3, PAD_RIGHT = 15, PAD_SELECT = 8, PAD_START = 9, PAD_UP = 12, PAD_VENDOR = 16XRPAD_*: XRPAD_A = 4, XRPAD_B = 5, XRPAD_SQUEEZE = 1, XRPAD_STICK_BUTTON = 3, XRPAD_STICK_X = 2, XRPAD_STICK_Y = 3, XRPAD_TOUCHPAD_BUTTON = 2, XRPAD_TOUCHPAD_X = 0, XRPAD_TOUCHPAD_Y = 1, XRPAD_TRIGGER = 0CURVE_*: CURVE_LINEAR = 0, CURVE_SMOOTHSTEP = 1, CURVE_SPLINE = 4, CURVE_STEP = 5math.DEG_TO_RADmath.RAD_TO_DEGBODYTYPE_*: BODYTYPE_DYNAMIC = 'dynamic', BODYTYPE_KINEMATIC = 'kinematic', BODYTYPE_STATIC = 'static'JOINTTYPE_*: JOINTTYPE_6DOF = '6dof', JOINTTYPE_BALL = 'ball', JOINTTYPE_FIXED = 'fixed', JOINTTYPE_HINGE = 'hinge', JOINTTYPE_SLIDER = 'slider'MOTION_*: MOTION_FREE = 'free', MOTION_LIMITED = 'limited', MOTION_LOCKED = 'locked'DISTANCE_*: DISTANCE_EXPONENTIAL = 'exponential', DISTANCE_INVERSE = 'inverse', DISTANCE_LINEAR = 'linear'BUTTON_*: BUTTON_TRANSITION_MODE_SPRITE_CHANGE = 1, BUTTON_TRANSITION_MODE_TINT = 0ELEMENTTYPE_*: ELEMENTTYPE_GROUP = 'group', ELEMENTTYPE_IMAGE = 'image', ELEMENTTYPE_TEXT = 'text'FITMODE_*: FITMODE_CONTAIN = 'contain', FITMODE_COVER = 'cover', FITMODE_STRETCH = 'stretch'FITTING_*: FITTING_BOTH = 3, FITTING_NONE = 0, FITTING_SHRINK = 2, FITTING_STRETCH = 1SCALEMODE_*: SCALEMODE_BLEND = 'blend', SCALEMODE_NONE = 'none'SCROLL_*: SCROLL_MODE_BOUNCE = 1, SCROLL_MODE_CLAMP = 0, SCROLL_MODE_INFINITE = 2SCROLLBAR_*: SCROLLBAR_VISIBILITY_SHOW_ALWAYS = 0, SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED = 1XRDEPTHSENSINGFORMAT_*: XRDEPTHSENSINGFORMAT_F32 = 'float32', XRDEPTHSENSINGFORMAT_L8A8 = 'luminance-alpha', XRDEPTHSENSINGFORMAT_R16U = 'unsigned-short'XRDEPTHSENSINGUSAGE_*: XRDEPTHSENSINGUSAGE_CPU = 'cpu-optimized', XRDEPTHSENSINGUSAGE_GPU = 'gpu-optimized'XREYE_*: XREYE_LEFT = 'left', XREYE_NONE = 'none', XREYE_RIGHT = 'right'XRHAND_*: XRHAND_LEFT = 'left', XRHAND_NONE = 'none', XRHAND_RIGHT = 'right'XRSPACE_*: XRSPACE_BOUNDEDFLOOR = 'bounded-floor', XRSPACE_LOCAL = 'local', XRSPACE_LOCALFLOOR = 'local-floor', XRSPACE_UNBOUNDED = 'unbounded', XRSPACE_VIEWER = 'viewer'XRTARGETRAY_*: XRTARGETRAY_GAZE = 'gaze', XRTARGETRAY_POINTER = 'tracked-pointer', XRTARGETRAY_SCREEN = 'screen'XRTRACKABLE_*: XRTRACKABLE_MESH = 'mesh', XRTRACKABLE_PLANE = 'plane', XRTRACKABLE_POINT = 'point'XRTYPE_*: XRTYPE_AR = 'immersive-ar', XRTYPE_INLINE = 'inline', XRTYPE_VR = 'immersive-vr'FILLMODE_*: FILLMODE_FILL_WINDOW = 'FILL_WINDOW', FILLMODE_KEEP_ASPECT = 'KEEP_ASPECT', FILLMODE_NONE = 'NONE'LINECAP_*: LINECAP_BUTT = 0, LINECAP_ROUND = 2, LINECAP_SQUARE = 1LINEJOIN_*: LINEJOIN_BEVEL = 1, LINEJOIN_MITER = 0, LINEJOIN_ROUND = 2LINEWIDTH_*: LINEWIDTH_SCREEN = 0, LINEWIDTH_WORLD = 1RESOLUTION_*: RESOLUTION_AUTO = 'AUTO', RESOLUTION_FIXED = 'FIXED'string.ASCII_*: string.ASCII_LETTERS = ASCII_LETTERS, string.ASCII_LOWERCASE = ASCII_LOWERCASE, string.ASCII_UPPERCASE = ASCII_UPPERCASEVariable · category: Math
Conversion factor between degrees and radians.
const DEG_TO_RAD: number
Variable · category: Math
Conversion factor between radians and degrees.
const RAD_TO_DEG: number
Variable · category: Other
All ASCII letters.
const ASCII_LETTERS: string = ASCII_LETTERS
Variable · category: Other
All lowercase letters.
const ASCII_LOWERCASE: string = ASCII_LOWERCASE
Variable · category: Other
All uppercase letters.
const ASCII_UPPERCASE: string = ASCII_UPPERCASE
Variable · category: Graphics
Clamps texture coordinate to the range 0 to 1.
const ADDRESS_CLAMP_TO_EDGE: 1 = 1
Variable · category: Graphics
Texture coordinate to be set to the fractional part if the integer part is even. If the integer part is odd, then the texture coordinate is set to 1 minus the fractional part.
const ADDRESS_MIRRORED_REPEAT: 2 = 2
Variable · category: Graphics
Ignores the integer part of texture coordinates, using only the fractional part.
const ADDRESS_REPEAT: 0 = 0
Variable · category: Animation
const ANIM_BLEND_1D: string = '1D'
Variable · category: Animation
const ANIM_BLEND_2D_CARTESIAN: string = '2D_CARTESIAN'
Variable · category: Animation
const ANIM_BLEND_2D_DIRECTIONAL: string = '2D_DIRECTIONAL'
Variable · category: Animation
const ANIM_BLEND_DIRECT: string = 'DIRECT'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '==='.
const ANIM_EQUAL_TO: "EQUAL_TO" = 'EQUAL_TO'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '>'.
const ANIM_GREATER_THAN: "GREATER_THAN" = 'GREATER_THAN'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '>='.
const ANIM_GREATER_THAN_EQUAL_TO: "GREATER_THAN_EQUAL_TO" = 'GREATER_THAN_EQUAL_TO'
Variable · category: Animation
Used to set the anim state graph transition interruption source as the next state only.
const ANIM_INTERRUPTION_NEXT: "NEXT_STATE" = 'NEXT_STATE'
Variable · category: Animation
Used to set the anim state graph transition interruption sources as the next state followed by the previous state.
const ANIM_INTERRUPTION_NEXT_PREV: "NEXT_STATE_PREV_STATE" = 'NEXT_STATE_PREV_STATE'
Variable · category: Animation
Used to set the anim state graph transition interruption source to no state.
const ANIM_INTERRUPTION_NONE: "NONE" = 'NONE'
Variable · category: Animation
Used to set the anim state graph transition interruption source as the previous state only.
const ANIM_INTERRUPTION_PREV: "PREV_STATE" = 'PREV_STATE'
Variable · category: Animation
Used to set the anim state graph transition interruption sources as the previous state followed by the next state.
const ANIM_INTERRUPTION_PREV_NEXT: "PREV_STATE_NEXT_STATE" = 'PREV_STATE_NEXT_STATE'
Variable · category: Animation
Used to indicate that a layers animations should blend additively with previous layers.
const ANIM_LAYER_ADDITIVE: "ADDITIVE" = 'ADDITIVE'
Variable · category: Animation
Used to indicate that a layers animations should overwrite all previous layers.
const ANIM_LAYER_OVERWRITE: "OVERWRITE" = 'OVERWRITE'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '<'.
const ANIM_LESS_THAN: "LESS_THAN" = 'LESS_THAN'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '<='.
const ANIM_LESS_THAN_EQUAL_TO: "LESS_THAN_EQUAL_TO" = 'LESS_THAN_EQUAL_TO'
Variable · category: Animation
Used to set an anim state graph transition condition predicate as '!=='.
const ANIM_NOT_EQUAL_TO: "NOT_EQUAL_TO" = 'NOT_EQUAL_TO'
Variable · category: Animation
Used to set an anim state graph parameter as type boolean.
const ANIM_PARAMETER_BOOLEAN: "BOOLEAN" = 'BOOLEAN'
Variable · category: Animation
Used to set an anim state graph parameter as type float.
const ANIM_PARAMETER_FLOAT: "FLOAT" = 'FLOAT'
Variable · category: Animation
Used to set an anim state graph parameter as type integer.
const ANIM_PARAMETER_INTEGER: "INTEGER" = 'INTEGER'
Variable · category: Animation
Used to set an anim state graph parameter as type trigger.
const ANIM_PARAMETER_TRIGGER: "TRIGGER" = 'TRIGGER'
Variable · category: Animation
Used to indicate any state in an anim state graph layer.
const ANIM_STATE_ANY: "ANY" = 'ANY'
Variable · category: Animation
The ending state in an anim state graph layer.
const ANIM_STATE_END: "END" = 'END'
Variable · category: Animation
The starting state in an anim state graph layer.
const ANIM_STATE_START: "START" = 'START'
Variable · category: Graphics
Automatically set aspect ratio to current render target's width divided by height.
const ASPECT_AUTO: 0 = 0
Variable · category: Graphics
Use the manual aspect ratio value.
const ASPECT_MANUAL: 1 = 1
Variable · category: Asset
Asset type name for animation.
const ASSET_ANIMATION: "animation" = 'animation'
Variable · category: Asset
Asset type name for audio.
const ASSET_AUDIO: "audio" = 'audio'
Variable · category: Asset
Asset type name for a container.
const ASSET_CONTAINER: "container" = 'container'
Variable · category: Asset
Asset type name for CSS.
const ASSET_CSS: "css" = 'css'
Variable · category: Asset
Asset type name for cubemap.
const ASSET_CUBEMAP: "cubemap" = 'cubemap'
Variable · category: Asset
Asset type name for HTML.
const ASSET_HTML: "html" = 'html'
Variable · category: Asset · deprecated
Asset type name for image.
Deprecated: No resource handler is registered for 'image' assets. Use ASSET_TEXTURE
instead.
const ASSET_IMAGE: "image" = 'image'
Variable · category: Asset
Asset type name for json.
const ASSET_JSON: "json" = 'json'
Variable · category: Asset
Asset type name for material.
const ASSET_MATERIAL: "material" = 'material'
Variable · category: Asset
Asset type name for model.
const ASSET_MODEL: "model" = 'model'
Variable · category: Asset
Asset type name for script.
const ASSET_SCRIPT: "script" = 'script'
Variable · category: Asset
Asset type name for shader.
const ASSET_SHADER: "shader" = 'shader'
Variable · category: Asset
Asset type name for text.
const ASSET_TEXT: "text" = 'text'
Variable · category: Asset
Asset type name for texture.
const ASSET_TEXTURE: "texture" = 'texture'
Variable · category: Asset
Asset type name for textureatlas.
const ASSET_TEXTUREATLAS: "textureatlas" = 'textureatlas'
Variable · category: Graphics
Single color lightmap.
const BAKE_COLOR: 0 = 0
Variable · category: Graphics
Single color lightmap + dominant light direction (used for bump/specular).
const BAKE_COLORDIR: 1 = 1
Variable · category: Graphics
Add the color of the source fragment to the destination fragment and write the result to the frame buffer.
const BLEND_ADDITIVE: 1 = 1
Variable · category: Graphics
Same as BLEND_ADDITIVE except the source RGB is multiplied by the source alpha.
const BLEND_ADDITIVEALPHA: 6 = 6
Variable · category: Graphics
Maximum color.
const BLEND_MAX: 10 = 10
Variable · category: Graphics
Minimum color.
const BLEND_MIN: 9 = 9
Variable · category: Graphics
Multiply the color of the source fragment by the color of the destination fragment and write the result to the frame buffer.
const BLEND_MULTIPLICATIVE: 5 = 5
Variable · category: Graphics
Multiplies colors and doubles the result.
const BLEND_MULTIPLICATIVE2X: 7 = 7
Variable · category: Graphics
Disable blending.
const BLEND_NONE: 3 = 3
Variable · category: Graphics
Enable simple translucency for materials such as glass. This is equivalent to enabling a source blend mode of BLENDMODE_SRC_ALPHA and a destination blend mode of BLENDMODE_ONE_MINUS_SRC_ALPHA.
const BLEND_NORMAL: 2 = 2
Variable · category: Graphics
Similar to BLEND_NORMAL expect the source fragment is assumed to have already been multiplied by the source alpha value.
const BLEND_PREMULTIPLIED: 4 = 4
Variable · category: Graphics
Softer version of additive.
const BLEND_SCREEN: 8 = 8
Variable · category: Graphics
Subtract the color of the source fragment from the destination fragment and write the result to the frame buffer.
const BLEND_SUBTRACTIVE: 0 = 0
Variable · category: Graphics
Add the results of the source and destination fragment multiplies.
const BLENDEQUATION_ADD: 0 = 0
Variable · category: Graphics
Use the largest value.
const BLENDEQUATION_MAX: 4 = 4
Variable · category: Graphics
Use the smallest value.
const BLENDEQUATION_MIN: 3 = 3
Variable · category: Graphics
Reverse and subtract the results of the source and destination fragment multiplies.
const BLENDEQUATION_REVERSE_SUBTRACT: 2 = 2
Variable · category: Graphics
Subtract the results of the source and destination fragment multiplies.
const BLENDEQUATION_SUBTRACT: 1 = 1
Variable · category: Graphics
Multiplies all fragment components by a constant.
const BLENDMODE_CONSTANT: 11 = 11
Variable · category: Graphics
Multiply all fragment components by the alpha value of the destination fragment.
const BLENDMODE_DST_ALPHA: 9 = 9
Variable · category: Graphics
Multiply all fragment components by the components of the destination fragment.
const BLENDMODE_DST_COLOR: 4 = 4
Variable · category: Graphics
Multiply all fragment components by one.
const BLENDMODE_ONE: 1 = 1
Variable · category: Graphics
Multiplies all fragment components by 1 minus a constant.
const BLENDMODE_ONE_MINUS_CONSTANT: 12 = 12
Variable · category: Graphics
Multiply all fragment components by one minus the alpha value of the destination fragment.
const BLENDMODE_ONE_MINUS_DST_ALPHA: 10 = 10
Variable · category: Graphics
Multiply all fragment components by one minus the components of the destination fragment.
const BLENDMODE_ONE_MINUS_DST_COLOR: 5 = 5
Variable · category: Graphics
Multiply all fragment components by one minus the alpha value of the source fragment.
const BLENDMODE_ONE_MINUS_SRC_ALPHA: 8 = 8
Variable · category: Graphics
Multiply all fragment components by one minus the components of the source fragment.
const BLENDMODE_ONE_MINUS_SRC_COLOR: 3 = 3
Variable · category: Graphics
Multiply all fragment components by one minus the alpha value of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.
const BLENDMODE_ONE_MINUS_SRC1_ALPHA: 16 = 16
Variable · category: Graphics
Multiply all fragment components by one minus the components of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.
const BLENDMODE_ONE_MINUS_SRC1_COLOR: 14 = 14
Variable · category: Graphics
Multiply all fragment components by the alpha value of the source fragment.
const BLENDMODE_SRC_ALPHA: 6 = 6
Variable · category: Graphics
Multiply all fragment components by the alpha value of the source fragment.
const BLENDMODE_SRC_ALPHA_SATURATE: 7 = 7
Variable · category: Graphics
Multiply all fragment components by the components of the source fragment.
const BLENDMODE_SRC_COLOR: 2 = 2
Variable · category: Graphics
Multiply all fragment components by the alpha value of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.
const BLENDMODE_SRC1_ALPHA: 15 = 15
Variable · category: Graphics
Multiply all fragment components by the components of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.
const BLENDMODE_SRC1_COLOR: 13 = 13
Variable · category: Graphics
Multiply all fragment components by zero.
const BLENDMODE_ZERO: 0 = 0
Variable · category: Graphics
Box filter.
const BLUR_BOX: 0 = 0
Variable · category: Graphics
Gaussian filter. May look smoother than box, but requires more samples.
const BLUR_GAUSSIAN: 1 = 1
Variable · category: Physics
Rigid body is simulated according to applied forces.
const BODYTYPE_DYNAMIC: "dynamic" = 'dynamic'
Variable · category: Physics
Rigid body has infinite mass and does not respond to forces. It is moved by setting the position and rotation of its entity.
const BODYTYPE_KINEMATIC: "kinematic" = 'kinematic'
Variable · category: Physics
Rigid body has infinite mass and cannot move.
const BODYTYPE_STATIC: "static" = 'static'
Variable · category: Graphics
The data store contents will be modified repeatedly and used many times.
const BUFFER_DYNAMIC: 1 = 1
Variable · category: Graphics
The data store contents will be modified repeatedly on the GPU and used many times. Optimal for transform feedback usage.
const BUFFER_GPUDYNAMIC: 3 = 3
Variable · category: Graphics
The data store contents will be modified once and used many times.
const BUFFER_STATIC: 0 = 0
Variable · category: Graphics
The data store contents will be modified once and used at most a few times.
const BUFFER_STREAM: 2 = 2
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a destination of a copy operation, or as a target of a write operation.
const BUFFERUSAGE_COPY_DST: 8 = 0x0008
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a source of a copy operation.
const BUFFERUSAGE_COPY_SRC: 4 = 0x0004
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as an index buffer.
const BUFFERUSAGE_INDEX: 16 = 0x0010
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to make it available for read access by CPU.
const BUFFERUSAGE_READ: 1 = 0x0001
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as an uniform buffer.
const BUFFERUSAGE_UNIFORM: 64 = 0x0040
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a vertex buffer.
const BUFFERUSAGE_VERTEX: 32 = 0x0020
Variable · category: Graphics
A flag utilized during the construction of a StorageBuffer to make it available for write access by CPU.
const BUFFERUSAGE_WRITE: 2 = 0x0002
Variable · category: User Interface
Specifies different sprites for the hover, pressed and inactive states.
const BUTTON_TRANSITION_MODE_SPRITE_CHANGE: 1 = 1
Variable · category: User Interface
Specifies different color tints for the hover, pressed and inactive states.
const BUTTON_TRANSITION_MODE_TINT: 0 = 0
Variable · category: Graphics
Clear the color buffer.
const CLEARFLAG_COLOR: 1 = 1
Variable · category: Graphics
Clear the depth buffer.
const CLEARFLAG_DEPTH: 2 = 2
Variable · category: Graphics
Clear the stencil buffer.
const CLEARFLAG_STENCIL: 4 = 4
Variable · category: Graphics
The negative X face of a cubemap.
const CUBEFACE_NEGX: 1 = 1
Variable · category: Graphics
The negative Y face of a cubemap.
const CUBEFACE_NEGY: 3 = 3
Variable · category: Graphics
The negative Z face of a cubemap.
const CUBEFACE_NEGZ: 5 = 5
Variable · category: Graphics
The positive X face of a cubemap.
const CUBEFACE_POSX: 0 = 0
Variable · category: Graphics
The positive Y face of a cubemap.
const CUBEFACE_POSY: 2 = 2
Variable · category: Graphics
The positive Z face of a cubemap.
const CUBEFACE_POSZ: 4 = 4
Variable · category: Graphics
The cube map is box-projected based on a world space axis-aligned bounding box.
const CUBEPROJ_BOX: 1 = 1
Variable · category: Graphics
The cube map is treated as if it is infinitely far away.
const CUBEPROJ_NONE: 0 = 0
Variable · category: Graphics
Triangles facing away from the view direction are culled.
const CULLFACE_BACK: 1 = 1
Variable · category: Graphics
Triangles facing the view direction are culled.
const CULLFACE_FRONT: 2 = 2
Variable · category: Graphics
No triangles are culled.
const CULLFACE_NONE: 0 = 0
Variable · category: Math
A linear interpolation scheme.
const CURVE_LINEAR: 0 = 0
Variable · category: Math
A smooth step interpolation scheme.
const CURVE_SMOOTHSTEP: 1 = 1
Variable · category: Math
Cardinal spline interpolation scheme. For a Catmull-Rom spline, specify a curve tension of 0.5.
const CURVE_SPLINE: 4 = 4
Variable · category: Math
A stepped interpolator that does not perform any blending.
const CURVE_STEP: 5 = 5
Variable · category: Graphics
The depth value of the multisampled depth buffer is resolved by taking the maximum value of all samples - with a standard depth buffer this selects the farthest surface. See RenderTarget#depthResolveMode.
const DEPTHRESOLVE_MAX: "max" = 'max'
Variable · category: Graphics
The depth value of the multisampled depth buffer is resolved by taking the minimum value of all samples - with a standard depth buffer this selects the nearest surface, which is a conservative and stable choice for depth-consuming effects. This is the default. See RenderTarget#depthResolveMode.
const DEPTHRESOLVE_MIN: "min" = 'min'
Variable · category: Graphics
The depth value of the multisampled depth buffer is resolved by taking its sample at index 0. See RenderTarget#depthResolveMode.
const DEPTHRESOLVE_SAMPLE0: "sample0" = 'sample0'
Variable · category: Graphics
Add together the primary and secondary colors.
const DETAILMODE_ADD: "add" = 'add'
Variable · category: Graphics
Select whichever of the primary and secondary colors is lighter, component-wise.
const DETAILMODE_MAX: "max" = 'max'
Variable · category: Graphics
Select whichever of the primary and secondary colors is darker, component-wise.
const DETAILMODE_MIN: "min" = 'min'
Variable · category: Graphics
Multiply together the primary and secondary colors.
const DETAILMODE_MUL: "mul" = 'mul'
Variable · category: Graphics
Multiplies or screens the colors, depending on the primary color.
const DETAILMODE_OVERLAY: "overlay" = 'overlay'
Variable · category: Graphics
Softer version of DETAILMODE_ADD.
const DETAILMODE_SCREEN: "screen" = 'screen'
Variable · category: Graphics
A Null device type.
const DEVICETYPE_NULL: "null" = 'null'
Variable · category: Graphics
A WebGL 2 device type.
const DEVICETYPE_WEBGL2: "webgl2" = 'webgl2'
Variable · category: Graphics
A WebGL 2 device type with only the extensions available on 99%+ of devices exposed, and capabilities clamped to the values 99%+ of devices report. Useful for testing engine behavior on the most constrained WebGL 2 devices (e.g. no multi-draw, no float texture filtering, no compressed textures, 4k textures).
const DEVICETYPE_WEBGL2_BARE: "webgl2:bare" = 'webgl2:bare'
Variable · category: Graphics
A WebGPU device type.
const DEVICETYPE_WEBGPU: "webgpu" = 'webgpu'
Variable · category: Graphics
A WebGPU device type with no optional features requested and default spec limits. Useful for testing engine behavior on the most constrained WebGPU devices (e.g. no compressed textures, no float32-filterable, no timestamp-query).
const DEVICETYPE_WEBGPU_BARE: "webgpu:bare" = 'webgpu:bare'
Variable · category: Graphics
Display format for high dynamic range data, using 16bit floating point values. Note: This is supported on WebGPU platform only, and ignored on other platforms. On displays without HDR support, it silently falls back to DISPLAYFORMAT_LDR. Use GraphicsDevice.isHdr to see if the HDR format is used. When it is, it's recommended to use TONEMAP_NONE for the tonemapping mode, to avoid it clipping the high dynamic range.
const DISPLAYFORMAT_HDR: "hdr" = 'hdr'
Variable · category: Graphics
Display format for low dynamic range data. This is always supported; however, due to the cost, it does not implement linear alpha blending on the main framebuffer. Instead, alpha blending occurs in sRGB space.
const DISPLAYFORMAT_LDR: "ldr" = 'ldr'
Variable · category: Graphics
Display format for low dynamic range data in the sRGB color space. This format correctly implements linear alpha blending on the main framebuffer, with the alpha blending occurring in linear space. This is currently supported on WebGPU platform only. On unsupported platforms, it silently falls back to DISPLAYFORMAT_LDR.
const DISPLAYFORMAT_LDR_SRGB: "ldr_srgb" = 'ldr_srgb'
Variable · category: Sound
Exponential distance model.
const DISTANCE_EXPONENTIAL: "exponential" = 'exponential'
Variable · category: Sound
Inverse distance model.
const DISTANCE_INVERSE: "inverse" = 'inverse'
Variable · category: Sound
Linear distance model.
const DISTANCE_LINEAR: "linear" = 'linear'
Variable · category: Graphics
Opacity is dithered using a Bayer 16 matrix.
const DITHER_BAYER16: "bayer16" = 'bayer16'
Variable · category: Graphics
Opacity is dithered using a Bayer 2 matrix.
const DITHER_BAYER2: "bayer2" = 'bayer2'
Variable · category: Graphics
Opacity is dithered using a Bayer 4 matrix.
const DITHER_BAYER4: "bayer4" = 'bayer4'
Variable · category: Graphics
Opacity is dithered using a Bayer 8 matrix.
const DITHER_BAYER8: "bayer8" = 'bayer8'
Variable · category: Graphics
Opacity is dithered using a blue noise.
const DITHER_BLUENOISE: "bluenoise" = 'bluenoise'
Variable · category: Graphics
Opacity is dithered using an interleaved gradient noise.
const DITHER_IGNNOISE: "ignnoise" = 'ignnoise'
Variable · category: Graphics
Opacity dithering is disabled.
const DITHER_NONE: "none" = 'none'
Variable · category: User Interface
A ElementComponent that contains child ElementComponents.
const ELEMENTTYPE_GROUP: "group" = 'group'
Variable · category: User Interface
A ElementComponent that displays an image.
const ELEMENTTYPE_IMAGE: "image" = 'image'
Variable · category: User Interface
A ElementComponent that displays text.
const ELEMENTTYPE_TEXT: "text" = 'text'
Variable · category: Graphics
Box shape parameterized by emitterExtents. Initial velocity is directed towards local Z axis.
const EMITTERSHAPE_BOX: 0 = 0
Variable · category: Graphics
Sphere shape parameterized by emitterRadius. Initial velocity is directed outwards from the center.
const EMITTERSHAPE_SPHERE: 1 = 1
Variable · category: Other
When resizing the window the size of the canvas will change to fill the window exactly.
const FILLMODE_FILL_WINDOW: "FILL_WINDOW" = 'FILL_WINDOW'
Variable · category: Other
When resizing the window the size of the canvas will change to fill the window as best it can, while maintaining the same aspect ratio.
const FILLMODE_KEEP_ASPECT: "KEEP_ASPECT" = 'KEEP_ASPECT'
Variable · category: Other
When resizing the window the size of the canvas will not change.
const FILLMODE_NONE: "NONE" = 'NONE'
Variable · category: Graphics
Bilinear filtering.
const FILTER_LINEAR: 1 = 1
Variable · category: Graphics
Linearly interpolate both the mipmap levels and between texels.
const FILTER_LINEAR_MIPMAP_LINEAR: 5 = 5
Variable · category: Graphics
Use the nearest neighbor after linearly interpolating between mipmap levels.
const FILTER_LINEAR_MIPMAP_NEAREST: 4 = 4
Variable · category: Graphics
Point sample filtering.
const FILTER_NEAREST: 0 = 0
Variable · category: Graphics
Linearly interpolate in the nearest mipmap level.
const FILTER_NEAREST_MIPMAP_LINEAR: 3 = 3
Variable · category: Graphics
Use the nearest neighbor in the nearest mipmap level.
const FILTER_NEAREST_MIPMAP_NEAREST: 2 = 2
Variable · category: User Interface
Fit the content within the Element's bounding box while preserving its Aspect Ratio.
const FITMODE_CONTAIN: "contain" = 'contain'
Variable · category: User Interface
Fit the content to cover the entire Element's bounding box while preserving its Aspect Ratio.
const FITMODE_COVER: "cover" = 'cover'
Variable · category: User Interface
Fit the content exactly to Element's bounding box.
const FITMODE_STRETCH: "stretch" = 'stretch'
Variable · category: User Interface
Apply both STRETCH and SHRINK fitting logic where applicable.
const FITTING_BOTH: 3 = 3
Variable · category: User Interface
Disable all fitting logic.
const FITTING_NONE: 0 = 0
Variable · category: User Interface
Shrink child elements to fit the parent container.
const FITTING_SHRINK: 2 = 2
Variable · category: User Interface
Stretch child elements to fit the parent container.
const FITTING_STRETCH: 1 = 1
Variable · category: Graphics
Fog rises according to an exponential curve controlled by a density value.
const FOG_EXP: "exp" = 'exp'
Variable · category: Graphics
Fog rises according to an exponential curve controlled by a density value.
const FOG_EXP2: "exp2" = 'exp2'
Variable · category: Graphics
Fog rises linearly from zero to 1 between a start and end depth.
const FOG_LINEAR: "linear" = 'linear'
Variable · category: Graphics
No fog is applied to the scene.
const FOG_NONE: "none" = 'none'
Variable · category: Graphics
No Fresnel.
const FRESNEL_NONE: 0 = 0
Variable · category: Graphics
Schlick's approximation of Fresnel.
const FRESNEL_SCHLICK: 2 = 2
Variable · category: Graphics
The counterclockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation.
const FRONTFACE_CCW: 0 = 0
Variable · category: Graphics
The clockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation.
const FRONTFACE_CW: 1 = 1
Variable · category: Graphics
Always pass.
const FUNC_ALWAYS: 7 = 7
Variable · category: Graphics
Pass if (ref & mask) == (stencil & mask).
const FUNC_EQUAL: 2 = 2
Variable · category: Graphics
Pass if (ref & mask) > (stencil & mask).
const FUNC_GREATER: 4 = 4
Variable · category: Graphics
Pass if (ref & mask) >= (stencil & mask).
const FUNC_GREATEREQUAL: 6 = 6
Variable · category: Graphics
Pass if (ref & mask) < (stencil & mask).
const FUNC_LESS: 1 = 1
Variable · category: Graphics
Pass if (ref & mask) <= (stencil & mask).
const FUNC_LESSEQUAL: 3 = 3
Variable · category: Graphics
Never pass.
const FUNC_NEVER: 0 = 0
Variable · category: Graphics
Pass if (ref & mask) != (stencil & mask).
const FUNC_NOTEQUAL: 5 = 5
Variable · category: Graphics
No gamma correction.
const GAMMA_NONE: 0 = 0
Variable · category: Graphics
Apply sRGB gamma correction.
const GAMMA_SRGB: 1 = 1
Variable · category: Graphics
The splat budget is a limit: the LOD distances of each GSplat decide the detail, and GSplatParams#splatBudget only lowers it when they would ask for more splats than it allows. A distant GSplat uses only the few splats its distance calls for, leaving the rest of the budget unused.
const GSPLAT_BUDGET_LIMIT: "limit" = 'limit'
Variable · category: Graphics
The splat budget is a target: LOD detail is raised until GSplatParams#splatBudget is used up, wherever the camera is. The LOD distances of each GSplat still shape how detail falls off with distance and how it divides between GSplats, but not how much of it there is. The default.
const GSPLAT_BUDGET_TARGET: "target" = 'target'
Variable · category: Graphics
Debug rendering that draws world-space AABBs for each GSplat, colorized by LOD.
const GSPLAT_DEBUG_AABBS: number = 4
Variable · category: Graphics
Debug rendering that colorizes Gaussian splats by their selected LOD level.
const GSPLAT_DEBUG_LOD: number = 1
Variable · category: Graphics
Debug rendering that draws world-space AABBs for each octree node of streamed GSplats, colorized by the currently selected LOD.
const GSPLAT_DEBUG_NODE_AABBS: number = 5
Variable · category: Graphics
No debug rendering for Gaussian splats. Normal rendering mode.
const GSPLAT_DEBUG_NONE: number = 0
Variable · category: Graphics
Debug rendering that assigns a random color per spherical harmonics update pass, visualizing when SH color updates occur.
const GSPLAT_DEBUG_SH_UPDATE: number = 2
Variable · category: Graphics
Automatically selects the best rendering pipeline for the current platform.
const GSPLAT_RENDERER_AUTO: number = 0
Variable · category: Graphics
Rasterization-based rendering with CPU-side sorting.
const GSPLAT_RENDERER_RASTER_CPU_SORT: number = 1
Variable · category: Graphics
Rasterization-based rendering with GPU-side culling and sorting. WebGPU only.
const GSPLAT_RENDERER_RASTER_GPU_SORT: number = 2
Variable · category: Graphics
Stream texture is stored per gsplat component instance.
const GSPLAT_STREAM_INSTANCE: number = 1
Variable · category: Graphics
Stream texture is stored at resource level, shared across all component instances.
const GSPLAT_STREAM_RESOURCE: number = 0
Variable · category: Graphics
Compact work buffer data format optimized for reduced memory and bandwidth. Uses 11+11+10 bit RGB color, half-angle quaternion rotation and log-encoded scale. 20 bytes per splat.
const GSPLATDATA_COMPACT: string = 'compact'
Variable · category: Graphics
Large work buffer data format with full precision. Uses RGBA16F color, float16 rotation and float16 scale. 32 bytes per splat.
const GSPLATDATA_LARGE: string = 'large'
Variable · category: Graphics
16-bit unsigned vertex indices (0 to 65,535).
const INDEXFORMAT_UINT16: 1 = 1
Variable · category: Graphics
32-bit unsigned vertex indices (0 to 4,294,967,295).
const INDEXFORMAT_UINT32: 2 = 2
Variable · category: Graphics
8-bit unsigned vertex indices (0 to 255).
const INDEXFORMAT_UINT8: 0 = 0
Variable · category: Animation
A cubic spline interpolation scheme.
const INTERPOLATION_CUBIC: 2 = 2
Variable · category: Animation
A linear interpolation scheme.
const INTERPOLATION_LINEAR: 1 = 1
Variable · category: Animation
A stepped interpolation scheme.
const INTERPOLATION_STEP: 0 = 0
Variable · category: Physics
Generic 6 degrees of freedom joint. Each linear and angular axis can be independently locked, limited or free, with optional springs.
const JOINTTYPE_6DOF: "6dof" = '6dof'
Variable · category: Physics
Ball and socket joint. The bodies can rotate freely about the joint's anchor point. Optional limits constrain the swing (cone) and twist angles.
const JOINTTYPE_BALL: "ball" = 'ball'
Variable · category: Physics
Joint rigidly locks all degrees of freedom, welding the two bodies together.
const JOINTTYPE_FIXED: "fixed" = 'fixed'
Variable · category: Physics
Hinge joint. The bodies can rotate about the joint's X axis, like a door hinge or a wheel axle. Supports optional rotation limits and a motor.
const JOINTTYPE_HINGE: "hinge" = 'hinge'
Variable · category: Physics
Slider (prismatic) joint. The bodies can translate along the joint's X axis, like a drawer runner or a piston. Supports optional travel limits and a motor.
const JOINTTYPE_SLIDER: "slider" = 'slider'
Variable · category: Input Devices
const KEY_0: number = 48
Variable · category: Input Devices
const KEY_1: number = 49
Variable · category: Input Devices
const KEY_2: number = 50
Variable · category: Input Devices
const KEY_3: number = 51
Variable · category: Input Devices
const KEY_4: number = 52
Variable · category: Input Devices
const KEY_5: number = 53
Variable · category: Input Devices
const KEY_6: number = 54
Variable · category: Input Devices
const KEY_7: number = 55
Variable · category: Input Devices
const KEY_8: number = 56
Variable · category: Input Devices
const KEY_9: number = 57
Variable · category: Input Devices
const KEY_A: number = 65
Variable · category: Input Devices
const KEY_ADD: number = 107
Variable · category: Input Devices
const KEY_ALT: number = 18
Variable · category: Input Devices
const KEY_B: number = 66
Variable · category: Input Devices
const KEY_BACK_SLASH: number = 220
Variable · category: Input Devices
const KEY_BACKSPACE: number = 8
Variable · category: Input Devices
const KEY_C: number = 67
Variable · category: Input Devices
const KEY_CAPS_LOCK: number = 20
Variable · category: Input Devices
const KEY_CLOSE_BRACKET: number = 221
Variable · category: Input Devices
const KEY_COMMA: number = 188
Variable · category: Input Devices
const KEY_CONTEXT_MENU: number = 93
Variable · category: Input Devices
const KEY_CONTROL: number = 17
Variable · category: Input Devices
const KEY_D: number = 68
Variable · category: Input Devices
const KEY_DECIMAL: number = 110
Variable · category: Input Devices
const KEY_DELETE: number = 46
Variable · category: Input Devices
const KEY_DIVIDE: number = 111
Variable · category: Input Devices
const KEY_DOWN: number = 40
Variable · category: Input Devices
const KEY_E: number = 69
Variable · category: Input Devices
const KEY_END: number = 35
Variable · category: Input Devices
const KEY_ENTER: number = 13
Variable · category: Input Devices
const KEY_EQUAL: number = 61
Variable · category: Input Devices
const KEY_ESCAPE: number = 27
Variable · category: Input Devices
const KEY_F: number = 70
Variable · category: Input Devices
const KEY_F1: number = 112
Variable · category: Input Devices
const KEY_F10: number = 121
Variable · category: Input Devices
const KEY_F11: number = 122
Variable · category: Input Devices
const KEY_F12: number = 123
Variable · category: Input Devices
const KEY_F2: number = 113
Variable · category: Input Devices
const KEY_F3: number = 114
Variable · category: Input Devices
const KEY_F4: number = 115
Variable · category: Input Devices
const KEY_F5: number = 116
Variable · category: Input Devices
const KEY_F6: number = 117
Variable · category: Input Devices
const KEY_F7: number = 118
Variable · category: Input Devices
const KEY_F8: number = 119
Variable · category: Input Devices
const KEY_F9: number = 120
Variable · category: Input Devices
const KEY_G: number = 71
Variable · category: Input Devices
const KEY_H: number = 72
Variable · category: Input Devices
const KEY_HOME: number = 36
Variable · category: Input Devices
const KEY_I: number = 73
Variable · category: Input Devices
const KEY_INSERT: number = 45
Variable · category: Input Devices
const KEY_J: number = 74
Variable · category: Input Devices
const KEY_K: number = 75
Variable · category: Input Devices
const KEY_L: number = 76
Variable · category: Input Devices
const KEY_LEFT: number = 37
Variable · category: Input Devices
const KEY_M: number = 77
Variable · category: Input Devices
const KEY_META: number = 224
Variable · category: Input Devices
const KEY_MULTIPLY: number = 106
Variable · category: Input Devices
const KEY_N: number = 78
Variable · category: Input Devices
const KEY_NUMPAD_0: number = 96
Variable · category: Input Devices
const KEY_NUMPAD_1: number = 97
Variable · category: Input Devices
const KEY_NUMPAD_2: number = 98
Variable · category: Input Devices
const KEY_NUMPAD_3: number = 99
Variable · category: Input Devices
const KEY_NUMPAD_4: number = 100
Variable · category: Input Devices
const KEY_NUMPAD_5: number = 101
Variable · category: Input Devices
const KEY_NUMPAD_6: number = 102
Variable · category: Input Devices
const KEY_NUMPAD_7: number = 103
Variable · category: Input Devices
const KEY_NUMPAD_8: number = 104
Variable · category: Input Devices
const KEY_NUMPAD_9: number = 105
Variable · category: Input Devices
const KEY_O: number = 79
Variable · category: Input Devices
const KEY_OPEN_BRACKET: number = 219
Variable · category: Input Devices
const KEY_P: number = 80
Variable · category: Input Devices
const KEY_PAGE_DOWN: number = 34
Variable · category: Input Devices
const KEY_PAGE_UP: number = 33
Variable · category: Input Devices
const KEY_PAUSE: number = 19
Variable · category: Input Devices
const KEY_PERIOD: number = 190
Variable · category: Input Devices
const KEY_PRINT_SCREEN: number = 44
Variable · category: Input Devices
const KEY_Q: number = 81
Variable · category: Input Devices
const KEY_R: number = 82
Variable · category: Input Devices
const KEY_RETURN: number = 13
Variable · category: Input Devices
const KEY_RIGHT: number = 39
Variable · category: Input Devices
const KEY_S: number = 83
Variable · category: Input Devices
const KEY_SEMICOLON: number = 59
Variable · category: Input Devices
const KEY_SEPARATOR: number = 108
Variable · category: Input Devices
const KEY_SHIFT: number = 16
Variable · category: Input Devices
const KEY_SLASH: number = 191
Variable · category: Input Devices
const KEY_SPACE: number = 32
Variable · category: Input Devices
const KEY_SUBTRACT: number = 109
Variable · category: Input Devices
const KEY_T: number = 84
Variable · category: Input Devices
const KEY_TAB: number = 9
Variable · category: Input Devices
const KEY_U: number = 85
Variable · category: Input Devices
const KEY_UP: number = 38
Variable · category: Input Devices
const KEY_V: number = 86
Variable · category: Input Devices
const KEY_W: number = 87
Variable · category: Input Devices
const KEY_WINDOWS: number = 91
Variable · category: Input Devices
const KEY_X: number = 88
Variable · category: Input Devices
const KEY_Y: number = 89
Variable · category: Input Devices
const KEY_Z: number = 90
Variable · category: Graphics
The depth layer.
const LAYERID_DEPTH: 1 = 1
Variable · category: Graphics
The immediate layer.
const LAYERID_IMMEDIATE: 3 = 3
Variable · category: Graphics
The skybox layer.
const LAYERID_SKYBOX: 2 = 2
Variable · category: Graphics
The UI layer.
const LAYERID_UI: 4 = 4
Variable · category: Graphics
The world layer.
const LAYERID_WORLD: 0 = 0
Variable · category: Graphics
Inverse squared distance falloff model for light attenuation.
const LIGHTFALLOFF_INVERSESQUARED: 1 = 1
Variable · category: Graphics
Linear distance falloff model for light attenuation.
const LIGHTFALLOFF_LINEAR: 0 = 0
Variable · category: Graphics
Disk shape of light source.
const LIGHTSHAPE_DISK: 2 = 2
Variable · category: Graphics
Infinitesimally small point light source shape.
const LIGHTSHAPE_PUNCTUAL: 0 = 0
Variable · category: Graphics
Rectangle shape of light source.
const LIGHTSHAPE_RECT: 1 = 1
Variable · category: Graphics
Sphere shape of light source.
const LIGHTSHAPE_SPHERE: 3 = 3
Variable · category: Graphics
Directional (global) light source.
const LIGHTTYPE_DIRECTIONAL: 0 = 0
Variable · category: Graphics
Omni-directional (local) light source.
const LIGHTTYPE_OMNI: 1 = 1
Variable · category: Graphics
Spot (local) light source.
const LIGHTTYPE_SPOT: 2 = 2
Variable · category: Other
Butt line caps stop exactly at the first and last points.
const LINECAP_BUTT: 0 = 0
Variable · category: Other
Round line caps extend past line and dash ends by half the line width.
const LINECAP_ROUND: 2 = 2
Variable · category: Other
Square line caps extend past the first and last points by half the line width.
const LINECAP_SQUARE: 1 = 1
Variable · category: Other
Bevel joins connect segment edges directly.
const LINEJOIN_BEVEL: 1 = 1
Variable · category: Other
Miter joins extend edges until they intersect.
const LINEJOIN_MITER: 0 = 0
Variable · category: Other
Round joins connect segments using a circular edge.
const LINEJOIN_ROUND: 2 = 2
Variable · category: Other
Line widths are measured in screen pixels.
const LINEWIDTH_SCREEN: 0 = 0
Variable · category: Other
Line widths are measured in world units.
const LINEWIDTH_WORLD: 1 = 1
Variable · category: Physics
Specified degree of freedom has free movement.
const MOTION_FREE: "free" = 'free'
Variable · category: Physics
Specified degree of freedom has limited movement.
const MOTION_LIMITED: "limited" = 'limited'
Variable · category: Physics
Specified degree of freedom is locked and allows no movement.
const MOTION_LOCKED: "locked" = 'locked'
Variable · category: Input Devices
The left mouse button.
const MOUSEBUTTON_LEFT: 0 = 0
Variable · category: Input Devices
The middle mouse button.
const MOUSEBUTTON_MIDDLE: 1 = 1
Variable · category: Input Devices
No mouse buttons pressed.
const MOUSEBUTTON_NONE: -1 = -1
Variable · category: Input Devices
The right mouse button.
const MOUSEBUTTON_RIGHT: 2 = 2
Variable · category: Graphics
Horizontal orientation.
const ORIENTATION_HORIZONTAL: 0 = 0
Variable · category: Graphics
Vertical orientation.
const ORIENTATION_VERTICAL: 1 = 1
Variable · category: Input Devices
Index for pad 1.
const PAD_1: 0 = 0
Variable · category: Input Devices
Index for pad 2.
const PAD_2: 1 = 1
Variable · category: Input Devices
Index for pad 3.
const PAD_3: 2 = 2
Variable · category: Input Devices
Index for pad 4.
const PAD_4: 3 = 3
Variable · category: Input Devices
Direction pad down.
const PAD_DOWN: 13 = 13
Variable · category: Input Devices
The first face button, from bottom going clockwise.
const PAD_FACE_1: 0 = 0
Variable · category: Input Devices
The second face button, from bottom going clockwise.
const PAD_FACE_2: 1 = 1
Variable · category: Input Devices
The third face button, from bottom going clockwise.
const PAD_FACE_3: 2 = 2
Variable · category: Input Devices
The fourth face button, from bottom going clockwise.
const PAD_FACE_4: 3 = 3
Variable · category: Input Devices
The first shoulder button on the left.
const PAD_L_SHOULDER_1: 4 = 4
Variable · category: Input Devices
The second shoulder button on the left.
const PAD_L_SHOULDER_2: 6 = 6
Variable · category: Input Devices
The button when depressing the left analogue stick.
const PAD_L_STICK_BUTTON: 10 = 10
Variable · category: Input Devices
Horizontal axis on the left analogue stick.
const PAD_L_STICK_X: 0 = 0
Variable · category: Input Devices
Vertical axis on the left analogue stick.
const PAD_L_STICK_Y: 1 = 1
Variable · category: Input Devices
Direction pad left.
const PAD_LEFT: 14 = 14
Variable · category: Input Devices
The first shoulder button on the right.
const PAD_R_SHOULDER_1: 5 = 5
Variable · category: Input Devices
The second shoulder button on the right.
const PAD_R_SHOULDER_2: 7 = 7
Variable · category: Input Devices
The button when depressing the right analogue stick.
const PAD_R_STICK_BUTTON: 11 = 11
Variable · category: Input Devices
Horizontal axis on the right analogue stick.
const PAD_R_STICK_X: 2 = 2
Variable · category: Input Devices
Vertical axis on the right analogue stick.
const PAD_R_STICK_Y: 3 = 3
Variable · category: Input Devices
Direction pad right.
const PAD_RIGHT: 15 = 15
Variable · category: Input Devices
The select button.
const PAD_SELECT: 8 = 8
Variable · category: Input Devices
The start button.
const PAD_START: 9 = 9
Variable · category: Input Devices
Direction pad up.
const PAD_UP: 12 = 12
Variable · category: Input Devices
Vendor specific button.
const PAD_VENDOR: 16 = 16
Variable · category: Graphics
Parallax occlusion mapping marches the view ray through the height field to find where it meets the displaced surface. This costs more than PARALLAX_OFFSET, but represents deeper displacement without smearing the texture.
const PARALLAX_OCCLUSION: "occlusion" = 'occlusion'
Variable · category: Graphics
Parallax mapping computes the uv offset from a single tap of the height map. This is the cheapest option, and suits shallow surface detail.
const PARALLAX_OFFSET: "offset" = 'offset'
Variable · category: Graphics
Similar to previous, but the normal is affected by emitter(entity) transformation.
const PARTICLEORIENTATION_EMITTER: 2 = 2
Variable · category: Graphics
Particles are facing camera.
const PARTICLEORIENTATION_SCREEN: 0 = 0
Variable · category: Graphics
User defines world space normal (particleNormal) to set planes orientation.
const PARTICLEORIENTATION_WORLD: 1 = 1
Variable · category: Graphics
Sorting based on distance to the camera. CPU only.
const PARTICLESORT_DISTANCE: 1 = 1
Variable · category: Graphics
Newer particles are drawn first. CPU only.
const PARTICLESORT_NEWER_FIRST: 2 = 2
Variable · category: Graphics
No sorting, particles are drawn in arbitrary order. Can be simulated on GPU.
const PARTICLESORT_NONE: 0 = 0
Variable · category: Graphics
Older particles are drawn first. CPU only.
const PARTICLESORT_OLDER_FIRST: 3 = 3
Variable · category: Graphics
A floating-point color-only format with 11 bits for red and green channels and 10 bits for the blue channel.
const PIXELFORMAT_111110F: 18 = 18
Variable · category: Graphics
ATC compressed format with no alpha channel.
const PIXELFORMAT_ATC_RGB: 29 = 29
Variable · category: Graphics
ATC compressed format with alpha channel.
const PIXELFORMAT_ATC_RGBA: 30 = 30
Variable · category: Graphics
Compressed high dynamic range signed floating point format storing RGB values.
const PIXELFORMAT_BC6F: 65 = 65
Variable · category: Graphics
Compressed high dynamic range unsigned floating point format storing RGB values.
const PIXELFORMAT_BC6UF: 66 = 66
Variable · category: Graphics
Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA data.
const PIXELFORMAT_BC7: 67 = 67
Variable · category: Graphics
Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of SRGB_ALPHA data.
const PIXELFORMAT_BC7_SRGBA: 68 = 68
Variable · category: Graphics
A readable depth buffer format.
const PIXELFORMAT_DEPTH: 16 = 16
Variable · category: Graphics
A 16-bit depth buffer format.
const PIXELFORMAT_DEPTH16: 69 = 69
Variable · category: Graphics
A readable depth/stencil buffer format.
const PIXELFORMAT_DEPTHSTENCIL: 17 = 17
Variable · category: Graphics
Block compressed format storing 16 input pixels in 64 bits of output, consisting of two 16-bit RGB 5:6:5 color values and a 4x4 two bit lookup table.
const PIXELFORMAT_DXT1: 8 = 8
Variable · category: Graphics
Format equivalent to PIXELFORMAT_DXT1 but sampled in linear color space.
const PIXELFORMAT_DXT1_SRGB: 54 = 54
Variable · category: Graphics
Block compressed format storing 16 input pixels (corresponding to a 4x4 pixel block) into 128 bits of output, consisting of 64 bits of alpha channel data (4 bits for each pixel) followed by 64 bits of color data; encoded the same way as DXT1.
const PIXELFORMAT_DXT3: 9 = 9
Variable · category: Graphics
Format equivalent to PIXELFORMAT_DXT3 but sampled in linear color space.
const PIXELFORMAT_DXT3_SRGBA: 55 = 55
Variable · category: Graphics
Block compressed format storing 16 input pixels into 128 bits of output, consisting of 64 bits of alpha channel data (two 8 bit alpha values and a 4x4 3 bit lookup table) followed by 64 bits of color data (encoded the same way as DXT1).
const PIXELFORMAT_DXT5: 10 = 10
Variable · category: Graphics
Format equivalent to PIXELFORMAT_DXT5 but sampled in linear color space.
const PIXELFORMAT_DXT5_SRGBA: 56 = 56
Variable · category: Graphics
ETC1 compressed format.
const PIXELFORMAT_ETC1: 21 = 21
Variable · category: Graphics
ETC2 (RGB) compressed format.
const PIXELFORMAT_ETC2_RGB: 22 = 22
Variable · category: Graphics
ETC2 (RGBA) compressed format.
const PIXELFORMAT_ETC2_RGBA: 23 = 23
Variable · category: Graphics
Format equivalent to PIXELFORMAT_ETC2_RGB but sampled in linear color space.
const PIXELFORMAT_ETC2_SRGB: 61 = 61
Variable · category: Graphics
Format equivalent to PIXELFORMAT_ETC2_RGBA but sampled in linear color space.
const PIXELFORMAT_ETC2_SRGBA: 62 = 62
Variable · category: Graphics
PVRTC (2BPP RGB) compressed format.
const PIXELFORMAT_PVRTC_2BPP_RGB_1: 24 = 24
Variable · category: Graphics
PVRTC (2BPP RGBA) compressed format.
const PIXELFORMAT_PVRTC_2BPP_RGBA_1: 25 = 25
Variable · category: Graphics
PVRTC (4BPP RGB) compressed format.
const PIXELFORMAT_PVRTC_4BPP_RGB_1: 26 = 26
Variable · category: Graphics
PVRTC (4BPP RGBA) compressed format.
const PIXELFORMAT_PVRTC_4BPP_RGBA_1: 27 = 27
Variable · category: Graphics
16-bit floating point R (16-bit float for red channel).
const PIXELFORMAT_R16F: 50 = 50
Variable · category: Graphics
16-bit signed integer single-channel (R) format.
const PIXELFORMAT_R16I: 34 = 34
Variable · category: Graphics
16-bit unsigned integer single-channel (R) format.
const PIXELFORMAT_R16U: 35 = 35
Variable · category: Graphics
32-bit floating point single channel format.
const PIXELFORMAT_R32F: 15 = 15
Variable · category: Graphics
32-bit signed integer single-channel (R) format.
const PIXELFORMAT_R32I: 36 = 36
Variable · category: Graphics
32-bit unsigned integer single-channel (R) format.
const PIXELFORMAT_R32U: 37 = 37
Variable · category: Graphics
8-bit per-channel (R) format.
const PIXELFORMAT_R8: 52 = 52
Variable · category: Graphics
8-bit signed integer single-channel (R) format.
const PIXELFORMAT_R8I: 32 = 32
Variable · category: Graphics
8-bit unsigned integer single-channel (R) format.
const PIXELFORMAT_R8U: 33 = 33
Variable · category: Graphics
16-bit floating point RG (16-bit float for each red and green channels).
const PIXELFORMAT_RG16F: 51 = 51
Variable · category: Graphics
16-bit per-channel signed integer (RG) format.
const PIXELFORMAT_RG16I: 40 = 40
Variable · category: Graphics
16-bit per-channel unsigned integer (RG) format.
const PIXELFORMAT_RG16U: 41 = 41
Variable · category: Graphics
32-bit floating point RG (32-bit float for each red and green channels). WebGPU only.
const PIXELFORMAT_RG32F: 70 = 70
Variable · category: Graphics
32-bit per-channel signed integer (RG) format.
const PIXELFORMAT_RG32I: 42 = 42
Variable · category: Graphics
32-bit per-channel unsigned integer (RG) format.
const PIXELFORMAT_RG32U: 43 = 43
Variable · category: Graphics
8-bit per-channel (RG) format.
const PIXELFORMAT_RG8: 53 = 53
Variable · category: Graphics
8-bit per-channel signed integer (RG) format.
const PIXELFORMAT_RG8I: 38 = 38
Variable · category: Graphics
8-bit per-channel signed normalized (RG) format.
const PIXELFORMAT_RG8S: 72 = 72
Variable · category: Graphics
8-bit per-channel unsigned integer (RG) format.
const PIXELFORMAT_RG8U: 39 = 39
Variable · category: Graphics
10-bit RGB with 2-bit alpha unsigned normalized format.
const PIXELFORMAT_RGB10A2: 74 = 74
Variable · category: Graphics
10-bit RGB with 2-bit alpha unsigned integer format.
const PIXELFORMAT_RGB10A2U: 75 = 75
Variable · category: Graphics
16-bit floating point RGB (16-bit float for each red, green and blue channels).
const PIXELFORMAT_RGB16F: 11 = 11
Variable · category: Graphics
32-bit floating point RGB (32-bit float for each red, green and blue channels).
const PIXELFORMAT_RGB32F: 13 = 13
Variable · category: Graphics
16-bit RGB (5-bits for red channel, 6 for green and 5 for blue).
const PIXELFORMAT_RGB565: 3 = 3
Variable · category: Graphics
24-bit RGB (8-bits for red channel, 8 for green and 8 for blue).
const PIXELFORMAT_RGB8: 6 = 6
Variable · category: Graphics
32-bit RGB format with shared 5-bit exponent (9 bits each for RGB mantissa). HDR format.
const PIXELFORMAT_RGB9E5: 71 = 71
Variable · category: Graphics
16-bit floating point RGBA (16-bit float for each red, green, blue and alpha channels).
const PIXELFORMAT_RGBA16F: 12 = 12
Variable · category: Graphics
16-bit per-channel signed integer (RGBA) format.
const PIXELFORMAT_RGBA16I: 46 = 46
Variable · category: Graphics
16-bit per-channel unsigned integer (RGBA) format.
const PIXELFORMAT_RGBA16U: 47 = 47
Variable · category: Graphics
32-bit floating point RGBA (32-bit float for each red, green, blue and alpha channels).
const PIXELFORMAT_RGBA32F: 14 = 14
Variable · category: Graphics
32-bit per-channel signed integer (RGBA) format.
const PIXELFORMAT_RGBA32I: 48 = 48
Variable · category: Graphics
32-bit per-channel unsigned integer (RGBA) format.
const PIXELFORMAT_RGBA32U: 49 = 49
Variable · category: Graphics
16-bit RGBA (4-bits for red channel, 4 for green, 4 for blue with 4-bit alpha).
const PIXELFORMAT_RGBA4: 5 = 5
Variable · category: Graphics
16-bit RGBA (5-bits for red channel, 5 for green, 5 for blue with 1-bit alpha).
const PIXELFORMAT_RGBA5551: 4 = 4
Variable · category: Graphics
32-bit RGBA (8-bits for red channel, 8 for green, 8 for blue with 8-bit alpha).
const PIXELFORMAT_RGBA8: 7 = 7
Variable · category: Graphics
8-bit per-channel signed integer (RGBA) format.
const PIXELFORMAT_RGBA8I: 44 = 44
Variable · category: Graphics
8-bit per-channel signed normalized (RGBA) format.
const PIXELFORMAT_RGBA8S: 73 = 73
Variable · category: Graphics
8-bit per-channel unsigned integer (RGBA) format.
const PIXELFORMAT_RGBA8U: 45 = 45
Variable · category: Graphics
Color-only sRGB format.
const PIXELFORMAT_SRGB8: 19 = 19
Variable · category: Graphics
Color sRGB format with additional alpha channel.
const PIXELFORMAT_SRGBA8: 20 = 20
Variable · category: Graphics
List of points that are linked sequentially by line segments, with a closing line segment between the last and first points.
const PRIMITIVE_LINELOOP: 2 = 2
Variable · category: Graphics
Discrete list of line segments.
const PRIMITIVE_LINES: 1 = 1
Variable · category: Graphics
List of points that are linked sequentially by line segments.
const PRIMITIVE_LINESTRIP: 3 = 3
Variable · category: Graphics
List of distinct points.
const PRIMITIVE_POINTS: 0 = 0
Variable · category: Graphics
Discrete list of triangles.
const PRIMITIVE_TRIANGLES: 4 = 4
Variable · category: Graphics
Connected fan of triangles where the first vertex forms triangles with the following pairs of vertices.
const PRIMITIVE_TRIFAN: 6 = 6
Variable · category: Graphics
Connected strip of triangles where a specified vertex forms a triangle using the previous two.
const PRIMITIVE_TRISTRIP: 5 = 5
Variable · category: Graphics
An orthographic camera projection where the frustum shape is essentially a cuboid.
const PROJECTION_ORTHOGRAPHIC: 1 = 1
Variable · category: Graphics
A perspective camera projection where the frustum shape is essentially pyramidal.
const PROJECTION_PERSPECTIVE: 0 = 0
Variable · category: Graphics
Render mesh instance as points.
const RENDERSTYLE_POINTS: 2 = 2
Variable · category: Graphics
Render mesh instance as solid geometry.
const RENDERSTYLE_SOLID: 0 = 0
Variable · category: Graphics
Render mesh instance as wireframe.
const RENDERSTYLE_WIREFRAME: 1 = 1
Variable · category: Graphics
The render target stores the image with row 0 being the bottom row of the rendered image, on
all graphics APIs - replicating WebGL2's native layout. See the origin option of the
RenderTarget constructor for guidance on which origin to use.
const RENDERTARGET_ORIGIN_BOTTOM: "bottom" = 'bottom'
Variable · category: Graphics
The render target stores the image in the native orientation of the graphics API - bottom-up
on WebGL2, top-down on WebGPU - so the stored row order differs between the APIs. This is the
default. See the origin option of the RenderTarget constructor for guidance on which
origin to use.
const RENDERTARGET_ORIGIN_NATIVE: "native" = 'native'
Variable · category: Graphics
The render target stores the image with row 0 being the top row of the rendered image, on all
graphics APIs - the same layout image textures use. See the origin option of the
RenderTarget constructor for guidance on which origin to use.
const RENDERTARGET_ORIGIN_TOP: "top" = 'top'
Variable · category: Other
When the canvas is resized the resolution of the canvas will change to match the size of the canvas.
const RESOLUTION_AUTO: "AUTO" = 'AUTO'
Variable · category: Other
When the canvas is resized the resolution of the canvas will remain at the same value and the output will just be scaled to fit the canvas.
const RESOLUTION_FIXED: "FIXED" = 'FIXED'
Variable · category: Graphics
A sampler type of a texture that contains depth data. Typically used for depth textures.
const SAMPLETYPE_DEPTH: 2 = 2
Variable · category: Graphics
A sampler type of a texture that contains floating-point data. Typically stored for color textures, where data can be filtered.
const SAMPLETYPE_FLOAT: 0 = 0
Variable · category: Graphics
A sampler type of a texture that contains signed integer data.
const SAMPLETYPE_INT: 3 = 3
Variable · category: Graphics
A sampler type of a texture that contains unsigned integer data.
const SAMPLETYPE_UINT: 4 = 4
Variable · category: Graphics
A sampler type of a texture that contains floating-point data, but cannot be filtered. Typically used for textures storing data that cannot be interpolated.
const SAMPLETYPE_UNFILTERABLE_FLOAT: 1 = 1
Variable · category: User Interface
Scale the ScreenComponent when the application's resolution is different than the ScreenComponent's referenceResolution.
const SCALEMODE_BLEND: "blend" = 'blend'
Variable · category: User Interface
Always use the application's resolution as the resolution for the ScreenComponent.
const SCALEMODE_NONE: "none" = 'none'
Variable · category: User Interface
Content scrolls past its bounds and then gently bounces back.
const SCROLL_MODE_BOUNCE: 1 = 1
Variable · category: User Interface
Content does not scroll any further than its bounds.
const SCROLL_MODE_CLAMP: 0 = 0
Variable · category: User Interface
Content can scroll forever.
const SCROLL_MODE_INFINITE: 2 = 2
Variable · category: User Interface
The scrollbar will be visible all the time.
const SCROLLBAR_VISIBILITY_SHOW_ALWAYS: 0 = 0
Variable · category: User Interface
The scrollbar will be visible only when content exceeds the size of the viewport.
const SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED: 1 = 1
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR0: "ATTR0" = 'ATTR0'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR1: "ATTR1" = 'ATTR1'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR10: "ATTR10" = 'ATTR10'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR11: "ATTR11" = 'ATTR11'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR12: "ATTR12" = 'ATTR12'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR13: "ATTR13" = 'ATTR13'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR14: "ATTR14" = 'ATTR14'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR15: "ATTR15" = 'ATTR15'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR2: "ATTR2" = 'ATTR2'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR3: "ATTR3" = 'ATTR3'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR4: "ATTR4" = 'ATTR4'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR5: "ATTR5" = 'ATTR5'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR6: "ATTR6" = 'ATTR6'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR7: "ATTR7" = 'ATTR7'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR8: "ATTR8" = 'ATTR8'
Variable · category: Graphics
Vertex attribute with a user defined semantic.
const SEMANTIC_ATTR9: "ATTR9" = 'ATTR9'
Variable · category: Graphics
Vertex attribute to be treated as skin blend indices.
const SEMANTIC_BLENDINDICES: "BLENDINDICES" = 'BLENDINDICES'
Variable · category: Graphics
Vertex attribute to be treated as skin blend weights.
const SEMANTIC_BLENDWEIGHT: "BLENDWEIGHT" = 'BLENDWEIGHT'
Variable · category: Graphics
Vertex attribute to be treated as a color.
const SEMANTIC_COLOR: "COLOR" = 'COLOR'
Variable · category: Graphics
Vertex attribute to be treated as a normal.
const SEMANTIC_NORMAL: "NORMAL" = 'NORMAL'
Variable · category: Graphics
Vertex attribute to be treated as a position.
const SEMANTIC_POSITION: "POSITION" = 'POSITION'
Variable · category: Graphics
Vertex attribute to be treated as a tangent.
const SEMANTIC_TANGENT: "TANGENT" = 'TANGENT'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 0).
const SEMANTIC_TEXCOORD0: "TEXCOORD0" = 'TEXCOORD0'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 1).
const SEMANTIC_TEXCOORD1: "TEXCOORD1" = 'TEXCOORD1'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 2).
const SEMANTIC_TEXCOORD2: "TEXCOORD2" = 'TEXCOORD2'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 3).
const SEMANTIC_TEXCOORD3: "TEXCOORD3" = 'TEXCOORD3'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 4).
const SEMANTIC_TEXCOORD4: "TEXCOORD4" = 'TEXCOORD4'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 5).
const SEMANTIC_TEXCOORD5: "TEXCOORD5" = 'TEXCOORD5'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 6).
const SEMANTIC_TEXCOORD6: "TEXCOORD6" = 'TEXCOORD6'
Variable · category: Graphics
Vertex attribute to be treated as a texture coordinate (set 7).
const SEMANTIC_TEXCOORD7: "TEXCOORD7" = 'TEXCOORD7'
Variable · category: Graphics
Render shaded materials using forward rendering.
const SHADER_FORWARD: 0 = 0
Variable · category: Graphics
Shader source code uses GLSL language.
const SHADERLANGUAGE_GLSL: "glsl" = 'glsl'
Variable · category: Graphics
Shader source code uses WGSL language.
const SHADERLANGUAGE_WGSL: "wgsl" = 'wgsl'
Variable · category: Graphics
Shader used for debug rendering of albedo.
const SHADERPASS_ALBEDO: "debug_albedo" = 'debug_albedo'
Variable · category: Graphics
Shader used for debug rendering of ao.
const SHADERPASS_AO: "debug_ao" = 'debug_ao'
Variable · category: Graphics
Shader used for debug rendering of emission.
const SHADERPASS_EMISSION: "debug_emission" = 'debug_emission'
Variable · category: Graphics
Shader that performs forward rendering.
const SHADERPASS_FORWARD: "forward" = 'forward'
Variable · category: Graphics
Shader used for debug rendering of gloss.
const SHADERPASS_GLOSS: "debug_gloss" = 'debug_gloss'
Variable · category: Graphics
Shader used for debug rendering of lighting.
const SHADERPASS_LIGHTING: "debug_lighting" = 'debug_lighting'
Variable · category: Graphics
Shader used for debug rendering of metalness.
const SHADERPASS_METALNESS: "debug_metalness" = 'debug_metalness'
Variable · category: Graphics
Shader used for debug rendering of opacity.
const SHADERPASS_OPACITY: "debug_opacity" = 'debug_opacity'
Variable · category: Graphics
Shader used for debug rendering of specularity.
const SHADERPASS_SPECULARITY: "debug_specularity" = 'debug_specularity'
Variable · category: Graphics
Shader used for debug rendering of UV0 texture coordinates.
const SHADERPASS_UV0: "debug_uv0" = 'debug_uv0'
Variable · category: Graphics
Shader used for debug rendering of world normal.
const SHADERPASS_WORLDNORMAL: "debug_world_normal" = 'debug_world_normal'
Variable · category: Graphics
The resource is visible to the compute shader.
const SHADERSTAGE_COMPUTE: 4 = 4
Variable · category: Graphics
The resource is visible to the fragment shader.
const SHADERSTAGE_FRAGMENT: 2 = 2
Variable · category: Graphics
The resource is visible to the vertex shader.
const SHADERSTAGE_VERTEX: 1 = 1
Variable · category: Graphics
The flag that controls shadow rendering for the 0 cascade
const SHADOW_CASCADE_0: 1 = 1
Variable · category: Graphics
The flag that controls shadow rendering for the 1 cascade
const SHADOW_CASCADE_1: 2 = 2
Variable · category: Graphics
The flag that controls shadow rendering for the 2 cascade
const SHADOW_CASCADE_2: 4 = 4
Variable · category: Graphics
The flag that controls shadow rendering for the 3 cascade
const SHADOW_CASCADE_3: 8 = 8
Variable · category: Graphics
The flag that controls shadow rendering for the all cascades
const SHADOW_CASCADE_ALL: 255 = 255
Variable · category: Graphics
A shadow sampling technique using a 16-bit shadow map that performs a single depth comparison for sharp shadow edges.
const SHADOW_PCF1_16F: 7 = 7
Variable · category: Graphics
A shadow sampling technique using a 32-bit shadow map that performs a single depth comparison for sharp shadow edges.
const SHADOW_PCF1_32F: 5 = 5
Variable · category: Graphics
A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.
const SHADOW_PCF3_16F: 8 = 8
Variable · category: Graphics
A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.
const SHADOW_PCF3_32F: 0 = 0
Variable · category: Graphics
A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.
const SHADOW_PCF5_16F: 9 = 9
Variable · category: Graphics
A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 5x5 grid of texels for softened shadow edges.
const SHADOW_PCF5_32F: 4 = 4
Variable · category: Graphics
A shadow sampling technique using a 32-bit shadow map that adjusts filter size based on blocker distance, producing realistic, soft shadow edges that vary with the light's occlusion. Note that this technique requires both GraphicsDevice#textureFloatRenderable and GraphicsDevice#textureFloatFilterable to be true, and falls back to SHADOW_PCF3_32F otherwise.
const SHADOW_PCSS_32F: 6 = 6
Variable · category: Graphics
A shadow sampling technique using a 16-bit exponential variance shadow map that leverages variance to approximate shadow boundaries, enabling soft shadows. Only supported when GraphicsDevice#textureHalfFloatRenderable is true. Falls back to SHADOW_PCF3_32F, if not supported.
const SHADOW_VSM_16F: 2 = 2
Variable · category: Graphics
A shadow sampling technique using a 32-bit exponential variance shadow map that leverages variance to approximate shadow boundaries, enabling soft shadows. Only supported when GraphicsDevice#textureFloatRenderable is true. Falls back to SHADOW_VSM_16F, if not supported.
const SHADOW_VSM_32F: 3 = 3
Variable · category: Graphics
The shadow map is not to be updated.
const SHADOWUPDATE_NONE: 0 = 0
Variable · category: Graphics
The shadow map is regenerated every frame.
const SHADOWUPDATE_REALTIME: 2 = 2
Variable · category: Graphics
The shadow map is regenerated this frame and not on subsequent frames.
const SHADOWUPDATE_THISFRAME: 1 = 1
Variable · category: Graphics
A sky texture is rendered using a box projection. This is generally suitable for interior environments.
const SKYTYPE_BOX: "box" = 'box'
Variable · category: Graphics
A sky texture is rendered using a dome projection. This is generally suitable for exterior environments.
const SKYTYPE_DOME: "dome" = 'dome'
Variable · category: Graphics
A sky texture is rendered using an infinite projection.
const SKYTYPE_INFINITE: "infinite" = 'infinite'
Variable · category: Graphics
Mesh instances are sorted back to front. This is the way to properly render many semi-transparent objects on different depth, one is blended on top of another.
const SORTMODE_BACK2FRONT: 3 = 3
Variable · category: Graphics
Mesh instances are sorted front to back. Depending on GPU and the scene, this option may give better performance than SORTMODE_MATERIALMESH due to reduced overdraw.
const SORTMODE_FRONT2BACK: 4 = 4
Variable · category: Graphics
Mesh instances are sorted based on MeshInstance#drawOrder.
const SORTMODE_MANUAL: 1 = 1
Variable · category: Graphics
Mesh instances are sorted to minimize switching between materials and meshes to improve rendering performance.
const SORTMODE_MATERIALMESH: 2 = 2
Variable · category: Graphics
No sorting is applied. Mesh instances are rendered in the same order they were added to a layer.
const SORTMODE_NONE: 0 = 0
Variable · category: Graphics
Use AO directly to occlude specular.
const SPECOCC_AO: 1 = 1
Variable · category: Graphics
Modify AO based on material glossiness/view angle to occlude specular.
const SPECOCC_GLOSSDEPENDENT: 2 = 2
Variable · category: Graphics
No specular occlusion.
const SPECOCC_NONE: 0 = 0
Variable · category: Graphics
This mode renders a sprite as a simple quad.
const SPRITE_RENDERMODE_SIMPLE: 0 = 0
Variable · category: Graphics
This mode renders a sprite using 9-slicing in 'sliced' mode. Sliced mode stretches the top and bottom regions of the sprite horizontally, the left and right regions vertically and the middle region both horizontally and vertically.
const SPRITE_RENDERMODE_SLICED: 1 = 1
Variable · category: Graphics
This mode renders a sprite using 9-slicing in 'tiled' mode. Tiled mode tiles the top and bottom regions of the sprite horizontally, the left and right regions vertically and the middle region both horizontally and vertically.
const SPRITE_RENDERMODE_TILED: 2 = 2
Variable · category: Graphics
A SpriteComponent that renders sprite animations.
const SPRITETYPE_ANIMATED: "animated" = 'animated'
Variable · category: Graphics
A SpriteComponent that displays a single frame from a sprite asset.
const SPRITETYPE_SIMPLE: "simple" = 'simple'
Variable · category: Graphics
SSAO is applied as a standalone effect after the scene is rendered. This method uniformly overlays ambient occlusion across the image, disregarding direct lighting interactions. While this may sacrifice some realism, it can be advantageous for achieving specific artistic styles.
const SSAOTYPE_COMBINE: "combine" = 'combine'
Variable · category: Graphics
SSAO is applied during the lighting calculation stage, allowing it to blend seamlessly with scene lighting. This results in ambient occlusion being more pronounced in areas where direct light is obstructed, enhancing realism.
const SSAOTYPE_LIGHTING: "lighting" = 'lighting'
Variable · category: Graphics
SSAO is disabled.
const SSAOTYPE_NONE: "none" = 'none'
Variable · category: Graphics
Decrement the value.
const STENCILOP_DECREMENT: 5 = 5
Variable · category: Graphics
Decrement the value but wrap it to a maximum representable value if the current value is 0.
const STENCILOP_DECREMENTWRAP: 6 = 6
Variable · category: Graphics
Increment the value.
const STENCILOP_INCREMENT: 3 = 3
Variable · category: Graphics
Increment the value but wrap it to zero when it's larger than a maximum representable value.
const STENCILOP_INCREMENTWRAP: 4 = 4
Variable · category: Graphics
Invert the value bitwise.
const STENCILOP_INVERT: 7 = 7
Variable · category: Graphics
Don't change the stencil buffer value.
const STENCILOP_KEEP: 0 = 0
Variable · category: Graphics
Replace value with the reference value (see StencilParameters).
const STENCILOP_REPLACE: 2 = 2
Variable · category: Graphics
Set value to zero.
const STENCILOP_ZERO: 1 = 1
Variable · category: Graphics
Texture data is stored in a 1-dimensional texture.
const TEXTUREDIMENSION_1D: "1d" = '1d'
Variable · category: Graphics
Texture data is stored in a 2-dimensional texture.
const TEXTUREDIMENSION_2D: "2d" = '2d'
Variable · category: Graphics
Texture data is stored in an array of 2-dimensional textures.
const TEXTUREDIMENSION_2D_ARRAY: "2d-array" = '2d-array'
Variable · category: Graphics
Texture data is stored in a 3-dimensional texture.
const TEXTUREDIMENSION_3D: "3d" = '3d'
Variable · category: Graphics
Texture data is stored in a cube texture.
const TEXTUREDIMENSION_CUBE: "cube" = 'cube'
Variable · category: Graphics
Texture data is stored in an array of cube textures.
const TEXTUREDIMENSION_CUBE_ARRAY: "cube-array" = 'cube-array'
Variable · category: Graphics
The texture is not in a locked state.
const TEXTURELOCK_NONE: 0 = 0
Variable · category: Graphics
Read only. Any changes to the locked mip level's pixels will not update the texture.
const TEXTURELOCK_READ: 1 = 1
Variable · category: Graphics
Write only. The contents of the specified mip level will be entirely replaced.
const TEXTURELOCK_WRITE: 2 = 2
Variable · category: Graphics
Texture data is stored in cubemap projection format.
const TEXTUREPROJECTION_CUBE: "cube" = 'cube'
Variable · category: Graphics
Texture data is stored in equirectangular projection format.
const TEXTUREPROJECTION_EQUIRECT: "equirect" = 'equirect'
Variable · category: Graphics
Texture data is not stored a specific projection format.
const TEXTUREPROJECTION_NONE: "none" = 'none'
Variable · category: Graphics
Texture data is stored in octahedral projection format.
const TEXTUREPROJECTION_OCTAHEDRAL: "octahedral" = 'octahedral'
Variable · category: Graphics
Texture is a default type.
const TEXTURETYPE_DEFAULT: "default" = 'default'
Variable · category: Graphics
Texture stores high dynamic range data in RGBE format.
const TEXTURETYPE_RGBE: "rgbe" = 'rgbe'
Variable · category: Graphics
Texture stores high dynamic range data in RGBM format.
const TEXTURETYPE_RGBM: "rgbm" = 'rgbm'
Variable · category: Graphics
Texture stores high dynamic range data in RGBP encoding.
const TEXTURETYPE_RGBP: "rgbp" = 'rgbp'
Variable · category: Graphics
Texture stores normalmap data swizzled in GGGR format. This is used for tangent space normal maps. The R component is stored in alpha and G is stored in RGB. This packing can result in higher quality when the texture data is compressed.
const TEXTURETYPE_SWIZZLEGGGR: "swizzleGGGR" = 'swizzleGGGR'
Variable · category: Graphics
ACES filmic tonemapping curve.
const TONEMAP_ACES: 3 = 3
Variable · category: Graphics
ACES v2 filmic tonemapping curve.
const TONEMAP_ACES2: 4 = 4
Variable · category: Graphics
Filmic tonemapping curve.
const TONEMAP_FILMIC: 1 = 1
Variable · category: Graphics
Hejl filmic tonemapping curve.
const TONEMAP_HEJL: 2 = 2
Variable · category: Graphics
Linear tonemapping. The colors are preserved, but the exposure is applied.
const TONEMAP_LINEAR: 0 = 0
Variable · category: Graphics
Khronos PBR Neutral tonemapping curve.
const TONEMAP_NEUTRAL: 5 = 5
Variable · category: Graphics
No tonemapping or exposure is applied. Used for HDR rendering.
const TONEMAP_NONE: 6 = 6
Variable · category: Debug
Logs all assets in the asset registry.
const TRACEID_ASSETS: "Assets" = 'Assets'
Variable · category: Debug
Logs the creation of bind groups.
const TRACEID_BINDGROUP_ALLOC: "BindGroupAlloc" = 'BindGroupAlloc'
Variable · category: Debug
Logs the creation of bind group formats.
const TRACEID_BINDGROUPFORMAT_ALLOC: "BindGroupFormatAlloc" = 'BindGroupFormatAlloc'
Variable · category: Debug
Logs GPU buffer memory tracked on the graphics device (vertex, index, storage).
const TRACEID_BUFFERS: "Buffers" = 'Buffers'
Variable · category: Debug
Logs the creation of compute pipelines. WebGPU only.
const TRACEID_COMPUTEPIPELINE_ALLOC: "ComputePipelineAlloc" = 'ComputePipelineAlloc'
Variable · category: Debug
Logs the internal debug information for Elements.
const TRACEID_ELEMENT: "Element" = 'Element'
Variable · category: Debug
Logs the GPU timings.
const TRACEID_GPU_TIMINGS: "GpuTimings" = 'GpuTimings'
Variable · category: Debug
Records where a material was created and last changed, so that the debug build can report them when a material property is changed without a subsequent call to Material#update.
const TRACEID_MATERIAL_UPDATE: "MaterialUpdate" = 'MaterialUpdate'
Variable · category: Debug
Logs the loaded GSplat resources for individual LOD levels of an octree.
const TRACEID_OCTREE_RESOURCES: "OctreeResources" = 'OctreeResources'
Variable · category: Debug
Logs the creation of pipeline layouts. WebGPU only.
const TRACEID_PIPELINELAYOUT_ALLOC: "PipelineLayoutAlloc" = 'PipelineLayoutAlloc'
Variable · category: Debug
Logs render actions created by the layer composition. Only executes when the layer composition changes.
const TRACEID_RENDER_ACTION: "RenderAction" = 'RenderAction'
Variable · category: Debug
Logs a frame number.
const TRACEID_RENDER_FRAME: "RenderFrame" = 'RenderFrame'
Variable · category: Debug
Logs a frame time.
const TRACEID_RENDER_FRAME_TIME: "RenderFrameTime" = 'RenderFrameTime'
Variable · category: Debug
Logs basic information about generated render passes.
const TRACEID_RENDER_PASS: "RenderPass" = 'RenderPass'
Variable · category: Debug
Logs additional detail for render passes.
const TRACEID_RENDER_PASS_DETAIL: "RenderPassDetail" = 'RenderPassDetail'
Variable · category: Debug
Logs the render queue commands.
const TRACEID_RENDER_QUEUE: "RenderQueue" = 'RenderQueue'
Variable · category: Debug
Logs the allocation of render targets.
const TRACEID_RENDER_TARGET_ALLOC: "RenderTargetAlloc" = 'RenderTargetAlloc'
Variable · category: Debug
Logs the creation of render pipelines. WebGPU only.
const TRACEID_RENDERPIPELINE_ALLOC: "RenderPipelineAlloc" = 'RenderPipelineAlloc'
Variable · category: Debug
Logs the creation of shaders.
const TRACEID_SHADER_ALLOC: "ShaderAlloc" = 'ShaderAlloc'
Variable · category: Debug
Logs the compilation time of shaders.
const TRACEID_SHADER_COMPILE: "ShaderCompile" = 'ShaderCompile'
Variable · category: Debug
Logs the allocation of textures.
const TRACEID_TEXTURE_ALLOC: "TextureAlloc" = 'TextureAlloc'
Variable · category: Debug
Logs the vram use by all textures in memory.
const TRACEID_TEXTURES: "Textures" = 'Textures'
Variable · category: Debug
Logs the vram use by the index buffers.
const TRACEID_VRAM_IB: "VRAM.Ib" = 'VRAM.Ib'
Variable · category: Debug
Logs the vram use by the storage buffers.
const TRACEID_VRAM_SB: "VRAM.Sb" = 'VRAM.Sb'
Variable · category: Debug
Logs the vram use by the textures.
const TRACEID_VRAM_TEXTURE: "VRAM.Texture" = 'VRAM.Texture'
Variable · category: Debug
Logs the vram use by the vertex buffers.
const TRACEID_VRAM_VB: "VRAM.Vb" = 'VRAM.Vb'
Variable · category: Graphics
Captures all varyings into one interleaved transform feedback buffer.
const TRANSFORM_FEEDBACK_INTERLEAVED: 0 = 0
Variable · category: Graphics
Captures each varying into its own transform feedback buffer.
const TRANSFORM_FEEDBACK_SEPARATE: 1 = 1
Variable · category: Graphics
16-bit floating point vertex element type.
const TYPE_FLOAT16: 7 = 7
Variable · category: Graphics
Floating point vertex element type.
const TYPE_FLOAT32: 6 = 6
Variable · category: Graphics
Signed short vertex element type.
const TYPE_INT16: 2 = 2
Variable · category: Graphics
Signed integer vertex element type.
const TYPE_INT32: 4 = 4
Variable · category: Graphics
Signed byte vertex element type.
const TYPE_INT8: 0 = 0
Variable · category: Graphics
Unsigned short vertex element type.
const TYPE_UINT16: 3 = 3
Variable · category: Graphics
Unsigned integer vertex element type.
const TYPE_UINT32: 5 = 5
Variable · category: Graphics
Unsigned byte vertex element type.
const TYPE_UINT8: 1 = 1
Variable · category: Graphics
Boolean uniform type.
const UNIFORMTYPE_BOOL: 0 = 0
Variable · category: Graphics
2 x Boolean uniform type.
const UNIFORMTYPE_BVEC2: 9 = 9
Variable · category: Graphics
3 x Boolean uniform type.
const UNIFORMTYPE_BVEC3: 10 = 10
Variable · category: Graphics
4 x Boolean uniform type.
const UNIFORMTYPE_BVEC4: 11 = 11
Variable · category: Graphics
Float uniform type.
const UNIFORMTYPE_FLOAT: 2 = 2
Variable · category: Graphics
Integer uniform type.
const UNIFORMTYPE_INT: 1 = 1
Variable · category: Graphics
2 x Integer uniform type.
const UNIFORMTYPE_IVEC2: 6 = 6
Variable · category: Graphics
3 x Integer uniform type.
const UNIFORMTYPE_IVEC3: 7 = 7
Variable · category: Graphics
4 x Integer uniform type.
const UNIFORMTYPE_IVEC4: 8 = 8
Variable · category: Graphics
2 x 2 x Float uniform type.
const UNIFORMTYPE_MAT2: 12 = 12
Variable · category: Graphics
3 x 3 x Float uniform type.
const UNIFORMTYPE_MAT3: 13 = 13
Variable · category: Graphics
4 x 4 x Float uniform type.
const UNIFORMTYPE_MAT4: 14 = 14
Variable · category: Graphics
Unsigned integer uniform type.
const UNIFORMTYPE_UINT: 26 = 26
Variable · category: Graphics
2 x Unsigned integer uniform type.
const UNIFORMTYPE_UVEC2: 27 = 27
Variable · category: Graphics
3 x Unsigned integer uniform type.
const UNIFORMTYPE_UVEC3: 28 = 28
Variable · category: Graphics
4 x Unsigned integer uniform type.
const UNIFORMTYPE_UVEC4: 29 = 29
Variable · category: Graphics
2 x Float uniform type.
const UNIFORMTYPE_VEC2: 3 = 3
Variable · category: Graphics
3 x Float uniform type.
const UNIFORMTYPE_VEC3: 4 = 4
Variable · category: Graphics
4 x Float uniform type.
const UNIFORMTYPE_VEC4: 5 = 5
Variable · category: Graphics
Center of view.
const VIEW_CENTER: 0 = 0
Variable · category: Graphics
Left of view. Only used in stereo rendering.
const VIEW_LEFT: 1 = 1
Variable · category: Graphics
Right of view. Only used in stereo rendering.
const VIEW_RIGHT: 2 = 2
Variable · category: Graphics
Work buffer is updated every frame. Useful for custom shader code via GSplatComponent#setWorkBufferModifier that depends on time or animated uniforms.
const WORKBUFFER_UPDATE_ALWAYS: number = 2
Variable · category: Graphics
Work buffer is updated only when needed (transform, format, LOD changes, new gsplat etc).
const WORKBUFFER_UPDATE_AUTO: number = 0
Variable · category: Graphics
Work buffer is updated once on the next frame, then automatically switches to WORKBUFFER_UPDATE_AUTO.
const WORKBUFFER_UPDATE_ONCE: number = 1
Variable · category: XR
Float 32 - indicates that depth sensing preferred raw data format is Float (32 bit).
const XRDEPTHSENSINGFORMAT_F32: "float32" = 'float32'
Variable · category: XR
Luminance Alpha - indicates that depth sensing preferred raw data format is Luminance Alpha (8bit + 8bit). This format is guaranteed to be supported.
const XRDEPTHSENSINGFORMAT_L8A8: "luminance-alpha" = 'luminance-alpha'
Variable · category: XR
Unsigned Short - indicates that depth sensing preferred raw data format is Unsigned Short (16 bit).
const XRDEPTHSENSINGFORMAT_R16U: "unsigned-short" = 'unsigned-short'
Variable · category: XR
CPU - indicates that depth sensing preferred usage is CPU. This usage path is guaranteed to be supported.
const XRDEPTHSENSINGUSAGE_CPU: "cpu-optimized" = 'cpu-optimized'
Variable · category: XR
GPU - indicates that depth sensing preferred usage is GPU.
const XRDEPTHSENSINGUSAGE_GPU: "gpu-optimized" = 'gpu-optimized'
Variable · category: XR
Left - view associated with left eye.
const XREYE_LEFT: "left" = 'left'
Variable · category: XR
None - view associated with a monoscopic screen, such as mobile phone screens.
const XREYE_NONE: "none" = 'none'
Variable · category: XR
Right - view associated with right eye.
const XREYE_RIGHT: "right" = 'right'
Variable · category: XR
Left - indicates that input source is meant to be held in left hand.
const XRHAND_LEFT: "left" = 'left'
Variable · category: XR
None - input source is not meant to be held in hands.
const XRHAND_NONE: "none" = 'none'
Variable · category: XR
Right - indicates that input source is meant to be held in right hand.
const XRHAND_RIGHT: "right" = 'right'
Variable · category: Input Devices
The A button from XR pad.
const XRPAD_A: 4 = 4
Variable · category: Input Devices
The B button from XR pad.
const XRPAD_B: 5 = 5
Variable · category: Input Devices
The squeeze button from XR pad.
const XRPAD_SQUEEZE: 1 = 1
Variable · category: Input Devices
The button when pressing the XR pad's stick.
const XRPAD_STICK_BUTTON: 3 = 3
Variable · category: Input Devices
Horizontal axis on the stick of an XR pad.
const XRPAD_STICK_X: 2 = 2
Variable · category: Input Devices
Vertical axis on the stick of an XR pad.
const XRPAD_STICK_Y: 3 = 3
Variable · category: Input Devices
The button when pressing the XR pad's touchpad.
const XRPAD_TOUCHPAD_BUTTON: 2 = 2
Variable · category: Input Devices
Horizontal axis on the touchpad of an XR pad.
const XRPAD_TOUCHPAD_X: 0 = 0
Variable · category: Input Devices
Vertical axis on the touchpad of an XR pad.
const XRPAD_TOUCHPAD_Y: 1 = 1
Variable · category: Input Devices
The trigger button from XR pad.
const XRPAD_TRIGGER: 0 = 0
Variable · category: XR
Bounded Floor - represents a tracking space with its native origin at the floor, where the user is expected to move within a pre-established boundary. Tracking in a bounded-floor reference space is optimized for keeping the native origin and bounds geometry stable relative to the user's environment.
const XRSPACE_BOUNDEDFLOOR: "bounded-floor" = 'bounded-floor'
Variable · category: XR
Local - represents a tracking space with a native origin near the viewer at the time of creation. The exact position and orientation will be initialized based on the conventions of the underlying platform. When using this reference space the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with 6DoF tracking, local reference spaces should emphasize keeping the origin stable relative to the user's environment.
const XRSPACE_LOCAL: "local" = 'local'
Variable · category: XR
Local Floor - represents a tracking space with a native origin at the floor in a safe position for the user to stand. The y axis equals 0 at floor level, with the x and z position and orientation initialized based on the conventions of the underlying platform. Floor level value might be estimated by the underlying platform. When using this reference space, the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with 6DoF tracking, local-floor reference spaces should emphasize keeping the origin stable relative to the user's environment.
const XRSPACE_LOCALFLOOR: "local-floor" = 'local-floor'
Variable · category: XR
Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially even long distances from their starting point. Tracking in an unbounded reference space is optimized for stability around the user's current position, and as such the native origin may drift over time.
const XRSPACE_UNBOUNDED: "unbounded" = 'unbounded'
Variable · category: XR
Viewer - always supported space with some basic tracking capabilities.
const XRSPACE_VIEWER: "viewer" = 'viewer'
Variable · category: XR
Gaze - indicates the target ray will originate at the viewer and follow the direction it is facing. This is commonly referred to as a "gaze input" device in the context of head-mounted displays.
const XRTARGETRAY_GAZE: "gaze" = 'gaze'
Variable · category: XR
Tracked Pointer - indicates that the target ray originates from either a handheld device or other hand-tracking mechanism and represents that the user is using their hands or the held device for pointing.
const XRTARGETRAY_POINTER: "tracked-pointer" = 'tracked-pointer'
Variable · category: XR
Screen - indicates that the input source was an interaction with the canvas element associated with an inline session's output context, such as a mouse click or touch event.
const XRTARGETRAY_SCREEN: "screen" = 'screen'
Variable · category: XR
Mesh - indicates that the hit test results will be computed based on the meshes detected by the underlying Augmented Reality system.
const XRTRACKABLE_MESH: "mesh" = 'mesh'
Variable · category: XR
Plane - indicates that the hit test results will be computed based on the planes detected by the underlying Augmented Reality system.
const XRTRACKABLE_PLANE: "plane" = 'plane'
Variable · category: XR
Point - indicates that the hit test results will be computed based on the feature points detected by the underlying Augmented Reality system.
const XRTRACKABLE_POINT: "point" = 'point'
Variable · category: XR
Immersive AR - session that provides exclusive access to VR/AR device that is intended to be blended with real-world environment.
const XRTYPE_AR: "immersive-ar" = 'immersive-ar'
Variable · category: XR
Inline - always available type of session. It has limited features availability and is rendered into HTML element.
const XRTYPE_INLINE: "inline" = 'inline'
Variable · category: XR
Immersive VR - session that provides exclusive access to VR device with best available tracking features.
const XRTYPE_VR: "immersive-vr" = 'immersive-vr'