# PlayCanvas Engine API: All Pages > 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. Index: https://api.playcanvas.com/engine/llms.txt Total Pages: 1102 Generated: 2026-10-08 ================================================================================ URL: https://api.playcanvas.com/engine/classes/AnimBlendTree.md # AnimBlendTree Class · extends [`AnimNode`](https://api.playcanvas.com/engine/classes/AnimNode.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree.js#L23 AnimBlendTrees are used to store and blend multiple [AnimNode](https://api.playcanvas.com/engine/classes/AnimNode.md)s 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](https://api.playcanvas.com/engine/variables/ANIM_BLEND_1D.md), [ANIM_BLEND_2D_DIRECTIONAL](https://api.playcanvas.com/engine/variables/ANIM_BLEND_2D_DIRECTIONAL.md), [ANIM_BLEND_2D_CARTESIAN](https://api.playcanvas.com/engine/variables/ANIM_BLEND_2D_CARTESIAN.md) and [ANIM_BLEND_DIRECT](https://api.playcanvas.com/engine/variables/ANIM_BLEND_DIRECT.md), 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](https://api.playcanvas.com/engine/classes/AnimStateGraph.md) and built when it loads. ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/AnimState.md)): The AnimState that this AnimBlendTree belongs to. - `parent` ([`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) `| null`): The parent of the AnimBlendTree. If not null, the AnimNode is stored as part of a [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) hierarchy. - `name` (`string`): The name of the BlendTree. Used when assigning an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) to its children. - `point` (`number |` [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The coordinate/vector that's used to determine the weight of this node when it's part of an [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md). - `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](https://api.playcanvas.com/engine/classes/AnimNode.md) or [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md). - `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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimBlendTree1D.md # AnimBlendTree1D Class · extends [`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-1d.js#L19 An AnimBlendTree that calculates its weights using the 1D algorithm from chapter 6 of [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). 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. ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/AnimState.md)): The AnimState that this AnimBlendTree belongs to. - `parent` ([`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) `| null`): The parent of the AnimBlendTree. If not null, the AnimNode is stored as part of a [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) hierarchy. - `name` (`string`): The name of the BlendTree. Used when assigning an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) to its children. - `point` (`number |` [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The coordinate/vector that's used to determine the weight of this node when it's part of an [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md). - `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](https://api.playcanvas.com/engine/classes/AnimNode.md) or [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md). - `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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimBlendTreeCartesian2D.md # AnimBlendTreeCartesian2D Class · extends [`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js#L17 An AnimBlendTree that calculates its weights using the 2D Cartesian algorithm from chapter 6, section 3 of [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). 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. ## Inherited from [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) - `new AnimBlendTreeCartesian2D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimBlendTreeDirect.md # AnimBlendTreeDirect Class · extends [`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-direct.js#L10 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. ## Inherited from [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) - `new AnimBlendTreeDirect(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimBlendTreeDirectional2D.md # AnimBlendTreeDirectional2D Class · extends [`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-2d-directional.js#L16 An AnimBlendTree that calculates its weights using the 2D directional algorithm from chapter 6 of [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). 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. ## Inherited from [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) - `new AnimBlendTreeDirectional2D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimComponent.md # AnimComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/component.js#L54 The AnimComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#anim) property: ```javascript 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: - [1D Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-1d) - [2D Cartesian Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-2d-cartesian) - [2D Directional Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-2d-directional) - [Animation Events](https://playcanvas.github.io/#/animation/events) - [Component Properties](https://playcanvas.github.io/#/animation/component-properties) - [Layer Masks](https://playcanvas.github.io/#/animation/layer-masks) - [Locomotion](https://playcanvas.github.io/#/animation/locomotion) ## Accessors ### activate ```ts get activate(): boolean set activate(value: boolean) ``` Gets whether the first animation will begin playing when the scene is loaded. ### baseLayer ```ts get baseLayer(): AnimComponentLayer | null ``` Returns the base layer of the state graph. ### layers ```ts get layers(): readonly AnimComponentLayer[] ``` Returns the animation layers available in this anim component. Use addLayer or loadStateGraph to change layers. ### normalizeWeights ```ts get normalizeWeights(): boolean set normalizeWeights(value: boolean) ``` Gets whether the animation component will normalize the weights of its layers by their sum total. ### playable ```ts get playable(): boolean ``` Returns whether all component layers are currently playable. ### playing ```ts get playing(): boolean set playing(value: boolean) ``` Gets whether to play or pause all animations in the component. ### rootBone ```ts get rootBone(): Entity set rootBone(value: Entity) ``` Gets the entity that this anim component should use as the root of the animation hierarchy. ### speed ```ts get speed(): number set speed(value: number) ``` Gets the speed multiplier for animation play back speed. ## Methods ### addLayer ```ts 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`](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md): The created anim component layer. ### assignAnimation ```ts 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](https://api.playcanvas.com/engine/classes/AnimComponent.md#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`](https://api.playcanvas.com/engine/classes/AnimTrack.md)): 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 ```ts findAnimationLayer(name: string): AnimComponentLayer ``` Finds an [AnimComponentLayer](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md) in this component. **Parameters** - `name` (`string`): The name of the anim component layer to find. **Returns** [`AnimComponentLayer`](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md): Layer. ### getBoolean ```ts 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 ```ts 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 ```ts 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 ```ts 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 ```ts 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** ```ts 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 ```ts rebind(): void ``` Rebind all of the components layers. ### removeNodeAnimations ```ts 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 ```ts removeStateGraph(): void ``` Removes all layers from the anim component. ### reset ```ts 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 ```ts 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 ```ts 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 ```ts 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 ```ts 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 ```ts 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. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimComponentLayer.md # AnimComponentLayer Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/component-layer.js#L34 An AnimComponentLayer is one layer of an [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md). It runs the state machine that the [AnimStateGraph](https://api.playcanvas.com/engine/classes/AnimStateGraph.md) defines for that layer and contributes the result to the entity's final pose with a [weight](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#weight), either overwriting the layers beneath it or adding to them according to `blendType`. A [mask](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#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](https://api.playcanvas.com/engine/classes/AnimComponent.md#baselayer); add more with [AnimComponent#addLayer](https://api.playcanvas.com/engine/classes/AnimComponent.md#addlayer). Playback is per layer: [play](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#play) starts a named state, [transition](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#transition) blends to another state over a given time, [pause](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#pause) and [reset](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#reset) act on the current state, and [activeState](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#activestate), [activeStateProgress](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#activestateprogress) and [transitioning](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#transitioning) report where the layer is. [assignAnimation](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#assignanimation) binds an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) to a state, or to a node inside a blend tree using a dotted path, and [blendToWeight](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#blendtoweight) fades the whole layer in or out. **Example** ```ts // 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'); ``` ## Accessors ### activeState ```ts get activeState(): string ``` Gets the currently active state name. ### activeStateCurrentTime ```ts get activeStateCurrentTime(): number set activeStateCurrentTime(time: number) ``` Gets the active state's time in seconds. ### activeStateDuration ```ts get activeStateDuration(): number ``` Gets the currently active states duration. ### activeStateProgress ```ts 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. ### mask ```ts get mask(): any set mask(value: any) ``` Gets the mask of bones which should be animated or ignored by this layer. ### name ```ts get name(): string ``` Returns the name of the layer. ### playable ```ts get playable(): boolean ``` Returns true if a state graph has been loaded and all states in the graph have been assigned animation tracks. ### playing ```ts get playing(): boolean set playing(value: boolean) ``` Gets whether this layer is currently playing. ### previousState ```ts get previousState(): string | null ``` Gets the previously active state name. ### states ```ts get states(): string[] ``` Gets all available states in this layers state graph. ### transitioning ```ts get transitioning(): boolean ``` Gets whether the anim component layer is currently transitioning between states. ### transitionProgress ```ts get transitionProgress(): number | null ``` Gets the progress, if the anim component layer is currently transitioning between states. Otherwise returns null. ### weight ```ts get weight(): number set weight(value: number) ``` Sets the blending weight of this layer. ## Methods ### assignAnimation ```ts 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](https://api.playcanvas.com/engine/classes/AnimComponent.md#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`](https://api.playcanvas.com/engine/classes/AnimTrack.md)): 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 ```ts 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 ```ts 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 ```ts pause(): void ``` Pause the animation in the current state. ### play ```ts 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 ```ts rebind(): void ``` Rebind any animations in the layer to the currently present components and model of the anim components entity. ### removeNodeAnimations ```ts 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 ```ts reset(): void ``` Reset the animation component to its initial state, including all parameters. The system will be paused. ### transition ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimComponentSystem.md # AnimComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/system.js#L33 Manages the [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md)s of an application and advances their state graphs each frame. Reach it through `app.systems.anim`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimCurve.md # AnimCurve Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-curve.js#L24 Animation curve links an input data set to an output data set and defines the interpolation method to use. The [paths](https://api.playcanvas.com/engine/classes/AnimCurve.md#paths) name the targets the curve drives, [input](https://api.playcanvas.com/engine/classes/AnimCurve.md#input) and [output](https://api.playcanvas.com/engine/classes/AnimCurve.md#output) index into the owning [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md)'s keyframe time and value data, and [interpolation](https://api.playcanvas.com/engine/classes/AnimCurve.md#interpolation) is one of [INTERPOLATION_STEP](https://api.playcanvas.com/engine/variables/INTERPOLATION_STEP.md), [INTERPOLATION_LINEAR](https://api.playcanvas.com/engine/variables/INTERPOLATION_LINEAR.md) or [INTERPOLATION_CUBIC](https://api.playcanvas.com/engine/variables/INTERPOLATION_CUBIC.md). ## Constructors ### constructor ```ts new AnimCurve(paths: AnimCurvePath[], input: number, output: number, interpolation: number) ``` Create a new animation curve. **Parameters** - `paths` ([`AnimCurvePath`](https://api.playcanvas.com/engine/interfaces/AnimCurvePath.md)`[]`): 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: - [INTERPOLATION_STEP](https://api.playcanvas.com/engine/variables/INTERPOLATION_STEP.md) - [INTERPOLATION_LINEAR](https://api.playcanvas.com/engine/variables/INTERPOLATION_LINEAR.md) - [INTERPOLATION_CUBIC](https://api.playcanvas.com/engine/variables/INTERPOLATION_CUBIC.md) ## Accessors ### input ```ts get input(): number ``` The index of the AnimTrack input which contains the key data for this curve. ### interpolation ```ts get interpolation(): number ``` The interpolation method used by this curve. ### output ```ts get output(): number ``` The index of the AnimTrack input which contains the key data for this curve. ### paths ```ts get paths(): AnimCurvePath[] ``` The list of paths which identify targets of this curve. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimData.md # AnimData Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-data.js#L8 Wraps a set of data used in animation: a flat [data](https://api.playcanvas.com/engine/classes/AnimData.md#data) array read [components](https://api.playcanvas.com/engine/classes/AnimData.md#components) values at a time, so a three-component set holds positions and a four-component set holds quaternions. An [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) keeps its keyframe times and values as AnimData that its curves index into. ## Constructors ### constructor ```ts new AnimData(components: number, data: number[] | Float32Array) ``` 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`): The set of data. ## Accessors ### components ```ts get components(): number ``` Gets the number of components that make up an element. ### data ```ts get data(): number[] | Float32Array ``` Gets the data. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimEvents.md # AnimEvents Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-events.js#L10 AnimEvents stores a sorted array of animation events which should fire sequentially during the playback of an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md). 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](https://api.playcanvas.com/engine/classes/AnimComponent.md) under the event's name, so a script listens with `entity.anim.on('footstep', callback)` and receives the event object. ## Constructors ### constructor ```ts new AnimEvents(events: any[]) ``` Create a new AnimEvents instance. **Parameters** - `events` (`any[]`): An array of animation events. **Example** ```ts 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; ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimNode.md # AnimNode Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-node.js#L19 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. ## Constructors ### constructor ```ts new AnimNode(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | number[], speed?: number) ``` Create a new AnimNode instance. **Parameters** - `state` ([`AnimState`](https://api.playcanvas.com/engine/classes/AnimState.md)): The AnimState that this BlendTree belongs to. - `parent` ([`AnimBlendTree`](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) `| null`): The parent of the AnimNode. If not null, the AnimNode is stored as part of an [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) hierarchy. - `name` (`string`): The name of the AnimNode. Used when assigning an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) 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](https://api.playcanvas.com/engine/classes/AnimBlendTree.md). - `speed` (`number`, optional, default `1`): The speed that its [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) should play at. Defaults to 1. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimState.md # AnimState Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-state.js#L29 Defines a single state that the controller can be in. Each state contains either a single [AnimNode](https://api.playcanvas.com/engine/classes/AnimNode.md) or an [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) of multiple [AnimNode](https://api.playcanvas.com/engine/classes/AnimNode.md)s, which will be used to animate the [Entity](https://api.playcanvas.com/engine/classes/Entity.md) while the state is active. An AnimState will stay active and play as long as there is no [AnimTransition](https://api.playcanvas.com/engine/classes/AnimTransition.md) 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](https://api.playcanvas.com/engine/classes/AnimStateGraph.md) and entered either by a transition or directly with [AnimComponentLayer#play](https://api.playcanvas.com/engine/classes/AnimComponentLayer.md#play). ## Constructors ### constructor ```ts 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 [AnimNode](https://api.playcanvas.com/engine/classes/AnimNode.md)s 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](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) hierarchy, used to store, blend and play multiple animations. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimStateGraph.md # AnimStateGraph Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/state-graph/anim-state-graph.js#L21 An asset resource which represents an anim state graph. It can be loaded into an anim component using the [AnimComponent#loadStateGraph](https://api.playcanvas.com/engine/classes/AnimComponent.md#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](https://api.playcanvas.com/engine/classes/AnimState.md), [AnimTransition](https://api.playcanvas.com/engine/classes/AnimTransition.md) and [AnimBlendTree](https://api.playcanvas.com/engine/classes/AnimBlendTree.md) objects, and [AnimComponent#assignAnimation](https://api.playcanvas.com/engine/classes/AnimComponent.md#assignanimation) then attaches an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) to each state. One graph can drive any number of components. ## Usage Scripts can retrieve an AnimStateGraph instance from assets of type 'animstategraph'. An AnimStateGraph can then be loaded into an anim component as follows: ```javascript const animStateGraph = app.assets.get(ASSET_ID).resource; const entity = new Entity(); entity.addComponent('anim'); entity.anim.loadStateGraph(animStateGraph); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimTrack.md # AnimTrack Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-track.js#L21 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](https://api.playcanvas.com/engine/classes/AnimComponent.md#assignanimation) method. A track is the engine's animation clip: a [name](https://api.playcanvas.com/engine/classes/AnimTrack.md#name), a [duration](https://api.playcanvas.com/engine/classes/AnimTrack.md#duration) in seconds and a list of [curves](https://api.playcanvas.com/engine/classes/AnimTrack.md#curves), each of which reads keyframe times from one of the [inputs](https://api.playcanvas.com/engine/classes/AnimTrack.md#inputs) and values from one of the [outputs](https://api.playcanvas.com/engine/classes/AnimTrack.md#outputs), and writes the result to a target path such as a node's local position or a component property. Optional [events](https://api.playcanvas.com/engine/classes/AnimTrack.md#events) fire at set times during playback. Tracks come from `animation` assets, GLB animations among them, and are what an [AnimState](https://api.playcanvas.com/engine/classes/AnimState.md) plays; one track can be assigned in any number of components. ## Properties ### EMPTY ```ts static EMPTY: AnimTrack ``` This AnimTrack can be used as a placeholder track when creating a state graph before having all associated animation data available. ## Accessors ### curves ```ts get curves(): AnimCurve[] ``` Gets the list of curves contained in the AnimTrack. ### duration ```ts get duration(): number ``` Gets the duration of the AnimTrack. ### events ```ts get events(): AnimEvents set events(animEvents: AnimEvents) ``` Gets the animation events that will fire during the playback of this anim track. ### inputs ```ts get inputs(): AnimData[] ``` Gets the list of curve key data contained in the AnimTrack. ### name ```ts get name(): string ``` Gets the name of the AnimTrack. ### outputs ```ts get outputs(): AnimData[] ``` Gets the list of curve values contained in the AnimTrack. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimTransition.md # AnimTransition Class · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-transition.js#L20 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](https://api.playcanvas.com/engine/variables/ANIM_GREATER_THAN.md) or [ANIM_EQUAL_TO](https://api.playcanvas.com/engine/variables/ANIM_EQUAL_TO.md). `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](https://api.playcanvas.com/engine/variables/ANIM_STATE_ANY.md) state so that it applies from every state. ## Constructors ### constructor ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Animation.md # Animation Class · category: Animation (Legacy) Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/animation.js#L36 An Animation contains the data that defines how a [Skeleton](https://api.playcanvas.com/engine/classes/Skeleton.md) animates over time. The Animation contains an array of [AnimationNode](https://api.playcanvas.com/engine/classes/AnimationNode.md)s, where each AnimationNode targets a specific [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md) referenced by a [Skeleton](https://api.playcanvas.com/engine/classes/Skeleton.md). An Animation can be played back by an [AnimationComponent](https://api.playcanvas.com/engine/classes/AnimationComponent.md). ## Constructors ### constructor ```ts new Animation() ``` Create a new Animation instance. ## Properties ### duration ```ts duration: number = 0 ``` Duration of the animation in seconds. ### name ```ts name: string = '' ``` Human-readable name of the animation. ## Accessors ### nodes ```ts get nodes(): AnimationNode[] ``` A read-only property to get array of animation nodes. ## Methods ### addNode ```ts addNode(node: AnimationNode): void ``` Adds a node to the internal nodes array. **Parameters** - `node` ([`AnimationNode`](https://api.playcanvas.com/engine/classes/AnimationNode.md)): The node to add. ### getNode ```ts getNode(name: string): AnimationNode ``` Gets a [AnimationNode](https://api.playcanvas.com/engine/classes/AnimationNode.md) by name. **Parameters** - `name` (`string`): The name of the [AnimationNode](https://api.playcanvas.com/engine/classes/AnimationNode.md). **Returns** [`AnimationNode`](https://api.playcanvas.com/engine/classes/AnimationNode.md): The [AnimationNode](https://api.playcanvas.com/engine/classes/AnimationNode.md) with the specified name. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimationComponent.md # AnimationComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Animation (Legacy) Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/animation/component.js#L43 The AnimationComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to play back skeletal animations on a model. It is a legacy component that has largely been superseded by [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md), 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#animation) property: ```javascript entity.animation.speed = 2; // Play the animation at double speed console.log(entity.animation.speed); // Get the playback speed and print it ``` ## Properties ### activate ```ts activate: boolean = true ``` If true, the first animation asset will begin playing when the scene is loaded. ### skeleton ```ts 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 ```ts speed: number = 1 ``` Speed multiplier for animation play back. 1 is playback at normal speed and 0 pauses the animation. ## Accessors ### animations ```ts get animations(): {} set animations(value: {}) ``` Gets the dictionary of animations by name. ### assets ```ts get assets(): (number | Asset)[] set assets(value: (number | Asset)[]) ``` Gets the array of animation assets or asset ids. ### currentTime ```ts get currentTime(): number set currentTime(currentTime: number) ``` Gets the current time position (in seconds) of the animation. ### duration ```ts get duration(): number ``` Gets the duration in seconds of the current animation. Returns 0 if no animation is playing. ### loop ```ts get loop(): boolean set loop(value: boolean) ``` Gets whether the animation will restart from the beginning when it reaches the end. ## Methods ### getAnimation ```ts getAnimation(name: string): Animation ``` Return an animation. **Parameters** - `name` (`string`): The name of the animation asset. **Returns** [`Animation`](https://api.playcanvas.com/engine/classes/Animation.md): An Animation. ### play ```ts 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. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimationComponentSystem.md # AnimationComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Animation (Legacy) Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/animation/system.js#L21 Manages the [AnimationComponent](https://api.playcanvas.com/engine/classes/AnimationComponent.md)s of an application, the legacy animation system. Reach it through `app.systems.animation`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. New work should use [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md). ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimationNode.md # AnimationNode Class · category: Animation (Legacy) Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/animation.js#L17 AnimationNode represents an array of keyframes that animate the transform of a [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md) over time. Typically, an [Animation](https://api.playcanvas.com/engine/classes/Animation.md) maintains a collection of AnimationNodes, one for each GraphNode in a [Skeleton](https://api.playcanvas.com/engine/classes/Skeleton.md). ## Constructors ### constructor ```ts new AnimationNode() ``` Create a new AnimationNode instance. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Skeleton.md # Skeleton Class · category: Animation (Legacy) Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/skeleton.js#L39 Represents a skeleton used to play animations. ## Constructors ### constructor ```ts new Skeleton(graph: GraphNode) ``` Create a new Skeleton instance. **Parameters** - `graph` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The root [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md) of the skeleton. ## Properties ### looping ```ts looping: boolean = true ``` Determines whether skeleton is looping its animation. ## Accessors ### animation ```ts get animation(): Animation set animation(value: Animation) ``` Gets the animation on the skeleton. ### currentTime ```ts get currentTime(): number set currentTime(value: number) ``` Gets the current time of the currently active animation in seconds. ### numNodes ```ts get numNodes(): number ``` Gets the number of nodes in the skeleton. ## Methods ### addTime ```ts 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 ```ts blend(skel1: Skeleton, skel2: Skeleton, alpha: number): void ``` Blends two skeletons together. **Parameters** - `skel1` ([`Skeleton`](https://api.playcanvas.com/engine/classes/Skeleton.md)): Skeleton holding the first pose to be blended. - `skel2` ([`Skeleton`](https://api.playcanvas.com/engine/classes/Skeleton.md)): 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 ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The root node of the graph that the skeleton is to drive. ### updateGraph ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AnimationHandler.md # AnimationHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/animation.js#L15 Resource handler for the `animation` asset type. Loads an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) from a GLB file, or a legacy [Animation](https://developer.mozilla.org/docs/Web/API/Animation) from a PlayCanvas JSON animation file. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `open(url: string, data: any, asset?: Asset): any` - `patch(asset: Asset, assets: AssetRegistry): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Asset.md # Asset Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L167 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](https://api.playcanvas.com/engine/classes/AssetRegistry.md) at [AppBase#assets](https://api.playcanvas.com/engine/classes/AppBase.md#assets), which loads them on demand. An asset has five parts: - `type` selects the [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) 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](https://api.playcanvas.com/engine/classes/Texture.md). `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](https://api.playcanvas.com/engine/classes/AssetRegistry.md#load), or set [preload](https://api.playcanvas.com/engine/classes/Asset.md#preload) so the asset loads when added. Wait for the result with [ready](https://api.playcanvas.com/engine/classes/Asset.md#ready) or listen for the `load` and `error` events. [unload](https://api.playcanvas.com/engine/classes/Asset.md#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](https://api.playcanvas.com/engine/classes/Texture.md) once loaded, and `app.assets.find('brick', 'texture')` returns one. See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) 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** ```ts 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** ## Constructors ### constructor ```ts new Asset(name: string, type: K, file?: object, data?: any, options?: object) ``` Create a new Asset record. Add it to the [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md) with [AssetRegistry#add](https://api.playcanvas.com/engine/classes/AssetRegistry.md#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`](https://api.playcanvas.com/engine/classes/Asset.md#k)): The type of asset (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)), which selects the resource handler and the type of [Asset#resource](https://api.playcanvas.com/engine/classes/Asset.md#resource). The types a developer commonly creates are: - "animation" - see [Animation](https://api.playcanvas.com/engine/classes/Animation.md) and [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) - "animclip" - see [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) - "animstategraph" - see [AnimStateGraph](https://api.playcanvas.com/engine/classes/AnimStateGraph.md) - "audio" - see [Sound](https://api.playcanvas.com/engine/classes/Sound.md) - "binary" - an `ArrayBuffer` - "container" - see [ContainerResource](https://api.playcanvas.com/engine/classes/ContainerResource.md) - "css" - a `string` - "cubemap" - see [Texture](https://api.playcanvas.com/engine/classes/Texture.md); null when only prefiltered levels are provided - "font" - see [Font](https://api.playcanvas.com/engine/classes/Font.md) - "gsplat" - a Gaussian splat resource - "html" - a `string` - "json" - the parsed JSON - "material" - see [Material](https://api.playcanvas.com/engine/classes/Material.md) - "model" - see [Model](https://api.playcanvas.com/engine/classes/Model.md) - "script" - see [Script](https://api.playcanvas.com/engine/classes/Script.md) - "shader" - a `string` - "sprite" - see [Sprite](https://api.playcanvas.com/engine/classes/Sprite.md) - "text" - a `string` - "texture" - see [Texture](https://api.playcanvas.com/engine/classes/Texture.md) - "textureatlas" - see [TextureAtlas](https://api.playcanvas.com/engine/classes/TextureAtlas.md) Types that the engine creates itself while loading, such as `render` or `scene`, are omitted here; every built-in type is listed in [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md). Any other string is accepted for an application-defined handler; see [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) 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](https://api.playcanvas.com/engine/classes/AssetRegistry.md#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](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl)). - `file.size` (`number`, optional): The size of the resource file or null if no size was set (e.g. from using [AssetRegistry#loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#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](https://api.playcanvas.com/engine/classes/ContainerHandler.md). - `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** ```ts // 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" }); ``` ## Properties ### id ```ts id: number ``` The asset id. ### loaded ```ts 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 ```ts loading: boolean = false ``` True if the resource is currently being loaded. ### options ```ts options: any = {} ``` Optional JSON data that contains the asset handler options. ### registry ```ts registry: AssetRegistry | null = null ``` The asset registry that this Asset belongs to. ### tags ```ts tags: Tags ``` Asset tags. Enables finding of assets by tags using the [AssetRegistry#findByTag](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findbytag) method. ### type ```ts type: K ``` The type of the asset: one of the [AssetType](https://api.playcanvas.com/engine/types/AssetType.md) names, or the name of an application-defined resource handler. See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md). ## Accessors ### data ```ts get data(): any set data(value: any) ``` Gets optional asset JSON data. ### file ```ts get file(): any set file(value: any) ``` Gets the file details or null if no file. ### name ```ts get name(): string set name(value: string) ``` Gets the asset name. ### preload ```ts get preload(): boolean set preload(value: boolean) ``` Gets whether to preload an asset. ### resource ```ts get resource(): AssetResource | undefined set resource(value: AssetResource) ``` Gets the asset resource. Its type follows the asset's type: a [Texture](https://api.playcanvas.com/engine/classes/Texture.md) for an `Asset<'texture'>`, a [Material](https://api.playcanvas.com/engine/classes/Material.md) for an `Asset<'material'>` and so on (see [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md)), or `unknown` when the type is only known as a `string`. It is `undefined` until the asset has loaded and after [Asset#unload](https://api.playcanvas.com/engine/classes/Asset.md#unload), so narrow it before use unless the asset is known to be loaded, for example inside [Asset#ready](https://api.playcanvas.com/engine/classes/Asset.md#ready). ### resources ```ts get resources(): AssetResource[] set resources(value: AssetResource[]) ``` 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`. ## Methods ### getFileUrl ```ts 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** ```ts const asset = app.assets.find("My Image", "texture"); const img = "<img src='" + asset.getFileUrl() + "'>"; ``` ### ready ```ts ready(callback: AssetReadyCallback, 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](https://api.playcanvas.com/engine/classes/Asset.md#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`](https://api.playcanvas.com/engine/types/AssetReadyCallback.md)`<`[`K`](https://api.playcanvas.com/engine/classes/Asset.md#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** ```ts const asset = app.assets.find("My Asset"); asset.ready((asset) => { // asset loaded }); app.assets.load(asset); ``` ### unload ```ts 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** ```ts const asset = app.assets.find("My Asset"); asset.unload(); // asset.resource is null ``` ## Events ### EVENT_ADDLOCALIZED ```ts static EVENT_ADDLOCALIZED: string = 'add:localized' ``` Fired when we add a new localized asset id to the asset. **Example** ```ts asset.on('add:localized', (locale, assetId) => { console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`); }); ``` ### EVENT_CHANGE ```ts static EVENT_CHANGE: string = 'change' ``` Fired when one of the asset properties `file`, `data`, `resource` or `resources` is changed. **Example** ```ts asset.on('change', (asset, property, newValue, oldValue) => { console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`); }); ``` ### EVENT_ERROR ```ts static EVENT_ERROR: string = 'error' ``` Fired if the asset encounters an error while loading. **Example** ```ts asset.on('error', (err, asset) => { console.error(`Error loading asset ${asset.name}: ${err}`); }); ``` ### EVENT_LOAD ```ts static EVENT_LOAD: string = 'load' ``` Fired when the asset has completed loading. **Example** ```ts asset.on('load', (asset) => { console.log(`Asset loaded: ${asset.name}`); }); ``` ### EVENT_PROGRESS ```ts 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: - downloads are skipped when `asset.file.contents` is supplied, so no progress is reported - totalBytes may not be reliable as it is based on the content-length header of the response **Example** ```ts asset.on('progress', (receivedBytes, totalBytes) => { console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when the asset is removed from the asset registry. **Example** ```ts asset.on('remove', (asset) => { console.log(`Asset removed: ${asset.name}`); }); ``` ### EVENT_REMOVELOCALIZED ```ts static EVENT_REMOVELOCALIZED: string = 'remove:localized' ``` Fired when we remove a localized asset id from the asset. **Example** ```ts asset.on('remove:localized', (locale, assetId) => { console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`); }); ``` ### EVENT_UNLOAD ```ts 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** ```ts asset.on('unload', (asset) => { console.log(`Asset about to unload: ${asset.name}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AssetListLoader.md # AssetListLoader Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-list-loader.js#L30 An AssetListLoader loads a group of assets together and reports once when every one of them has loaded or failed. Pass it [Asset](https://api.playcanvas.com/engine/classes/Asset.md) instances or asset ids. Assets not yet in the [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md) are added, and ids that the registry does not know yet are waited for until a matching asset is registered. Call [load](https://api.playcanvas.com/engine/classes/AssetListLoader.md#load) to start loading and [ready](https://api.playcanvas.com/engine/classes/AssetListLoader.md#ready) to be told when the list is complete without starting anything. **Example** ```ts 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`); } }); ``` ## Constructors ### constructor ```ts new AssetListLoader(assetList: number[] | Asset[], 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`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`): An array of [Asset](https://api.playcanvas.com/engine/classes/Asset.md) objects to load or an array of Asset IDs to load. - `assetRegistry` ([`AssetRegistry`](https://api.playcanvas.com/engine/classes/AssetRegistry.md)): The application's asset registry. **Example** ```ts 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); ``` ## Methods ### destroy ```ts destroy(): void ``` Removes all references to this asset list loader. ### load ```ts 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 ```ts 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. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AssetReference.md # AssetReference Class · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-reference.js#L22 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](https://api.playcanvas.com/engine/classes/AssetReference.md#id) or [url](https://api.playcanvas.com/engine/classes/AssetReference.md#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** ```ts const reference = new AssetReference('textureAsset', this, this.app.assets, { load: this.onTextureAssetLoad, remove: this.onTextureAssetRemove }, this); reference.id = this.textureAsset.id; ``` ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/AssetRegistry.md)): 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** ```ts const reference = new AssetReference('textureAsset', this, this.app.assets, { load: this.onTextureAssetLoad, add: this.onTextureAssetAdd, remove: this.onTextureAssetRemove }, this); reference.id = this.textureAsset.id; ``` ## Accessors ### id ```ts get id(): number | null set id(value: number | null) ``` Gets the asset id which this references. ### url ```ts get url(): string | null set url(value: string | null) ``` Gets the asset url which this references. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AssetRegistry.md # AssetRegistry Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L69 The AssetRegistry holds every [Asset](https://api.playcanvas.com/engine/classes/Asset.md) an application knows about and drives their loading through the [ResourceLoader](https://api.playcanvas.com/engine/classes/ResourceLoader.md). Each application has one at [AppBase#assets](https://api.playcanvas.com/engine/classes/AppBase.md#assets). Look assets up by id with [get](https://api.playcanvas.com/engine/classes/AssetRegistry.md#get), by name and type with [find](https://api.playcanvas.com/engine/classes/AssetRegistry.md#find) and [findAll](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findall), by URL with [getByUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#getbyurl), or by tag with [findByTag](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findbytag). Register an asset with [add](https://api.playcanvas.com/engine/classes/AssetRegistry.md#add), or create and load one in a single call with [loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl), which reuses any asset already registered for that URL. Adding an asset does not fetch it unless [Asset#preload](https://api.playcanvas.com/engine/classes/Asset.md#preload) is true. Call [load](https://api.playcanvas.com/engine/classes/AssetRegistry.md#load) to fetch it, then wait with [Asset#ready](https://api.playcanvas.com/engine/classes/Asset.md#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** ```ts const asset = app.assets.find('brick', 'texture'); app.assets.load(asset); asset.ready((asset) => { material.diffuseMap = asset.resource; }); ``` **Example** ```ts app.assets.loadFromUrl('models/robot.glb', 'container', (err, asset) => { app.root.addChild(asset.resource.instantiateRenderEntity()); }); ``` ## Constructors ### constructor ```ts new AssetRegistry(loader: ResourceLoader) ``` Create an instance of an AssetRegistry. **Parameters** - `loader` ([`ResourceLoader`](https://api.playcanvas.com/engine/classes/ResourceLoader.md)): The ResourceLoader used to load the asset files. ## Properties ### bundles ```ts 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 ```ts prefix: string | null = null ``` A URL prefix that will be added to all asset loading requests. ## Methods ### add ```ts add(asset: Asset): void ``` Add an asset to the registry. If [Asset#preload](https://api.playcanvas.com/engine/classes/Asset.md#preload) is `true`, it will also get loaded. **Parameters** - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``): The asset to add. **Example** ```ts const asset = new Asset("My Asset", "texture", { url: "../path/to/image.jpg" }); app.assets.add(asset); ``` ### filter ```ts filter(callback: FilterAssetCallback): Asset[] ``` Return all Assets that satisfy a filter callback. **Parameters** - `callback` ([`FilterAssetCallback`](https://api.playcanvas.com/engine/types/FilterAssetCallback.md)): The callback function that is used to filter assets. Return `true` to include an asset in the returned array. **Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets found. **Example** ```ts const assets = app.assets.filter(asset => asset.name.includes('monster')); console.log(`Found ${assets.length} assets with a name containing 'monster'`); ``` ### find ```ts find(name: string, type: K): Asset | 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](https://api.playcanvas.com/engine/classes/Texture.md). See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md). **Parameters** - `name` (`string`): The name of the Asset to find. - `type` ([`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findk)): The type of the Asset to find (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)). **Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`<`[`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findk)`> | null`: A single Asset or null if no Asset is found. **Example** ```ts const asset = app.assets.find("myTextureAsset", "texture"); if (asset) { const texture = asset.resource; // a Texture } ``` ```ts find(name: string, type?: string): Asset | 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`](https://api.playcanvas.com/engine/classes/Asset.md)` | null`: A single Asset or null if no Asset is found. **Example** ```ts const asset = app.assets.find("myAsset"); ``` ### findAll ```ts findAll(name: string, type: K): Asset[] ``` Return all Assets with the specified name and type found in the registry. The `type` also types the result, as for [AssetRegistry#find](https://api.playcanvas.com/engine/classes/AssetRegistry.md#find): `findAll('brick', 'texture')` returns `Asset<'texture'>[]`. **Parameters** - `name` (`string`): The name of the Assets to find. - `type` ([`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findallk)): The type of the Assets to find (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)). **Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)`<`[`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findallk)`>[]`: A list of all Assets found. **Example** ```ts const assets = app.assets.findAll('brick', 'texture'); console.log(`Found ${assets.length} texture assets named 'brick'`); const textures = assets.map(asset => asset.resource); // Texture[] ``` ```ts findAll(name: string, type?: string): Asset[] ``` 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`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets found. **Example** ```ts const assets = app.assets.findAll('brick'); ``` ### findByTag ```ts findByTag(...query: any[]): Asset[] ``` 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`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: A list of all Assets matched query. **Example** ```ts const assets = app.assets.findByTag("level-1"); // returns all assets that tagged by `level-1` ``` **Example** ```ts const assets = app.assets.findByTag("level-1", "level-2"); // returns all assets that tagged by `level-1` OR `level-2` ``` **Example** ```ts const assets = app.assets.findByTag(["level-1", "monster"]); // returns all assets that tagged by `level-1` AND `monster` ``` **Example** ```ts 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 ```ts get(id: number): Asset | undefined ``` Retrieve an asset from the registry by its id field. **Parameters** - `id` (`number`): The id of the asset to get. **Returns** [`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)` | undefined`: The asset. **Example** ```ts const asset = app.assets.get(100); ``` ### getByUrl ```ts getByUrl(url: string): Asset | 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`](https://api.playcanvas.com/engine/classes/Asset.md)` | undefined`: The asset. **Example** ```ts const asset = app.assets.getByUrl("../path/to/image.jpg"); ``` ### list ```ts list(filters?: object): Asset[] ``` 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`](https://api.playcanvas.com/engine/classes/Asset.md)`[]`: The filtered list of assets. ### load ```ts load(asset: Asset, 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](https://api.playcanvas.com/engine/classes/AppBase.md#preload) from completing. **Parameters** - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``): The asset to load. - `options` (`object`, optional): Options for asset loading. - `options.bundlesFilter` ([`BundlesFilterCallback`](https://api.playcanvas.com/engine/types/BundlesFilterCallback.md), 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** ```ts // 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 ```ts loadFromUrl(url: string, type: K, callback: LoadAssetCallback): 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](https://api.playcanvas.com/engine/classes/Texture.md). See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md). 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`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurlk)): The type of asset to load (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)). - `callback` ([`LoadAssetCallback`](https://api.playcanvas.com/engine/types/LoadAssetCallback.md)`<`[`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurlk)`>`): Function called when asset is loaded, passed (err, asset), where err is null if no errors were encountered. **Example** ```ts app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) { const texture = asset.resource; // a Texture }); ``` ### loadFromUrlAndFilename ```ts loadFromUrlAndFilename(url: string, filename: string, type: K, callback: LoadAssetCallback): 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`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurlandfilenamek)): The type of asset to load (an [AssetType](https://api.playcanvas.com/engine/types/AssetType.md)). - `callback` ([`LoadAssetCallback`](https://api.playcanvas.com/engine/types/LoadAssetCallback.md)`<`[`K`](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurlandfilenamek)`>`): Function called when asset is loaded, passed (err, asset), where err is null if no errors were encountered. **Example** ```ts const file = magicallyObtainAFile(); app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) { const texture = asset.resource; // a Texture }); ``` ### remove ```ts remove(asset: Asset): boolean ``` Remove an asset from the registry. **Parameters** - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``): The asset to remove. **Returns** `boolean`: True if the asset was successfully removed and false otherwise. **Example** ```ts const asset = app.assets.get(100); app.assets.remove(asset); ``` ## Events ### EVENT_ADD ```ts 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: 1. `add` - Fired when any asset is added to the registry. 2. `add:[id]` - Fired when an asset is added to the registry, where `[id]` is the unique id of the asset. 3. `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** ```ts app.assets.on('add', (asset) => { console.log(`Asset added: ${asset.name}`); }); ``` **Example** ```ts const id = 123456; app.assets.on('add:' + id, (asset) => { console.log(`Asset added: ${asset.name}`); }); ``` **Example** ```ts const id = 123456; const asset = app.assets.get(id); app.assets.on('add:url:' + asset.file.url, (asset) => { console.log(`Asset added: ${asset.name}`); }); ``` ### EVENT_ERROR ```ts static EVENT_ERROR: string = 'error' ``` Fired when an error occurs during asset loading. This event is available in two forms. They are as follows: 1. `error` - Fired when any asset reports an error in loading. 2. `error:[id]` - Fired when an asset reports an error in loading, where `[id]` is the unique id of the asset. **Example** ```ts const id = 123456; const asset = app.assets.get(id); app.assets.on('error', (err, asset) => { console.error(err); }); app.assets.load(asset); ``` **Example** ```ts const id = 123456; const asset = app.assets.get(id); app.assets.on('error:' + id, (err, asset) => { console.error(err); }); app.assets.load(asset); ``` ### EVENT_LOAD ```ts static EVENT_LOAD: string = 'load' ``` Fired when an asset completes loading. This event is available in three forms. They are as follows: 1. `load` - Fired when any asset finishes loading. 2. `load:[id]` - Fired when a specific asset has finished loading, where `[id]` is the unique id of the asset. 3. `load:url:[url]` - Fired when an asset finishes loading whose URL matches `[url]`, where `[url]` is the URL of the asset. **Example** ```ts app.assets.on('load', (asset) => { console.log(`Asset loaded: ${asset.name}`); }); ``` **Example** ```ts 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** ```ts 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); ``` ### EVENT_REMOVE ```ts 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: 1. `remove` - Fired when any asset is removed from the registry. 2. `remove:[id]` - Fired when an asset is removed from the registry, where `[id]` is the unique id of the asset. 3. `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** ```ts app.assets.on('remove', (asset) => { console.log(`Asset removed: ${asset.name}`); }); ``` **Example** ```ts const id = 123456; app.assets.on('remove:' + id, (asset) => { console.log(`Asset removed: ${asset.name}`); }); ``` **Example** ```ts const id = 123456; const asset = app.assets.get(id); app.assets.on('remove:url:' + asset.file.url, (asset) => { console.log(`Asset removed: ${asset.name}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AudioHandler.md # AudioHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/audio.js#L15 Resource handler for the `audio` asset type. Decodes any audio format the browser supports, such as MP3, OGG and WAV, into a [Sound](https://api.playcanvas.com/engine/classes/Sound.md) through the application's [SoundManager](https://api.playcanvas.com/engine/classes/SoundManager.md). ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `open(url: string, data: any, asset?: Asset): any` - `patch(asset: Asset, assets: AssetRegistry): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ContainerHandler.md # ContainerHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/container.js#L206 Resource handler for the `container` asset type. Loads glTF and GLB files, whose meshes, materials, textures, animations and Gaussian splats become one [ContainerResource](https://api.playcanvas.com/engine/classes/ContainerResource.md). 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: ```javascript const containerAsset = new Asset(filename, 'container', { url: url, filename: filename }, null, { texture: { preprocess: (gltfTexture) => { console.log("texture preprocess"); } } }); ``` ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `open(url: string, data: any, asset?: Asset): any` - `patch(asset: Asset, assets: AssetRegistry): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CubemapHandler.md # CubemapHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/cubemap.js#L33 Resource handler for the `cubemap` asset type. Assembles a cube map [Texture](https://api.playcanvas.com/engine/classes/Texture.md) from six face texture assets, from a prefiltered environment file, or both, and stores the results in [Asset#resources](https://api.playcanvas.com/engine/classes/Asset.md#resources). ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `asset` (`any`): Optional asset that is passed by ResourceLoader. **Returns** `any`: The parsed resource data. ### patch ```ts 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`) ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/FontHandler.md # FontHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/font.js#L45 Resource handler for the `font` asset type. Loads a [Font](https://api.playcanvas.com/engine/classes/Font.md) from a JSON glyph description and the texture pages that accompany it. Bitmap fonts and multi-channel signed distance field fonts are both supported. ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `asset` (`any`): Optional asset that is passed by ResourceLoader. **Returns** [`Font`](https://api.playcanvas.com/engine/classes/Font.md): The parsed resource data. ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MaterialHandler.md # MaterialHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/material.js#L29 Resource handler for the `material` asset type. Loads material JSON into a [StandardMaterial](https://api.playcanvas.com/engine/classes/StandardMaterial.md) and binds the texture assets it references. A custom parser may produce another kind of [Material](https://api.playcanvas.com/engine/classes/Material.md). ## Methods ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `open(url: string, data: any, asset?: Asset): any` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ModelHandler.md # ModelHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/model.js#L18 Resource handler for the `model` asset type. Loads legacy PlayCanvas JSON models and GLB files into a [Model](https://api.playcanvas.com/engine/classes/Model.md). OBJ files are supported once the `ObjModelParser` shipped in `playcanvas/scripts/esm/parsers/obj-model.mjs` is registered with [ResourceHandler#addParser](https://api.playcanvas.com/engine/classes/ResourceHandler.md#addparser). ## Methods ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `open(url: string, data: any, asset?: Asset): any` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RenderHandler.md # RenderHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/render.js#L19 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`. ## Methods ### load ```ts load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): 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`](https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md)): Called with the container's render data or an error. - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): The render asset whose container dependency should be loaded. ### open ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). **Returns** `Render`: The parsed resource data. ### patch ```ts 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`) ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ResourceHandler.md # ResourceHandler Class · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L83 A ResourceHandler loads and opens resources of one asset type on behalf of the [ResourceLoader](https://api.playcanvas.com/engine/classes/ResourceLoader.md). The engine ships a handler for every built-in [AssetType](https://api.playcanvas.com/engine/types/AssetType.md), and an application registers the ones listed in [AppOptions#resourceHandlers](https://api.playcanvas.com/engine/classes/AppOptions.md#resourcehandlers), so a hand-configured [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) may support only some types. Register your own with [ResourceLoader#addHandler](https://api.playcanvas.com/engine/classes/ResourceLoader.md#addhandler) to add a new type. A handler works in two steps. [load](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load) fetches the raw data for a URL and [open](https://api.playcanvas.com/engine/classes/ResourceHandler.md#open) turns that data into the resource stored on [Asset#resource](https://api.playcanvas.com/engine/classes/Asset.md#resource). A handler may also implement [patch](https://api.playcanvas.com/engine/classes/ResourceHandler.md#patch) to resolve references to other assets once the resource exists. Rather than overriding those methods, a handler can register one [ResourceParser](https://api.playcanvas.com/engine/interfaces/ResourceParser.md) per file format with [addParser](https://api.playcanvas.com/engine/classes/ResourceHandler.md#addparser) and let the base class pick the parser that claims the file. **Example** ```ts 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)); ``` ## Constructors ### constructor ```ts new ResourceHandler(app: AppBase, handlerType: string) ``` **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The running [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). - `handlerType` (`string`): The type of the resource the handler handles. ## Properties ### _app ```ts protected _app: AppBase ``` The running app instance. ### handlerType ```ts handlerType: string = '' ``` Type of the resource the handler handles. ## Accessors ### app ```ts get app(): AppBase ``` Gets the running [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) instance. ### maxRetries ```ts get maxRetries(): number set maxRetries(value: number) ``` Gets the number of times to retry a failed request for the resource. ### parsers ```ts get parsers(): ResourceParser[] ``` Gets a read-only copy of the registered parsers. ## Methods ### addParser ```ts addParser(parser: ResourceParser, decider?: any): void ``` Registers a [ResourceParser](https://api.playcanvas.com/engine/interfaces/ResourceParser.md) for this handler. Parsers are consulted newest-first: the most recently added parser whose [ResourceParser#canParse](https://api.playcanvas.com/engine/interfaces/ResourceParser.md#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`](https://api.playcanvas.com/engine/interfaces/ResourceParser.md)): 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** ```ts app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice)); ``` ### fetch ```ts fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): 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](https://api.playcanvas.com/engine/interfaces/ResourceParser.md)'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](https://api.playcanvas.com/engine/classes/Http.md) response type to fetch as (for example `Http.ResponseType.ARRAY_BUFFER` for a binary format, or `Http.ResponseType.TEXT`). - `callback` ([`ResourceHandlerCallback`](https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md)): Called with `(err, data)` when the fetch completes. - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): The asset being loaded, used to reuse already-fetched contents. ### load ```ts load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): 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`](https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md)): The callback used when the resource is loaded or an error occurs. - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): Optional asset that is passed by ResourceLoader. ### open ```ts open(url: string, data: any, asset?: Asset): 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): Optional asset that is passed by ResourceLoader. **Returns** `any`: The parsed resource data. ### patch ```ts patch(asset: Asset, 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`](https://api.playcanvas.com/engine/classes/Asset.md)``): The asset to patch. - `assets` ([`AssetRegistry`](https://api.playcanvas.com/engine/classes/AssetRegistry.md)): The asset registry. ### removeParser ```ts removeParser(parser: ResourceParser): void ``` Removes a previously registered [ResourceParser](https://api.playcanvas.com/engine/interfaces/ResourceParser.md). **Parameters** - `parser` ([`ResourceParser`](https://api.playcanvas.com/engine/interfaces/ResourceParser.md)): The parser to remove. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ResourceLoader.md # ResourceLoader Class · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/loader.js#L43 The ResourceLoader turns a URL and an asset type into a loaded resource. It owns one [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) 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](https://api.playcanvas.com/engine/classes/AppBase.md#loader). Most code never calls the loader directly: the [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md) does so on its behalf when an [Asset](https://api.playcanvas.com/engine/classes/Asset.md) loads. Use the loader to add support for a new asset type with [addHandler](https://api.playcanvas.com/engine/classes/ResourceLoader.md#addhandler), to reach an existing handler with [getHandler](https://api.playcanvas.com/engine/classes/ResourceLoader.md#gethandler), or to tune requests with [maxConcurrentRequests](https://api.playcanvas.com/engine/classes/ResourceLoader.md#maxconcurrentrequests), [withCredentials](https://api.playcanvas.com/engine/classes/ResourceLoader.md#withcredentials) and [enableRetry](https://api.playcanvas.com/engine/classes/ResourceLoader.md#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** ```ts app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice)); ``` **Example** ```ts app.loader.getHandler('gsplat').addParser(new SpzParser(app)); ``` ## Constructors ### constructor ```ts new ResourceLoader(app: AppBase) ``` Create a new ResourceLoader instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. ## Accessors ### maxConcurrentRequests ```ts get maxConcurrentRequests(): number set maxConcurrentRequests(value: number) ``` Gets the maximum number of asset requests that can be in flight at the same time. ### withCredentials ```ts get withCredentials(): boolean set withCredentials(value: boolean) ``` Gets whether asset requests are sent with credentials. ## Methods ### addHandler ```ts addHandler(type: string & {} | AssetType, handler: ResourceHandler): void ``` Add a [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) 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`](https://api.playcanvas.com/engine/types/AssetType.md)): The name of the resource type that the handler will be registered with: one of the built-in [AssetType](https://api.playcanvas.com/engine/types/AssetType.md) names, such as `'texture'`, `'model'` or `'container'`, or a new name for an application-defined handler. See [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) for typing the resource of a new name. - `handler` ([`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md)): An instance of a resource handler supporting at least `load()` and `open()`. **Example** ```ts // register a handler for a new 'csv' asset type (see ResourceHandler for the class) app.loader.addHandler('csv', new CsvHandler(app)); ``` ### clearCache ```ts 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 ```ts destroy(): void ``` Destroys the resource loader. ### disableRetry ```ts disableRetry(): void ``` Disables retrying of failed requests when loading assets. ### enableRetry ```ts 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 ```ts 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 ```ts getHandler(type: string & {} | AssetType): ResourceHandler | undefined ``` Get a [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) for a resource type. **Parameters** - `type` (`string & {} |` [`AssetType`](https://api.playcanvas.com/engine/types/AssetType.md)): The name of the resource type that the handler is registered with. **Returns** [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) `| undefined`: The registered handler, or undefined if the requested handler is not registered. ### load ```ts load(url: string, type: string, callback: ResourceLoaderCallback, asset?: Asset, 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`](https://api.playcanvas.com/engine/types/ResourceLoaderCallback.md)): 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`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): Optional asset that is passed into handler. - `options` (`object`, optional): Additional options for loading. - `options.bundlesFilter` ([`BundlesFilterCallback`](https://api.playcanvas.com/engine/types/BundlesFilterCallback.md), 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** ```ts app.loader.load("../path/to/texture.png", "texture", function (err, texture) { // use texture here }); ``` ### open ```ts 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](https://api.playcanvas.com/engine/classes/Model.md). **Parameters** - `type` (`string`): The type of resource. - `data` (`any`): The raw resource data. **Returns** `any`: The parsed resource data. ### patch ```ts patch(asset: Asset, 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`](https://api.playcanvas.com/engine/classes/Asset.md)``): The asset to patch. - `assets` ([`AssetRegistry`](https://api.playcanvas.com/engine/classes/AssetRegistry.md)): The asset registry. ### removeHandler ```ts removeHandler(type: string & {} | AssetType): void ``` Remove a [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) for a resource type. **Parameters** - `type` (`string & {} |` [`AssetType`](https://api.playcanvas.com/engine/types/AssetType.md)): The name of the type that the handler will be removed. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SceneHandler.md # SceneHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/scene.js#L15 Resource handler for the `scene` asset type. Loads a PlayCanvas scene JSON file, instantiates its entity hierarchy as the root of [AppBase#scene](https://api.playcanvas.com/engine/classes/AppBase.md#scene) and applies the scene's settings. ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). **Returns** [`Scene`](https://api.playcanvas.com/engine/classes/Scene.md): The parsed resource data. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `patch(asset: Asset, assets: AssetRegistry): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptHandler.md # ScriptHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/script.js#L21 Resource handler for loading JavaScript files dynamically. Two types of JavaScript files can be loaded, PlayCanvas scripts which contain calls to [createScript](https://api.playcanvas.com/engine/functions/createScript.md), or regular JavaScript files, such as third-party libraries. ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). **Returns** `any`: The parsed resource data. ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SpriteHandler.md # SpriteHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/sprite.js#L30 Resource handler for the `sprite` asset type. Builds a [Sprite](https://api.playcanvas.com/engine/classes/Sprite.md) from sprite JSON, loaded from a file or supplied as asset data, and binds the [TextureAtlas](https://api.playcanvas.com/engine/classes/TextureAtlas.md) asset it references. ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). **Returns** [`Sprite`](https://api.playcanvas.com/engine/classes/Sprite.md): The parsed resource data. ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureAtlasHandler.md # TextureAtlasHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/texture-atlas.js#L41 Resource handler for the `textureatlas` asset type. Loads a texture and its frame definitions into a [TextureAtlas](https://api.playcanvas.com/engine/classes/TextureAtlas.md). The frames come from the asset data, or from a JSON file with a texture of the same name beside it. ## Methods ### load ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `asset` (`any`): Optional asset that is passed by ResourceLoader. **Returns** [`TextureAtlas`](https://api.playcanvas.com/engine/classes/TextureAtlas.md) `| null`: The parsed resource data. ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureHandler.md # TextureHandler Class · extends [`ResourceHandler`](https://api.playcanvas.com/engine/classes/ResourceHandler.md) · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/texture.js#L172 Resource handler for the `texture` asset type. Loads 2D and 3D [Texture](https://api.playcanvas.com/engine/classes/Texture.md) resources from any image format the browser decodes, such as PNG, JPEG, WebP and AVIF, and from DDS, KTX, KTX2, Basis and HDR files. ## Methods ### open ```ts 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](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `asset` (`any`): Optional asset that is passed by ResourceLoader. **Returns** `any`: The parsed resource data. ### patch ```ts 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. ## Inherited from [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md) - `protected _app: AppBase` - `handlerType: string = ''` - `get app(): AppBase` - `get maxRetries(): number` · `set maxRetries(value: number)` - `get parsers(): ResourceParser[]` - `addParser(parser: ResourceParser, decider?: any): void` - `fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void` - `load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset): void` - `removeParser(parser: ResourceParser): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MiniStats.md # MiniStats Class · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L120 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](https://api.playcanvas.com/engine/classes/AppBase.md#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](https://api.playcanvas.com/engine/classes/AppStats.md#primitivecount), require a debug or profiler build. See [AppStats](https://api.playcanvas.com/engine/classes/AppStats.md) 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. ## Constructors ### constructor ```ts new MiniStats(app: AppBase, options?: MiniStatsOptions) ``` Create a new MiniStats instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. - `options` ([`MiniStatsOptions`](https://api.playcanvas.com/engine/interfaces/MiniStatsOptions.md), optional): Options for the MiniStats instance. **Example** ```ts const miniStats = new MiniStats(app); ``` ## Accessors ### cpuCollapsed ```ts get cpuCollapsed(): boolean set cpuCollapsed(value: boolean) ``` ### enabled ```ts get enabled(): boolean set enabled(value: boolean) ``` ### engineCollapsed ```ts get engineCollapsed(): boolean set engineCollapsed(value: boolean) ``` ### gpuCollapsed ```ts get gpuCollapsed(): boolean set gpuCollapsed(value: boolean) ``` ### resourcesCollapsed ```ts get resourcesCollapsed(): boolean set resourcesCollapsed(value: boolean) ``` ### resourcesEnabled ```ts get resourcesEnabled(): boolean set resourcesEnabled(value: boolean) ``` ### userCollapsed ```ts get userCollapsed(): boolean set userCollapsed(value: boolean) ``` ### vramCollapsed ```ts get vramCollapsed(): boolean set vramCollapsed(value: boolean) ``` ## Methods ### destroy ```ts destroy(): void ``` Destroy the MiniStats instance and release its event listeners, textures and mesh. **Example** ```ts miniStats.destroy(); ``` ### getDefaultOptions ```ts 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`](https://api.playcanvas.com/engine/interfaces/MiniStatsOptions.md): The default options for MiniStats. **Example** ```ts const options = MiniStats.getDefaultOptions(['gsplats']); options.sizes[2].width = 280; const miniStats = new MiniStats(app, options); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Tracing.md # Tracing Class · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/tracing.js#L12 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. ## Properties ### stack ```ts static stack: boolean = false ``` Enable call stack logging for trace calls. Defaults to false. ## Methods ### get ```ts 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. ### set ```ts static set(channel: string, enabled?: boolean): void ``` Enable or disable a trace channel. **Parameters** - `channel` (`string`): Name of the trace channel. Can be: - [TRACEID_RENDER_FRAME](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_FRAME.md) - [TRACEID_RENDER_FRAME_TIME](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_FRAME_TIME.md) - [TRACEID_RENDER_PASS](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_PASS.md) - [TRACEID_RENDER_PASS_DETAIL](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_PASS_DETAIL.md) - [TRACEID_RENDER_ACTION](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_ACTION.md) - [TRACEID_RENDER_TARGET_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_RENDER_TARGET_ALLOC.md) - [TRACEID_TEXTURE_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_TEXTURE_ALLOC.md) - [TRACEID_SHADER_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_SHADER_ALLOC.md) - [TRACEID_SHADER_COMPILE](https://api.playcanvas.com/engine/variables/TRACEID_SHADER_COMPILE.md) - [TRACEID_VRAM_TEXTURE](https://api.playcanvas.com/engine/variables/TRACEID_VRAM_TEXTURE.md) - [TRACEID_VRAM_VB](https://api.playcanvas.com/engine/variables/TRACEID_VRAM_VB.md) - [TRACEID_VRAM_IB](https://api.playcanvas.com/engine/variables/TRACEID_VRAM_IB.md) - [TRACEID_RENDERPIPELINE_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_RENDERPIPELINE_ALLOC.md) - [TRACEID_COMPUTEPIPELINE_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_COMPUTEPIPELINE_ALLOC.md) - [TRACEID_PIPELINELAYOUT_ALLOC](https://api.playcanvas.com/engine/variables/TRACEID_PIPELINELAYOUT_ALLOC.md) - [TRACEID_TEXTURES](https://api.playcanvas.com/engine/variables/TRACEID_TEXTURES.md) - [TRACEID_BUFFERS](https://api.playcanvas.com/engine/variables/TRACEID_BUFFERS.md) - [TRACEID_ASSETS](https://api.playcanvas.com/engine/variables/TRACEID_ASSETS.md) - [TRACEID_GPU_TIMINGS](https://api.playcanvas.com/engine/variables/TRACEID_GPU_TIMINGS.md) - `enabled` (`boolean`, optional, default `true`): New enabled state for the channel. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GltfExporter.md # GltfExporter Class · category: Exporter Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/exporters/gltf-exporter.js#L145 Implementation of the GLTF 2.0 format exporter. ## Methods ### build ```ts build(entity: Entity, options?: object): Promise ``` Converts a hierarchy of entities to GLB format. **Parameters** - `entity` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): 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: - Texture coordinates not referenced by materials - Vertex colors if not used by materials - Tangents if no normal maps are used - Skinning data if no skinned meshes exist Defaults to false. **Returns** `Promise`: - The GLB file content. ## Inherited from CoreExporter - `new GltfExporter()` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/UsdzExporter.md # UsdzExporter Class · category: Exporter Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/exporters/usdz-exporter.js#L154 Implementation of the USDZ format exporter. Note that ASCII version of the format (USDA) is used. ## Methods ### build ```ts build(entity: Entity, options?: object): Promise ``` Converts a hierarchy of entities to USDZ format. Skinned meshes are exported in their current pose. **Parameters** - `entity` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): 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`: - The USDZ file content. ## Inherited from CoreExporter - `new UsdzExporter()` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AppBase.md # AppBase Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L130 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: - The graphics device - see [GraphicsDevice](https://api.playcanvas.com/engine/classes/GraphicsDevice.md). - The asset registry - see [AssetRegistry](https://api.playcanvas.com/engine/classes/AssetRegistry.md). - The component system registry - see [ComponentSystemRegistry](https://api.playcanvas.com/engine/classes/ComponentSystemRegistry.md). - The scene - see [Scene](https://api.playcanvas.com/engine/classes/Scene.md). - Input devices - see [Keyboard](https://api.playcanvas.com/engine/classes/Keyboard.md), [Mouse](https://api.playcanvas.com/engine/classes/Mouse.md), [TouchDevice](https://api.playcanvas.com/engine/classes/TouchDevice.md), and [GamePads](https://api.playcanvas.com/engine/classes/GamePads.md). - The main update/render loop. Using AppBase directly requires you to register [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md)s and [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md)s yourself. This facilitates [tree-shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) when bundling your application. It is the preferred entry point for new code - [Application](https://api.playcanvas.com/engine/classes/Application.md) 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](https://api.playcanvas.com/engine/classes/AppBase.md#init) with an [AppOptions](https://api.playcanvas.com/engine/classes/AppOptions.md) supplying at minimum `graphicsDevice`, `componentSystems` and `resourceHandlers` before adding components or calling [AppBase#start](https://api.playcanvas.com/engine/classes/AppBase.md#start). Create the `graphicsDevice` with [createGraphicsDevice](https://api.playcanvas.com/engine/functions/createGraphicsDevice.md). ## Constructors ### constructor ```ts new AppBase(canvas: OffscreenCanvas | HTMLCanvasElement) ``` Create a new AppBase instance. **Parameters** - `canvas` (`OffscreenCanvas | HTMLCanvasElement`): The canvas element. **Example** ```ts const app = new AppBase(canvas); const options = new AppOptions(); app.init(options); // Start the application's main loop app.start(); ``` ## Properties ### assets ```ts assets: AssetRegistry ``` The asset registry managed by the application. **Example** ```ts // Search the asset registry for all assets with the tag 'vehicle' const vehicleAssets = this.app.assets.findByTag('vehicle'); ``` ### autoRender ```ts 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** ```ts // 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 ```ts elementInput: ElementInput | null = null ``` Used to handle input for [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. ### gamepads ```ts gamepads: GamePads | null = null ``` Used to access GamePad input. ### graphicsDevice ```ts graphicsDevice: GraphicsDevice ``` The graphics device used by the application. ### i18n ```ts i18n: I18n ``` Handles localization. ### keyboard ```ts keyboard: Keyboard | null = null ``` The keyboard device. ### lightmapper ```ts lightmapper: Lightmapper | null = null ``` The run-time lightmapper. ### loader ```ts loader: ResourceLoader ``` The resource loader. ### maxDeltaTime ```ts 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** ```ts // Don't clamp inter-frame times of 200ms or less this.app.maxDeltaTime = 0.2; ``` ### mouse ```ts mouse: Mouse | null = null ``` The mouse device. ### renderNextFrame ```ts renderNextFrame: boolean ``` Set to true to render the scene on the next iteration of the main loop. This only has an effect if [autoRender](https://api.playcanvas.com/engine/classes/AppBase.md#autorender) is set to false. The value of renderNextFrame is set back to false again as soon as the scene has been rendered. **Example** ```ts // Render the scene only while space key is pressed if (this.app.keyboard.isPressed(KEY_SPACE)) { this.app.renderNextFrame = true; } ``` ### root ```ts root: Entity ``` The root entity of the application. **Example** ```ts // Return the first entity called 'Camera' in a depth-first search of the scene hierarchy const camera = this.app.root.findByName('Camera'); ``` ### scene ```ts scene: Scene ``` The scene managed by the application. **Example** ```ts // Set the fog type property of the application's scene this.app.scene.fog.type = FOG_LINEAR; ``` ### scenes ```ts scenes: SceneRegistry ``` The scene registry managed by the application. **Example** ```ts // 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 ```ts scripts: ScriptRegistry ``` The application's script registry. ### scriptsOrder ```ts scriptsOrder: string[] = [] ``` Scripts in order of loading first. ### systems ```ts systems: ComponentSystemRegistry ``` The application's component system registry. **Example** ```ts // Set global gravity to zero this.app.systems.rigidbody.gravity.set(0, 0, 0); ``` **Example** ```ts // Set the global sound volume to 50% this.app.systems.sound.volume = 0.5; ``` ### timeScale ```ts 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](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#timescale). **Example** ```ts // Set the app to run at half speed this.app.timeScale = 0.5; ``` ### touch ```ts touch: TouchDevice | null = null ``` Used to get touch events input. ### xr ```ts xr: XrManager | null = null ``` The XR Manager that provides ability to start VR/AR sessions. **Example** ```ts // check if VR is available if (app.xr.isAvailable(XRTYPE_VR)) { // VR is available } ``` ## Accessors ### batcher ```ts 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. ### fillMode ```ts get fillMode(): string ``` The current fill mode of the canvas. Can be: - [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md): the canvas will always match the size provided. - [FILLMODE_FILL_WINDOW](https://api.playcanvas.com/engine/variables/FILLMODE_FILL_WINDOW.md): the canvas will simply fill the window, changing aspect ratio. - [FILLMODE_KEEP_ASPECT](https://api.playcanvas.com/engine/variables/FILLMODE_KEEP_ASPECT.md): the canvas will grow to fill the window as best it can while maintaining the aspect ratio. ### resolutionMode ```ts get resolutionMode(): string ``` The current resolution mode of the canvas, Can be: - [RESOLUTION_AUTO](https://api.playcanvas.com/engine/variables/RESOLUTION_AUTO.md): if width and height are not provided, canvas will be resized to match canvas client size. - [RESOLUTION_FIXED](https://api.playcanvas.com/engine/variables/RESOLUTION_FIXED.md): resolution of canvas will be fixed. ### stats ```ts get stats(): AppStats ``` The application's performance statistics. Returns the same [AppStats](https://api.playcanvas.com/engine/classes/AppStats.md) instance on every access. Engine measurements are read-only; [AppStats#user](https://api.playcanvas.com/engine/classes/AppStats.md#user) holds writable application-defined counters. See [AppStats](https://api.playcanvas.com/engine/classes/AppStats.md) for units, sampling and GPU profiling setup. ## Methods ### applySceneSettings ```ts 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: - [FOG_NONE](https://api.playcanvas.com/engine/variables/FOG_NONE.md) - [FOG_LINEAR](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md) - [FOG_EXP](https://api.playcanvas.com/engine/variables/FOG_EXP.md) - [FOG_EXP2](https://api.playcanvas.com/engine/variables/FOG_EXP2.md) - `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](https://api.playcanvas.com/engine/variables/FOG_EXP.md) or [FOG_EXP2](https://api.playcanvas.com/engine/variables/FOG_EXP2.md). - `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](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md). - `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](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md). - `settings.render.gamma_correction` (`number`): The gamma correction to apply when rendering the scene. Can be: - [GAMMA_NONE](https://api.playcanvas.com/engine/variables/GAMMA_NONE.md) - [GAMMA_SRGB](https://api.playcanvas.com/engine/variables/GAMMA_SRGB.md) - `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](https://api.playcanvas.com/engine/variables/GSPLATDATA_COMPACT.md). - `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: - [SHADOW_PCF1_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF1_32F.md) - [SHADOW_PCF3_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF3_32F.md) - [SHADOW_PCF5_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF5_32F.md) - [SHADOW_PCF1_16F](https://api.playcanvas.com/engine/variables/SHADOW_PCF1_16F.md) - [SHADOW_PCF3_16F](https://api.playcanvas.com/engine/variables/SHADOW_PCF3_16F.md) - [SHADOW_PCF5_16F](https://api.playcanvas.com/engine/variables/SHADOW_PCF5_16F.md) Defaults to [SHADOW_PCF3_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF3_32F.md). - `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: - [BAKE_COLOR](https://api.playcanvas.com/engine/variables/BAKE_COLOR.md): single color lightmap - [BAKE_COLORDIR](https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md): single color lightmap + dominant light direction (used for bump/specular) - `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](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). Defaults to [0, 1, 0]. - `settings.render.skyMeshPosition` (`number[]`, optional): The position of sky mesh. Ignored for [SKYTYPE_INFINITE](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). Defaults to [0, 0, 0]. - `settings.render.skyMeshRotation` (`number[]`, optional): The rotation of sky mesh. Ignored for [SKYTYPE_INFINITE](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). Defaults to [0, 0, 0]. - `settings.render.skyMeshScale` (`number[]`, optional): The scale of sky mesh. Ignored for [SKYTYPE_INFINITE](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). Defaults to [1, 1, 1]. - `settings.render.skyType` (`string`, optional): The type of the sky. One of the SKYTYPE_* constants. Defaults to [SKYTYPE_INFINITE](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). - `settings.render.tonemapping` (`number`): The tonemapping transform to apply when writing fragments to the frame buffer. Can be: - [TONEMAP_LINEAR](https://api.playcanvas.com/engine/variables/TONEMAP_LINEAR.md) - [TONEMAP_FILMIC](https://api.playcanvas.com/engine/variables/TONEMAP_FILMIC.md) - [TONEMAP_HEJL](https://api.playcanvas.com/engine/variables/TONEMAP_HEJL.md) - [TONEMAP_ACES](https://api.playcanvas.com/engine/variables/TONEMAP_ACES.md) - [TONEMAP_ACES2](https://api.playcanvas.com/engine/variables/TONEMAP_ACES2.md) - [TONEMAP_NEUTRAL](https://api.playcanvas.com/engine/variables/TONEMAP_NEUTRAL.md) **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/types/ConfigureAppCallback.md)): The Function called when the configuration file is loaded and parsed (or an error occurs). ### destroy ```ts 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** ```ts app.destroy(); ``` ### drawLine ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The start world space coordinate of the line. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The end world space coordinate of the line. - `color` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md), 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`](https://api.playcanvas.com/engine/classes/Layer.md), optional): The layer to render the line into. Defaults to [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md). **Example** ```ts // 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** ```ts // 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** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md)): 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`](https://api.playcanvas.com/engine/classes/Layer.md), optional): The layer to render the lines into. Defaults to [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md). **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)`[]`): An array of points to draw lines between. The length of the array must be a multiple of 2. - `colors` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md) `|` [`Color`](https://api.playcanvas.com/engine/classes/Color.md)`[]`): 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`](https://api.playcanvas.com/engine/classes/Layer.md), optional): The layer to render the lines into. Defaults to [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md). **Example** ```ts // 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** ```ts // 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 ```ts init(appOptions: AppOptions): void ``` Initialize the app. **Parameters** - `appOptions` ([`AppOptions`](https://api.playcanvas.com/engine/classes/AppOptions.md)): Options specifying the init parameters for the app. ### isHidden ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/types/PreloadAppCallback.md)): Function called when all assets are loaded. ### resizeCanvas ```ts resizeCanvas(width?: number, height?: number): { height: number; width: number } | undefined ``` Resize the application's canvas element in line with the current fill mode. - In [FILLMODE_KEEP_ASPECT](https://api.playcanvas.com/engine/variables/FILLMODE_KEEP_ASPECT.md) mode, the canvas will grow to fill the window as best it can while maintaining the aspect ratio. - In [FILLMODE_FILL_WINDOW](https://api.playcanvas.com/engine/variables/FILLMODE_FILL_WINDOW.md) mode, the canvas will simply fill the window, changing aspect ratio. - In [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md) mode, the canvas will always match the size provided. **Parameters** - `width` (`number`, optional): The width of the canvas. Only used if current fill mode is [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md). - `height` (`number`, optional): The height of the canvas. Only used if current fill mode is [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md). **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 ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/AppBase.md#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: - [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md): the canvas will always match the size provided. - [FILLMODE_FILL_WINDOW](https://api.playcanvas.com/engine/variables/FILLMODE_FILL_WINDOW.md): the canvas will simply fill the window, changing aspect ratio. - [FILLMODE_KEEP_ASPECT](https://api.playcanvas.com/engine/variables/FILLMODE_KEEP_ASPECT.md): the canvas will grow to fill the window as best it can while maintaining the aspect ratio. - `width` (`number`, optional): The width of the canvas (only used when mode is [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md)). - `height` (`number`, optional): The height of the canvas (only used when mode is [FILLMODE_NONE](https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md)). ### setCanvasResolution ```ts 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: - [RESOLUTION_AUTO](https://api.playcanvas.com/engine/variables/RESOLUTION_AUTO.md): if width and height are not provided, canvas will be resized to match canvas client size. - [RESOLUTION_FIXED](https://api.playcanvas.com/engine/variables/RESOLUTION_FIXED.md): resolution of canvas will be fixed. - `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 ```ts setSkybox(asset: Asset): void ``` Sets the skybox asset to current scene, and subscribes to asset load/change events. **Parameters** - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``): Asset of type `skybox` to be set to, or null to remove skybox. ### start ```ts start(): void ``` Start the application. This function does the following: 1. Fires an event on the application named 'start' 2. Calls initialize for all components on entities in the hierarchy 3. Fires an event on the application named 'initialize' 4. Calls postInitialize for all components on entities in the hierarchy 5. Fires an event on the application named 'postinitialize' 6. Starts executing the main loop of the application This function is called internally by PlayCanvas applications made in the Editor but you will need to call start yourself if you are using the engine stand-alone. The main loop is driven by `requestAnimationFrame`. Where that is unavailable, such as in Node.js, no loop runs, so call [update](https://api.playcanvas.com/engine/classes/AppBase.md#update) yourself at the rate you need. **Example** ```ts app.start(); ``` ### update ```ts 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** ```ts // run a Node.js server at 20 updates per second setInterval(() => app.update(1 / 20), 50); ``` ### updateCanvasSize ```ts updateCanvasSize(): void ``` Updates the [GraphicsDevice](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) 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. ### getApplication ```ts 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`](https://api.playcanvas.com/engine/classes/AppBase.md) `| undefined`: The running application, if any. **Example** ```ts const app = AppBase.getApplication(); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Application.md # Application Class · extends [`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/application.js#L109 Application is a subclass of [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md), which represents the base functionality for all PlayCanvas applications. It acts as a convenience class by internally registering all [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md)s and [ResourceHandler](https://api.playcanvas.com/engine/classes/ResourceHandler.md)s 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](https://api.playcanvas.com/engine/classes/AppBase.md), as this class is expected to be deprecated in a future release. Two limitations motivate that: - Its constructor is synchronous, so it cannot create a WebGPU device. Creating one requires awaiting [createGraphicsDevice](https://api.playcanvas.com/engine/functions/createGraphicsDevice.md). - It references every component system and resource handler, so none of them can be [tree-shaken](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) out of your bundle. [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) leaves that choice to you. The equivalent [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) setup registers only what the app actually uses: ```javascript 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](https://api.playcanvas.com/engine/classes/AppBase.md#keyboard), [AppBase#mouse](https://api.playcanvas.com/engine/classes/AppBase.md#mouse), [AppBase#touch](https://api.playcanvas.com/engine/classes/AppBase.md#touch), [AppBase#gamepads](https://api.playcanvas.com/engine/classes/AppBase.md#gamepads) and [AppBase#elementInput](https://api.playcanvas.com/engine/classes/AppBase.md#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) }`. ## Constructors ### constructor ```ts new Application(canvas: OffscreenCanvas | HTMLCanvasElement, options?: object) ``` Create a new Application instance. Automatically registers these component systems with the application's component system registry: - anim ([AnimComponentSystem](https://api.playcanvas.com/engine/classes/AnimComponentSystem.md)) - animation ([AnimationComponentSystem](https://api.playcanvas.com/engine/classes/AnimationComponentSystem.md)) - audiolistener ([AudioListenerComponentSystem](https://api.playcanvas.com/engine/classes/AudioListenerComponentSystem.md)) - button ([ButtonComponentSystem](https://api.playcanvas.com/engine/classes/ButtonComponentSystem.md)) - camera ([CameraComponentSystem](https://api.playcanvas.com/engine/classes/CameraComponentSystem.md)) - collision ([CollisionComponentSystem](https://api.playcanvas.com/engine/classes/CollisionComponentSystem.md)) - element ([ElementComponentSystem](https://api.playcanvas.com/engine/classes/ElementComponentSystem.md)) - gsplat ([GSplatComponentSystem](https://api.playcanvas.com/engine/classes/GSplatComponentSystem.md)) - joint ([JointComponentSystem](https://api.playcanvas.com/engine/classes/JointComponentSystem.md)) - layoutchild ([LayoutChildComponentSystem](https://api.playcanvas.com/engine/classes/LayoutChildComponentSystem.md)) - layoutgroup ([LayoutGroupComponentSystem](https://api.playcanvas.com/engine/classes/LayoutGroupComponentSystem.md)) - light ([LightComponentSystem](https://api.playcanvas.com/engine/classes/LightComponentSystem.md)) - model ([ModelComponentSystem](https://api.playcanvas.com/engine/classes/ModelComponentSystem.md)) - particlesystem ([ParticleSystemComponentSystem](https://api.playcanvas.com/engine/classes/ParticleSystemComponentSystem.md)) - rigidbody ([RigidBodyComponentSystem](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md)) - render ([RenderComponentSystem](https://api.playcanvas.com/engine/classes/RenderComponentSystem.md)) - screen ([ScreenComponentSystem](https://api.playcanvas.com/engine/classes/ScreenComponentSystem.md)) - script ([ScriptComponentSystem](https://api.playcanvas.com/engine/classes/ScriptComponentSystem.md)) - scrollbar ([ScrollbarComponentSystem](https://api.playcanvas.com/engine/classes/ScrollbarComponentSystem.md)) - scrollview ([ScrollViewComponentSystem](https://api.playcanvas.com/engine/classes/ScrollViewComponentSystem.md)) - sound ([SoundComponentSystem](https://api.playcanvas.com/engine/classes/SoundComponentSystem.md)) - sprite ([SpriteComponentSystem](https://api.playcanvas.com/engine/classes/SpriteComponentSystem.md)) **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](https://api.playcanvas.com/engine/classes/AppOptions.md#devtools). - `options.elementInput` ([`ElementInput`](https://api.playcanvas.com/engine/classes/ElementInput.md), optional): Input handler for [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. - `options.gamepads` ([`GamePads`](https://api.playcanvas.com/engine/classes/GamePads.md), optional): Gamepad handler for input. - `options.graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md), 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) constructor. - `options.keyboard` ([`Keyboard`](https://api.playcanvas.com/engine/classes/Keyboard.md), optional): Keyboard handler for input. - `options.mouse` ([`Mouse`](https://api.playcanvas.com/engine/classes/Mouse.md), optional): Mouse handler for input. - `options.physicsWorld` ([`PhysicsWorld`](https://api.playcanvas.com/engine/classes/PhysicsWorld.md), 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](https://api.playcanvas.com/engine/classes/AppOptions.md#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`](https://api.playcanvas.com/engine/classes/TouchDevice.md), optional): TouchDevice handler for input. **Example** ```ts // Engine-only example: create the application manually const app = new Application(canvas, options); // Start the application's main loop app.start(); ``` ## Inherited from [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) - `assets: AssetRegistry` - `autoRender: boolean = true` - `elementInput: ElementInput | null = null` - `gamepads: GamePads | null = null` - `graphicsDevice: GraphicsDevice` - `i18n: I18n` - `keyboard: Keyboard | null = null` - `lightmapper: Lightmapper | null = null` - `loader: ResourceLoader` - `maxDeltaTime: number = 0.1` - `mouse: Mouse | null = null` - `renderNextFrame: boolean` - `root: Entity` - `scene: Scene` - `scenes: SceneRegistry` - `scripts: ScriptRegistry` - `scriptsOrder: string[] = []` - `systems: ComponentSystemRegistry` - `timeScale: number = 1` - `touch: TouchDevice | null = null` - `xr: XrManager | null = null` - `get batcher(): BatchManager` - `get fillMode(): string` - `get resolutionMode(): string` - `get stats(): AppStats` - `applySceneSettings(settings: object): void` - `configure(url: string, callback: ConfigureAppCallback): void` - `destroy(): void` - `drawLine(start: Vec3, end: Vec3, color?: Color, depthTest?: boolean, layer?: Layer): void` - `drawLineArrays(positions: number[], colors: number[] | Color, depthTest?: boolean, layer?: Layer): void` - `drawLines(positions: Vec3[], colors: Color | Color[], depthTest?: boolean, layer?: Layer): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `init(appOptions: AppOptions): void` - `isHidden(): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `preload(callback: PreloadAppCallback): void` - `resizeCanvas(width?: number, height?: number): { height: number; width: number } | undefined` - `setAreaLightLuts(ltcMat1: number[], ltcMat2: number[]): void` - `setCanvasFillMode(mode: string, width?: number, height?: number): void` - `setCanvasResolution(mode: string, width?: number, height?: number): void` - `setSkybox(asset: Asset): void` - `start(): void` - `update(dt: number): void` - `updateCanvasSize(): void` - `static getApplication(id?: string): AppBase | undefined` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AppOptions.md # AppOptions Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-options.js#L23 AppOptions holds configuration settings utilized in the creation of an [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) instance. It allows functionality to be included or excluded from the AppBase instance. ## Properties ### assetPrefix ```ts assetPrefix: string ``` Prefix to apply to asset urls before loading. ### batchManager ```ts batchManager: typeof BatchManager ``` The BatchManager. ### componentSystems ```ts componentSystems: typeof ComponentSystem[] = [] ``` The component systems the app requires. ### devtools ```ts 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 ```ts elementInput: ElementInput ``` Input handler for [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. ### gamepads ```ts gamepads: GamePads ``` Gamepad handler for input. ### graphicsDevice ```ts graphicsDevice: GraphicsDevice ``` The graphics device. ### keyboard ```ts keyboard: Keyboard ``` Keyboard handler for input. ### lightmapper ```ts lightmapper: typeof Lightmapper ``` The lightmapper. ### mouse ```ts mouse: Mouse ``` Mouse handler for input. ### physicsWorld ```ts physicsWorld: PhysicsWorld ``` The physics backend used to simulate rigid bodies, collisions and joints, such as [AmmoPhysicsWorld](https://api.playcanvas.com/engine/classes/AmmoPhysicsWorld.md) or [NullPhysicsWorld](https://api.playcanvas.com/engine/classes/NullPhysicsWorld.md). When set, the application installs it into the [RigidBodyComponentSystem](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md) during [AppBase#init](https://api.playcanvas.com/engine/classes/AppBase.md#init), so [AppOptions#componentSystems](https://api.playcanvas.com/engine/classes/AppOptions.md#componentsystems) must include [RigidBodyComponentSystem](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md). A useful simulation also requires [CollisionComponentSystem](https://api.playcanvas.com/engine/classes/CollisionComponentSystem.md) - rigid bodies and triggers obtain their shapes from collision components - and [JointComponentSystem](https://api.playcanvas.com/engine/classes/JointComponentSystem.md) if joints are used. The rigid body system registers its contact listener with the world. When omitted, an [AmmoPhysicsWorld](https://api.playcanvas.com/engine/classes/AmmoPhysicsWorld.md) 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 ```ts resourceHandlers: typeof ResourceHandler[] = [] ``` The resource handlers the app requires. ### scriptPrefix ```ts scriptPrefix: string ``` Prefix to apply to script urls before loading. ### scriptsOrder ```ts scriptsOrder: string[] ``` Scripts in order of loading first. ### soundManager ```ts soundManager: SoundManager ``` The sound manager ### touch ```ts touch: TouchDevice ``` TouchDevice handler for input. ### xr ```ts xr: typeof XrManager ``` The XrManager. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AppStats.md # AppStats Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-stats.js#L47 Performance statistics for an application, accessed through [AppBase#stats](https://api.playcanvas.com/engine/classes/AppBase.md#stats). Engine measurements are read-only; [user](https://api.playcanvas.com/engine/classes/AppStats.md#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](https://api.playcanvas.com/engine/classes/AppStats.md#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](https://api.playcanvas.com/engine/classes/AppStats.md#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** ```ts 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 ## Accessors ### cpuAnimationTime ```ts get cpuAnimationTime(): number ``` CPU duration of the latest dedicated animation-update phase in milliseconds, used by [AnimComponentSystem](https://api.playcanvas.com/engine/classes/AnimComponentSystem.md). Excludes the legacy [AnimationComponentSystem](https://api.playcanvas.com/engine/classes/AnimationComponentSystem.md), which runs in the system update phase. Part of [cpuUpdateTime](https://api.playcanvas.com/engine/classes/AppStats.md#cpuupdatetime). Available in all builds. ### cpuPhysicsTime ```ts get cpuPhysicsTime(): number ``` CPU duration of the most recent physics step in milliseconds, including synchronization and contact handling. Normally part of [cpuSystemUpdateTime](https://api.playcanvas.com/engine/classes/AppStats.md#cpusystemupdatetime). Multiple manual steps are not accumulated. Zero before any step or when physics is paused through its timeScale property. Available in all builds. ### cpuRenderTime ```ts 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. ### cpuSystemPostUpdateTime ```ts get cpuSystemPostUpdateTime(): number ``` CPU duration of the latest component systems post-update phase in milliseconds, including script postUpdate callbacks. Part of [cpuUpdateTime](https://api.playcanvas.com/engine/classes/AppStats.md#cpuupdatetime). Available in all builds. ### cpuSystemUpdateTime ```ts 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](https://api.playcanvas.com/engine/classes/AppStats.md#cpuupdatetime). Available in all builds. ### cpuUpdateTime ```ts 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. ### drawCallCount ```ts get drawCallCount(): number ``` Total draw calls submitted during the previous frame, published at the start of the next application tick. Available in all builds. ### fps ```ts get fps(): number ``` Frame count over the latest approximately one-second reporting interval. Initially zero until an interval completes. Available in all builds. ### frameTime ```ts 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. ### gpuFrameTime ```ts 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. ### primitiveCount ```ts 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. ### user ```ts get user(): Map ``` 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](https://api.playcanvas.com/engine/classes/MiniStats.md), 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** ```ts 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); ``` ### vramIndexBufferBytes ```ts get vramIndexBufferBytes(): number ``` Estimated GPU index buffer memory in bytes. Available in all builds. ### vramStorageBufferBytes ```ts 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. ### vramTextureBytes ```ts get vramTextureBytes(): number ``` Estimated GPU texture memory in bytes. Available in all builds. ### vramTotalBytes ```ts get vramTotalBytes(): number ``` Total estimated GPU resource memory in bytes: textures, vertex buffers, index buffers, uniform buffers and storage buffers. Available in all builds. ### vramUniformBufferBytes ```ts get vramUniformBufferBytes(): number ``` Estimated GPU uniform buffer memory in bytes. Available in all builds. Zero when no tracked uniform buffers have been allocated. ### vramVertexBufferBytes ```ts get vramVertexBufferBytes(): number ``` Estimated GPU vertex buffer memory in bytes. Available in all builds. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Component.md # Component Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/component.js#L77 Components are used to attach functionality on a [Entity](https://api.playcanvas.com/engine/classes/Entity.md). Components can receive update events each frame, and expose properties to the PlayCanvas Editor. ## Properties ### entity ```ts entity: Entity ``` The Entity that this Component is attached to. ### system ```ts system: ComponentSystem ``` The ComponentSystem used to create this Component. ## Accessors ### enabled ```ts get enabled(): boolean set enabled(value: boolean) ``` Gets the enabled state of the component. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ComponentSystem.md # ComponentSystem Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/system.js#L21 Component Systems contain the logic and functionality to update all Components of a particular type. ## Constructors ### constructor ```ts new ComponentSystem(app: AppBase) ``` Create a new ComponentSystem instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application managing this system. ## Properties ### id ```ts readonly id: string ``` The id type of the ComponentSystem. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ComponentSystemRegistry.md # ComponentSystemRegistry Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/registry.js#L92 The ComponentSystemRegistry manages the instances of an application's [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md)s. [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) maintains a single instance of this class which can be accessed via [AppBase#systems](https://api.playcanvas.com/engine/classes/AppBase.md#systems). ```javascript // 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; ``` ## Constructors ### constructor ```ts new ComponentSystemRegistry() ``` Create a new ComponentSystemRegistry instance. ## Properties ### anim ```ts readonly anim: AnimComponentSystem | undefined ``` Gets the [AnimComponentSystem](https://api.playcanvas.com/engine/classes/AnimComponentSystem.md) from the registry. ### animation ```ts readonly animation: AnimationComponentSystem | undefined ``` Gets the [AnimationComponentSystem](https://api.playcanvas.com/engine/classes/AnimationComponentSystem.md) from the registry. ### audiolistener ```ts readonly audiolistener: AudioListenerComponentSystem | undefined ``` Gets the [AudioListenerComponentSystem](https://api.playcanvas.com/engine/classes/AudioListenerComponentSystem.md) from the registry. ### button ```ts readonly button: ButtonComponentSystem | undefined ``` Gets the [ButtonComponentSystem](https://api.playcanvas.com/engine/classes/ButtonComponentSystem.md) from the registry. ### camera ```ts readonly camera: CameraComponentSystem | undefined ``` Gets the [CameraComponentSystem](https://api.playcanvas.com/engine/classes/CameraComponentSystem.md) from the registry. ### collision ```ts readonly collision: CollisionComponentSystem | undefined ``` Gets the [CollisionComponentSystem](https://api.playcanvas.com/engine/classes/CollisionComponentSystem.md) from the registry. ### element ```ts readonly element: ElementComponentSystem | undefined ``` Gets the [ElementComponentSystem](https://api.playcanvas.com/engine/classes/ElementComponentSystem.md) from the registry. ### gsplat ```ts readonly gsplat: GSplatComponentSystem | undefined ``` Gets the [GSplatComponentSystem](https://api.playcanvas.com/engine/classes/GSplatComponentSystem.md) from the registry. ### joint ```ts readonly joint: JointComponentSystem | undefined ``` Gets the [JointComponentSystem](https://api.playcanvas.com/engine/classes/JointComponentSystem.md) from the registry. ### layoutchild ```ts readonly layoutchild: LayoutChildComponentSystem | undefined ``` Gets the [LayoutChildComponentSystem](https://api.playcanvas.com/engine/classes/LayoutChildComponentSystem.md) from the registry. ### layoutgroup ```ts readonly layoutgroup: LayoutGroupComponentSystem | undefined ``` Gets the [LayoutGroupComponentSystem](https://api.playcanvas.com/engine/classes/LayoutGroupComponentSystem.md) from the registry. ### light ```ts readonly light: LightComponentSystem | undefined ``` Gets the [LightComponentSystem](https://api.playcanvas.com/engine/classes/LightComponentSystem.md) from the registry. ### model ```ts readonly model: ModelComponentSystem | undefined ``` Gets the [ModelComponentSystem](https://api.playcanvas.com/engine/classes/ModelComponentSystem.md) from the registry. ### particlesystem ```ts readonly particlesystem: ParticleSystemComponentSystem | undefined ``` Gets the [ParticleSystemComponentSystem](https://api.playcanvas.com/engine/classes/ParticleSystemComponentSystem.md) from the registry. ### render ```ts readonly render: RenderComponentSystem | undefined ``` Gets the [RenderComponentSystem](https://api.playcanvas.com/engine/classes/RenderComponentSystem.md) from the registry. ### rigidbody ```ts readonly rigidbody: RigidBodyComponentSystem | undefined ``` Gets the [RigidBodyComponentSystem](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md) from the registry. ### screen ```ts readonly screen: ScreenComponentSystem | undefined ``` Gets the [ScreenComponentSystem](https://api.playcanvas.com/engine/classes/ScreenComponentSystem.md) from the registry. ### script ```ts readonly script: ScriptComponentSystem | undefined ``` Gets the [ScriptComponentSystem](https://api.playcanvas.com/engine/classes/ScriptComponentSystem.md) from the registry. ### scrollbar ```ts readonly scrollbar: ScrollbarComponentSystem | undefined ``` Gets the [ScrollbarComponentSystem](https://api.playcanvas.com/engine/classes/ScrollbarComponentSystem.md) from the registry. ### scrollview ```ts readonly scrollview: ScrollViewComponentSystem | undefined ``` Gets the [ScrollViewComponentSystem](https://api.playcanvas.com/engine/classes/ScrollViewComponentSystem.md) from the registry. ### sound ```ts readonly sound: SoundComponentSystem | undefined ``` Gets the [SoundComponentSystem](https://api.playcanvas.com/engine/classes/SoundComponentSystem.md) from the registry. ### sprite ```ts readonly sprite: SpriteComponentSystem | undefined ``` Gets the [SpriteComponentSystem](https://api.playcanvas.com/engine/classes/SpriteComponentSystem.md) from the registry. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Entity.md # Entity Class · extends [`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L153 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 [Component](https://api.playcanvas.com/engine/classes/Component.md)s attached to it. An Entity therefore brings together two things: - A transform: Entity extends [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md), so it has a position, rotation and scale, and can be parented to other entities to form a hierarchy. The root of that hierarchy is [AppBase#root](https://api.playcanvas.com/engine/classes/AppBase.md#root), and child entities inherit the transforms of their ancestors. - A set of components: each [Component](https://api.playcanvas.com/engine/classes/Component.md) adds a single capability. For example, a [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) renders the scene, a [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md) lights it, a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) draws a 3D mesh, and a [ScriptComponent](https://api.playcanvas.com/engine/classes/ScriptComponent.md) runs your own code. Add a capability with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), access it later through the matching property (such as [Entity#camera](https://api.playcanvas.com/engine/classes/Entity.md#camera) or [Entity#render](https://api.playcanvas.com/engine/classes/Entity.md#render)), and remove it with [Entity#removeComponent](https://api.playcanvas.com/engine/classes/Entity.md#removecomponent). An entity, together with all of its descendants and their components, can be enabled or disabled as a group via [GraphNode#enabled](https://api.playcanvas.com/engine/classes/GraphNode.md#enabled), and removed from the scene with [Entity#destroy](https://api.playcanvas.com/engine/classes/Entity.md#destroy). **Example** ```ts // 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** ```ts // 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 ``` ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/AppBase.md), optional): The application the entity belongs to, default is the current application. **Example** ```ts 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); ``` ## Properties ### anim ```ts readonly anim: AnimComponent | undefined ``` Gets the [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md) attached to this entity. ### animation ```ts readonly animation: AnimationComponent | undefined ``` Gets the [AnimationComponent](https://api.playcanvas.com/engine/classes/AnimationComponent.md) attached to this entity. ### audiolistener ```ts readonly audiolistener: AudioListenerComponent | undefined ``` Gets the [AudioListenerComponent](https://api.playcanvas.com/engine/classes/AudioListenerComponent.md) attached to this entity. ### button ```ts readonly button: ButtonComponent | undefined ``` Gets the [ButtonComponent](https://api.playcanvas.com/engine/classes/ButtonComponent.md) attached to this entity. ### camera ```ts readonly camera: CameraComponent | undefined ``` Gets the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) attached to this entity. ### collision ```ts readonly collision: CollisionComponent | undefined ``` Gets the [CollisionComponent](https://api.playcanvas.com/engine/classes/CollisionComponent.md) attached to this entity. ### element ```ts readonly element: ElementComponent | undefined ``` Gets the [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) attached to this entity. ### gsplat ```ts readonly gsplat: GSplatComponent | undefined ``` Gets the [GSplatComponent](https://api.playcanvas.com/engine/classes/GSplatComponent.md) attached to this entity. ### joint ```ts readonly joint: JointComponent | undefined ``` Gets the [JointComponent](https://api.playcanvas.com/engine/classes/JointComponent.md) attached to this entity. ### layoutchild ```ts readonly layoutchild: LayoutChildComponent | undefined ``` Gets the [LayoutChildComponent](https://api.playcanvas.com/engine/classes/LayoutChildComponent.md) attached to this entity. ### layoutgroup ```ts readonly layoutgroup: LayoutGroupComponent | undefined ``` Gets the [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md) attached to this entity. ### light ```ts readonly light: LightComponent | undefined ``` Gets the [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md) attached to this entity. ### model ```ts readonly model: ModelComponent | undefined ``` Gets the [ModelComponent](https://api.playcanvas.com/engine/classes/ModelComponent.md) attached to this entity. ### particlesystem ```ts readonly particlesystem: ParticleSystemComponent | undefined ``` Gets the [ParticleSystemComponent](https://api.playcanvas.com/engine/classes/ParticleSystemComponent.md) attached to this entity. ### render ```ts readonly render: RenderComponent | undefined ``` Gets the [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) attached to this entity. ### rigidbody ```ts readonly rigidbody: RigidBodyComponent | undefined ``` Gets the [RigidBodyComponent](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md) attached to this entity. ### screen ```ts readonly screen: ScreenComponent | undefined ``` Gets the [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md) attached to this entity. ### script ```ts readonly script: ScriptComponent | undefined ``` Gets the [ScriptComponent](https://api.playcanvas.com/engine/classes/ScriptComponent.md) attached to this entity. ### scrollbar ```ts readonly scrollbar: ScrollbarComponent | undefined ``` Gets the [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md) attached to this entity. ### scrollview ```ts readonly scrollview: ScrollViewComponent | undefined ``` Gets the [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.md) attached to this entity. ### sound ```ts readonly sound: SoundComponent | undefined ``` Gets the [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md) attached to this entity. ### sprite ```ts readonly sprite: SpriteComponent | undefined ``` Gets the [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md) attached to this entity. ## Accessors ### guid ```ts get guid(): string ``` Gets the GUID for this Entity. ## Methods ### _notifyHierarchyStateChanged ```ts protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void ``` **Parameters** - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The node to update. - `enabled` (`boolean`): Enable or disable the node. ### _onHierarchyStateChanged ```ts protected _onHierarchyStateChanged(enabled: boolean): void ``` **Parameters** - `enabled` (`boolean`): Enable or disable the node. ### addComponent ```ts addComponent(type: K, data?: K extends ComponentName ? ComponentOptions : 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](https://api.playcanvas.com/engine/classes/CameraComponent.md) and returns `CameraComponent | null`. See [ComponentOptions](https://api.playcanvas.com/engine/types/ComponentOptions.md) for the rule and [ComponentMap](https://api.playcanvas.com/engine/types/ComponentMap.md) for extending this to application-defined components. **Parameters** - `type` ([`K`](https://api.playcanvas.com/engine/classes/Entity.md#addcomponentk)): The name of the component to add (a [ComponentName](https://api.playcanvas.com/engine/types/ComponentName.md)). Valid strings are: - "anim" - see [AnimComponent](https://api.playcanvas.com/engine/classes/AnimComponent.md) - "animation" - see [AnimationComponent](https://api.playcanvas.com/engine/classes/AnimationComponent.md) - "audiolistener" - see [AudioListenerComponent](https://api.playcanvas.com/engine/classes/AudioListenerComponent.md) - "button" - see [ButtonComponent](https://api.playcanvas.com/engine/classes/ButtonComponent.md) - "camera" - see [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) - "collision" - see [CollisionComponent](https://api.playcanvas.com/engine/classes/CollisionComponent.md) - "element" - see [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) - "gsplat" - see [GSplatComponent](https://api.playcanvas.com/engine/classes/GSplatComponent.md) - "layoutchild" - see [LayoutChildComponent](https://api.playcanvas.com/engine/classes/LayoutChildComponent.md) - "layoutgroup" - see [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md) - "light" - see [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md) - "model" - see [ModelComponent](https://api.playcanvas.com/engine/classes/ModelComponent.md) - "particlesystem" - see [ParticleSystemComponent](https://api.playcanvas.com/engine/classes/ParticleSystemComponent.md) - "render" - see [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) - "rigidbody" - see [RigidBodyComponent](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md) - "screen" - see [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md) - "script" - see [ScriptComponent](https://api.playcanvas.com/engine/classes/ScriptComponent.md) - "scrollbar" - see [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md) - "scrollview" - see [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.md) - "sound" - see [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md) - "sprite" - see [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md) - `data` ([`K`](https://api.playcanvas.com/engine/classes/Entity.md#addcomponentk) `extends` [`ComponentName`](https://api.playcanvas.com/engine/types/ComponentName.md) `?` [`ComponentOptions`](https://api.playcanvas.com/engine/types/ComponentOptions.md)`<`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#addcomponentk)`> : 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](https://api.playcanvas.com/engine/types/ComponentOptions.md)). Any object is accepted for a component name that is not in [ComponentMap](https://api.playcanvas.com/engine/types/ComponentMap.md). **Returns** `(`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#addcomponentk) `extends` [`ComponentName`](https://api.playcanvas.com/engine/types/ComponentName.md) `?` [`ComponentMap`](https://api.playcanvas.com/engine/types/ComponentMap.md)`[`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#addcomponentk)`] :` [`Component`](https://api.playcanvas.com/engine/classes/Component.md)`) | null`: The new Component that was attached to the entity or null if there was an error. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Entity.md): A new Entity which is a deep copy of the original. **Example** ```ts const e = this.entity.clone(); // Add clone as a sibling to the original this.entity.parent.addChild(e); ``` ### destroy ```ts 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** ```ts const firstChild = this.entity.children[0]; firstChild.destroy(); // destroy child and all of its descendants ``` ### findByGuid ```ts findByGuid(guid: string): Entity | null ``` Find a descendant of this entity with the GUID. **Parameters** - `guid` (`string`): The GUID to search for. **Returns** [`Entity`](https://api.playcanvas.com/engine/classes/Entity.md) `| null`: The entity with the matching GUID or null if no entity is found. ### findComponent ```ts findComponent(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`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentk)): The name of the component type to retrieve. **Returns** `(`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentk) `extends` [`ComponentName`](https://api.playcanvas.com/engine/types/ComponentName.md) `?` [`ComponentMap`](https://api.playcanvas.com/engine/types/ComponentMap.md)`[`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentk)`] :` [`Component`](https://api.playcanvas.com/engine/classes/Component.md)`) | null`: A component of specified type, if the entity or any of its descendants has one. Returns null otherwise. **Example** ```ts // Get the first found light component in the hierarchy tree that starts with this entity const light = entity.findComponent("light"); ``` ### findComponents ```ts findComponents(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`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentsk)): The name of the component type to retrieve. **Returns** `(`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentsk) `extends` [`ComponentName`](https://api.playcanvas.com/engine/types/ComponentName.md) `?` [`ComponentMap`](https://api.playcanvas.com/engine/types/ComponentMap.md)`[`[`K`](https://api.playcanvas.com/engine/classes/Entity.md#findcomponentsk)`] :` [`Component`](https://api.playcanvas.com/engine/classes/Component.md)`)[]`: All components of specified type in the entity or any of its descendants. Returns empty array if none found. **Example** ```ts // Get all light components in the hierarchy tree that starts with this entity const lights = entity.findComponents("light"); ``` ### findScript ```ts findScript(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`](https://api.playcanvas.com/engine/classes/Entity.md#findscriptt) `| undefined`: A script instance of the specified class, if the entity or any of its descendants has one. Returns undefined otherwise. **Example** ```ts // Get the first PlayerController instance in the hierarchy tree that starts with this entity const controller = entity.findScript(PlayerController); // PlayerController | undefined ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Script.md) `| undefined`: A script instance with the specified name, if the entity or any of its descendants has one. Returns undefined otherwise. **Example** ```ts // Get the first found "playerController" instance in the hierarchy tree that starts with this entity const controller = entity.findScript("playerController"); ``` ### findScripts ```ts findScripts(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`](https://api.playcanvas.com/engine/classes/Entity.md#findscriptst)`[]`: All script instances of the specified class in the entity or any of its descendants. Returns an empty array if none are found. **Example** ```ts // Get all PlayerController instances in the hierarchy tree that starts with this entity const controllers = entity.findScripts(PlayerController); // PlayerController[] ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Script.md)`[]`: All script instances with the specified name in the entity or any of its descendants. Returns an empty array if none are found. **Example** ```ts // Get all "playerController" instances in the hierarchy tree that starts with this entity const controllers = entity.findScripts("playerController"); ``` ### removeComponent ```ts removeComponent(type: string & {} | ComponentName): void ``` Remove a component from the Entity. **Parameters** - `type` (`string & {} |` [`ComponentName`](https://api.playcanvas.com/engine/types/ComponentName.md)): The name of the Component type. **Example** ```ts const entity = new Entity(); entity.addComponent("light"); // add new light component entity.removeComponent("light"); // remove light component ``` ## Events ### EVENT_DESTROY ```ts static EVENT_DESTROY: string = 'destroy' ``` Fired after the entity is destroyed. **Example** ```ts entity.on('destroy', (e) => { console.log(`Entity ${e.name} has been destroyed`); }); ``` ## Inherited from [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md) - `protected _children: GraphNode[] = []` - `name: string` - `tags: Tags` - `get children(): readonly GraphNode[]` - `get enabled(): boolean` · `set enabled(enabled: boolean)` - `get forward(): Readonly` - `get graphDepth(): number` - `get parent(): GraphNode | null` - `get path(): string` - `get right(): Readonly` - `get root(): GraphNode` - `get up(): Readonly` - `addChild(node: GraphNode): void` - `find(attr: string | FindNodeCallback, value?: any): GraphNode[]` - `findByName(name: string): GraphNode | null` - `findByPath(path: string | string[]): GraphNode | null` - `findByTag(...query: any[]): GraphNode[]` - `findOne(attr: string | FindNodeCallback, value?: any): GraphNode | null` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `forEach(callback: ForEachNodeCallback, thisArg?: any): void` - `getEulerAngles(): Readonly` - `getLocalEulerAngles(): Readonly` - `getLocalPosition(): Readonly` - `getLocalRotation(): Readonly` - `getLocalScale(): Readonly` - `getLocalTransform(): Readonly` - `getPosition(): Readonly` - `getRotation(): Readonly` - `getWorldTransform(): Readonly` - `hasEvent(name: string): boolean` - `insertChild(node: GraphNode, index: number): void` - `isAncestorOf(node: GraphNode): boolean` - `isDescendantOf(node: GraphNode): boolean` - `lookAt(x: number, y: number, z: number, ux?: number, uy?: number, uz?: number): void` · `lookAt(target: Vec3, up?: Vec3): void` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `remove(): void` - `removeChild(child: GraphNode): void` - `reparent(parent: GraphNode, index?: number): void` - `rotate(x: number, y: number, z: number): void` · `rotate(rotation: Vec3): void` - `rotateLocal(x: number, y: number, z: number): void` · `rotateLocal(rotation: Vec3): void` - `setEulerAngles(x: number, y: number, z: number): void` · `setEulerAngles(angles: Vec3): void` - `setLocalEulerAngles(x: number, y: number, z: number): void` · `setLocalEulerAngles(angles: Vec3): void` - `setLocalPosition(x: number, y: number, z: number): void` · `setLocalPosition(position: Vec3): void` - `setLocalRotation(x: number, y: number, z: number, w: number): void` · `setLocalRotation(rotation: Quat): void` - `setLocalScale(x: number, y: number, z: number): void` · `setLocalScale(scale: Vec3): void` - `setPosition(x: number, y: number, z: number): void` · `setPosition(position: Vec3): void` - `setPositionAndRotation(position: Vec3, rotation: Quat): void` - `setRotation(x: number, y: number, z: number, w: number): void` · `setRotation(rotation: Quat): void` - `translate(x: number, y: number, z: number): void` · `translate(translation: Vec3): void` - `translateLocal(x: number, y: number, z: number): void` · `translateLocal(translation: Vec3): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/EventHandle.md # EventHandle Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handle.js#L34 Event Handle that is created by [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) and can be used for easier event removal and management. **Example** ```ts 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** ```ts // 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 = []; ``` ## Constructors ### constructor ```ts new EventHandle(handler: EventHandler, name: string, callback: HandleEventCallback, scope: any, once?: boolean) ``` **Parameters** - `handler` ([`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md)): source object of the event. - `name` (`string`): Name of the event. - `callback` ([`HandleEventCallback`](https://api.playcanvas.com/engine/types/HandleEventCallback.md)): 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. ## Methods ### off ```ts off(): void ``` Remove this event from its handler. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/EventHandler.md # EventHandler Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handler.js#L34 Abstract base class that implements functionality for event handling. ```javascript 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'); ``` ## Methods ### fire ```ts 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`](https://api.playcanvas.com/engine/classes/EventHandler.md): Self for chaining. **Example** ```ts obj.fire('test', 'This is the message'); ``` ### hasEvent ```ts 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** ```ts obj.on('test', () => {}); // bind an event to 'test' obj.hasEvent('test'); // returns true obj.hasEvent('hello'); // returns false ``` ### off ```ts 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](https://api.playcanvas.com/engine/classes/EventHandle.md) returned by [EventHandler#on](https://api.playcanvas.com/engine/classes/EventHandler.md#on) / [EventHandler#once](https://api.playcanvas.com/engine/classes/EventHandler.md#once) and calling its [EventHandle#off](https://api.playcanvas.com/engine/classes/EventHandle.md#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`](https://api.playcanvas.com/engine/types/HandleEventCallback.md), optional): Function to be unbound. - `scope` (`any`, optional): Scope that was used as the this when the event is fired. **Returns** [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/types/HandleEventCallback.md)): 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`](https://api.playcanvas.com/engine/classes/EventHandle.md): An event handle. For later removal, prefer retaining this handle and calling its [EventHandle#off](https://api.playcanvas.com/engine/classes/EventHandle.md#off) over [EventHandler#off](https://api.playcanvas.com/engine/classes/EventHandler.md#off) with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list). **Example** ```ts obj.on('test', (a, b) => { console.log(a + b); }); obj.fire('test', 1, 2); // prints 3 to the console ``` **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/types/HandleEventCallback.md)): 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`](https://api.playcanvas.com/engine/classes/EventHandle.md): An event handle. For removal before it fires, prefer retaining this handle and calling its [EventHandle#off](https://api.playcanvas.com/engine/classes/EventHandle.md#off) over [EventHandler#off](https://api.playcanvas.com/engine/classes/EventHandler.md#off) with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list). **Example** ```ts 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 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GraphNode.md # GraphNode Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L122 A GraphNode is a node in the scene graph: a named object with a position, rotation and scale, and a list of [children](https://api.playcanvas.com/engine/classes/GraphNode.md#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](https://api.playcanvas.com/engine/classes/GraphNode.md#parent); the [root](https://api.playcanvas.com/engine/classes/GraphNode.md#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](https://api.playcanvas.com/engine/classes/Entity.md), which adds components, so in practice these methods are called on entities. The conventions are the same on both: - Local methods such as [setLocalPosition](https://api.playcanvas.com/engine/classes/GraphNode.md#setlocalposition) and [getLocalRotation](https://api.playcanvas.com/engine/classes/GraphNode.md#getlocalrotation) work relative to the parent. Their world counterparts, [setPosition](https://api.playcanvas.com/engine/classes/GraphNode.md#setposition), [getRotation](https://api.playcanvas.com/engine/classes/GraphNode.md#getrotation) and the rest, account for the whole chain of ancestors. - Setters accept separate components or a vector or quaternion, and copy the value. - Getters return the node's internal storage as read-only; clone the result if you need to keep or modify it. - Euler angles are in degrees, and [forward](https://api.playcanvas.com/engine/classes/GraphNode.md#forward) is the node's negative Z axis. Build the hierarchy with [addChild](https://api.playcanvas.com/engine/classes/GraphNode.md#addchild), [insertChild](https://api.playcanvas.com/engine/classes/GraphNode.md#insertchild), [removeChild](https://api.playcanvas.com/engine/classes/GraphNode.md#removechild) and [reparent](https://api.playcanvas.com/engine/classes/GraphNode.md#reparent), and search it with [findByName](https://api.playcanvas.com/engine/classes/GraphNode.md#findbyname), [findByPath](https://api.playcanvas.com/engine/classes/GraphNode.md#findbypath), [findByTag](https://api.playcanvas.com/engine/classes/GraphNode.md#findbytag) and [find](https://api.playcanvas.com/engine/classes/GraphNode.md#find). Setting [enabled](https://api.playcanvas.com/engine/classes/GraphNode.md#enabled) to false disables the node and its whole subtree. **Example** ```ts // 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** ```ts // Getters return read-only internal storage: clone before modifying const start = node.getPosition().clone(); start.y += 1; node.setPosition(start); ``` ## Constructors ### constructor ```ts 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'. ## Properties ### _children ```ts protected _children: GraphNode[] = [] ``` ### name ```ts name: string ``` The non-unique name of a graph node. Defaults to 'Untitled'. ### tags ```ts tags: Tags ``` Interface for tagging graph nodes. Tag based searches can be performed using the [findByTag](https://api.playcanvas.com/engine/classes/GraphNode.md#findbytag) function. ## Accessors ### children ```ts get children(): readonly GraphNode[] ``` Gets the children of this graph node. Use addChild, insertChild, removeChild or reparent to change the hierarchy. ### enabled ```ts get enabled(): boolean set enabled(enabled: boolean) ``` Gets the enabled state of the GraphNode. ### forward ```ts get forward(): Readonly ``` Gets the normalized local space negative Z-axis vector of the graph node in world space. ### graphDepth ```ts 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. ### parent ```ts get parent(): GraphNode | null ``` Gets the parent of this graph node. ### path ```ts get path(): string ``` Gets the path of this graph node relative to the root of the hierarchy. ### right ```ts get right(): Readonly ``` Gets the normalized local space X-axis vector of the graph node in world space. ### root ```ts get root(): GraphNode ``` Gets the oldest ancestor graph node from this graph node. ### up ```ts get up(): Readonly ``` Gets the normalized local space Y-axis vector of the graph node in world space. ## Methods ### _notifyHierarchyStateChanged ```ts protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void ``` **Parameters** - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): Graph node to update. - `enabled` (`boolean`): True if enabled in the hierarchy, false if disabled. ### _onHierarchyStateChanged ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/GraphNode.md#setposition). **Parameters** - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The new child to add. **Example** ```ts const e = new Entity(app); this.entity.addChild(e); ``` ### clone ```ts clone(): GraphNode ``` Clone a graph node. **Returns** [`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md): A clone of the specified graph node. ### destroy ```ts 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** ```ts const firstChild = graphNode.children[0]; firstChild.destroy(); // destroy child and all of its descendants ``` ### find ```ts 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`](https://api.playcanvas.com/engine/types/FindNodeCallback.md)): 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`](https://api.playcanvas.com/engine/classes/GraphNode.md)`[]`: The array of graph nodes that match the search criteria. **Example** ```ts // 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** ```ts // Finds all nodes that have the name property set to 'Test' const entities = parent.find('name', 'Test'); ``` ### findByName ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md) `| null`: The first node to be found matching the supplied name. Returns null if no node is found. ### findByPath ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md) `| null`: The first node to be found matching the supplied path. Returns null if no node is found. **Example** ```ts // String form const grandchild = this.entity.findByPath('child/grandchild'); ``` **Example** ```ts // Array form const grandchild = this.entity.findByPath(['child', 'grandchild']); ``` ### findByTag ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md)`[]`: A list of all graph nodes that match the query. **Example** ```ts // Return all graph nodes tagged with `animal` const animals = node.findByTag("animal"); ``` **Example** ```ts // Return all graph nodes tagged with `bird` OR `mammal` const birdsAndMammals = node.findByTag("bird", "mammal"); ``` **Example** ```ts // Return all graph nodes tagged with `carnivore` AND `mammal` const meatEatingMammals = node.findByTag(["carnivore", "mammal"]); ``` **Example** ```ts // Return all graph nodes tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`) const meatEatingMammalsAndReptiles = node.findByTag(["carnivore", "mammal"], ["carnivore", "reptile"]); ``` ### findOne ```ts 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`](https://api.playcanvas.com/engine/types/FindNodeCallback.md)): 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`](https://api.playcanvas.com/engine/classes/GraphNode.md) `| null`: A graph node that matches the search criteria. Returns null if no node is found. **Example** ```ts // 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** ```ts // Finds the first node that has the name property set to 'Test' const node = parent.findOne('name', 'Test'); ``` ### forEach ```ts forEach(callback: ForEachNodeCallback, thisArg?: any): void ``` Executes a provided function once on this graph node and all of its descendants. **Parameters** - `callback` ([`ForEachNodeCallback`](https://api.playcanvas.com/engine/types/ForEachNodeCallback.md)): 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** ```ts // Log the path and name of each node in descendant tree starting with "parent" parent.forEach((node) => { console.log(node.path + "/" + node.name); }); ``` ### getEulerAngles ```ts getEulerAngles(): Readonly ``` 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](https://api.playcanvas.com/engine/classes/GraphNode.md#seteulerangles). **Returns** `Readonly<`[`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`>`: The world space rotation of the graph node in Euler angle form. **Example** ```ts const angles = this.entity.getEulerAngles(); angles.y = 180; // rotate the entity around Y by 180 degrees this.entity.setEulerAngles(angles); ``` ### getLocalEulerAngles ```ts getLocalEulerAngles(): Readonly ``` 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](https://api.playcanvas.com/engine/classes/GraphNode.md#setlocaleulerangles). **Returns** `Readonly<`[`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`>`: The local space rotation of the graph node as Euler angles in XYZ order. **Example** ```ts const angles = this.entity.getLocalEulerAngles(); angles.y = 180; this.entity.setLocalEulerAngles(angles); ``` ### getLocalPosition ```ts getLocalPosition(): Readonly ``` Get the position in local space for the specified GraphNode. The position is returned as a [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md). The returned vector should be considered read-only. To update the local position, use [setLocalPosition](https://api.playcanvas.com/engine/classes/GraphNode.md#setlocalposition). **Returns** `Readonly<`[`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`>`: The local space position of the graph node. **Example** ```ts const position = this.entity.getLocalPosition().clone(); position.x += 1; // move the entity 1 unit along x. this.entity.setLocalPosition(position); ``` ### getLocalRotation ```ts getLocalRotation(): Readonly ``` Get the rotation in local space for the specified GraphNode. The rotation is returned as a [Quat](https://api.playcanvas.com/engine/classes/Quat.md). The returned quaternion should be considered read-only. To update the local rotation, use [setLocalRotation](https://api.playcanvas.com/engine/classes/GraphNode.md#setlocalrotation). **Returns** `Readonly<`[`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)`>`: The local space rotation of the graph node as a quaternion. **Example** ```ts const rotation = this.entity.getLocalRotation(); ``` ### getLocalScale ```ts getLocalScale(): Readonly ``` Get the scale in local space for the specified GraphNode. The scale is returned as a [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md). The returned vector should be considered read-only. To update the local scale, use [setLocalScale](https://api.playcanvas.com/engine/classes/GraphNode.md#setlocalscale). **Returns** `Readonly<`[`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`>`: The local space scale of the graph node. **Example** ```ts const scale = this.entity.getLocalScale().clone(); scale.x = 100; this.entity.setLocalScale(scale); ``` ### getLocalTransform ```ts getLocalTransform(): Readonly ``` 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`](https://api.playcanvas.com/engine/classes/Mat4.md)`>`: The node's local transformation matrix. **Example** ```ts const transform = this.entity.getLocalTransform(); ``` ### getPosition ```ts getPosition(): Readonly ``` Get the world space position for the specified GraphNode. The position is returned as a [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md). 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](https://api.playcanvas.com/engine/classes/GraphNode.md#setposition). **Returns** `Readonly<`[`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`>`: The world space position of the graph node. **Example** ```ts const position = this.entity.getPosition().clone(); position.x = 10; this.entity.setPosition(position); ``` ### getRotation ```ts getRotation(): Readonly ``` Get the world space rotation for the specified GraphNode. The rotation is returned as a [Quat](https://api.playcanvas.com/engine/classes/Quat.md). 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](https://api.playcanvas.com/engine/classes/GraphNode.md#setrotation). **Returns** `Readonly<`[`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)`>`: The world space rotation of the graph node as a quaternion. **Example** ```ts const rotation = this.entity.getRotation(); ``` ### getWorldTransform ```ts getWorldTransform(): Readonly ``` Get the world transformation matrix for this graph node. **Returns** `Readonly<`[`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)`>`: The node's world transformation matrix. **Example** ```ts const transform = this.entity.getWorldTransform(); ``` ### insertChild ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The new child to insert. - `index` (`number`): The index in the child list of the parent where the new node will be inserted. **Example** ```ts const e = new Entity(app); this.entity.insertChild(e, 1); ``` ### isAncestorOf ```ts isAncestorOf(node: GraphNode): boolean ``` Check if node is ancestor for another node. **Parameters** - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): Potential descendant of node. **Returns** `boolean`: If node is ancestor for another node. **Example** ```ts if (body.isAncestorOf(foot)) { // foot is within body's hierarchy } ``` ### isDescendantOf ```ts isDescendantOf(node: GraphNode): boolean ``` Check if node is descendant of another node. **Parameters** - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): Potential ancestor of node. **Returns** `boolean`: If node is descendant of another node. **Example** ```ts if (roof.isDescendantOf(house)) { // roof is descendant of house entity } ``` ### lookAt ```ts 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** ```ts // Look at the world space origin, using the (default) positive y-axis for up this.entity.lookAt(0, 0, 0); ``` **Example** ```ts // 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); ``` ```ts lookAt(target: Vec3, up?: Vec3): void ``` Reorients the graph node so that the negative z-axis points towards the target. **Parameters** - `target` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space coordinate to look at. - `up` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The world space up vector for look at transform. Defaults to [Vec3.UP](https://api.playcanvas.com/engine/classes/Vec3.md#up). **Returns** `void` **Example** ```ts // Look at another entity, using the (default) positive y-axis for up const target = otherEntity.getPosition(); this.entity.lookAt(target); ``` **Example** ```ts // Look at another entity, using the negative world y-axis for up const target = otherEntity.getPosition(); this.entity.lookAt(target, Vec3.DOWN); ``` ### remove ```ts remove(): void ``` Remove graph node from current parent. ### removeChild ```ts 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`](https://api.playcanvas.com/engine/classes/GraphNode.md)): The node to remove. **Example** ```ts const child = this.entity.children[0]; this.entity.removeChild(child); ``` ### reparent ```ts reparent(parent: GraphNode, index?: number): void ``` Remove graph node from current parent and add as child to new parent. **Parameters** - `parent` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)): New parent to attach graph node to. - `index` (`number`, optional): The child index where the child node should be placed. ### rotate ```ts 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** ```ts this.entity.rotate(0, 90, 0); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding world space rotation. **Returns** `void` **Example** ```ts const rotation = new Vec3(0, 90, 0); this.entity.rotate(rotation); ``` ### rotateLocal ```ts 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** ```ts this.entity.rotateLocal(0, 90, 0); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding local space rotation. **Returns** `void` **Example** ```ts const rotation = new Vec3(0, 90, 0); this.entity.rotateLocal(rotation); ``` ### setEulerAngles ```ts 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** ```ts this.entity.setEulerAngles(0, 90, 0); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding rotations around world space axes in degrees. **Returns** `void` **Example** ```ts const angles = new Vec3(0, 90, 0); this.entity.setEulerAngles(angles); ``` ### setLocalEulerAngles ```ts 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** ```ts // Set rotation of 90 degrees around y-axis via 3 numbers this.entity.setLocalEulerAngles(0, 90, 0); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding rotations around local space axes in degrees. **Returns** `void` **Example** ```ts // Set rotation of 90 degrees around y-axis via a vector const angles = new Vec3(0, 90, 0); this.entity.setLocalEulerAngles(angles); ``` ### setLocalPosition ```ts 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** ```ts this.entity.setLocalPosition(0, 10, 0); ``` ```ts setLocalPosition(position: Vec3): void ``` Sets the local space position of the specified graph node. **Parameters** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding local space position. **Returns** `void` **Example** ```ts const pos = new Vec3(0, 10, 0); this.entity.setLocalPosition(pos); ``` ### setLocalRotation ```ts 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** ```ts this.entity.setLocalRotation(0, 0, 0, 1); ``` ```ts setLocalRotation(rotation: Quat): void ``` Sets the local space rotation of the specified graph node. **Parameters** - `rotation` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): Quaternion holding local space rotation. **Returns** `void` **Example** ```ts const q = new Quat(); this.entity.setLocalRotation(q); ``` ### setLocalScale ```ts 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** ```ts this.entity.setLocalScale(10, 10, 10); ``` ```ts setLocalScale(scale: Vec3): void ``` Sets the local space scale factor of the specified graph node. **Parameters** - `scale` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding local space scale. **Returns** `void` **Example** ```ts const scale = new Vec3(10, 10, 10); this.entity.setLocalScale(scale); ``` ### setPosition ```ts 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** ```ts this.entity.setPosition(0, 10, 0); ``` ```ts setPosition(position: Vec3): void ``` Sets the world space position of the specified graph node. **Parameters** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding world space position. **Returns** `void` **Example** ```ts const position = new Vec3(0, 10, 0); this.entity.setPosition(position); ``` ### setPositionAndRotation ```ts 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** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space position to set. - `rotation` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The world space rotation to set. **Example** ```ts const position = new Vec3(0, 10, 0); const rotation = new Quat().setFromEulerAngles(0, 90, 0); this.entity.setPositionAndRotation(position, rotation); ``` ### setRotation ```ts 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** ```ts this.entity.setRotation(0, 0, 0, 1); ``` ```ts setRotation(rotation: Quat): void ``` Sets the world space rotation of the specified graph node. **Parameters** - `rotation` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): Quaternion holding world space rotation. **Returns** `void` **Example** ```ts const rotation = new Quat(); this.entity.setRotation(rotation); ``` ### translate ```ts 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** ```ts this.entity.translate(10, 0, 0); ``` ```ts translate(translation: Vec3): void ``` Translates the graph node in world space by the specified translation vector. **Parameters** - `translation` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding world space translation. **Returns** `void` **Example** ```ts const translation = new Vec3(10, 0, 0); this.entity.translate(translation); ``` ### translateLocal ```ts 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** ```ts this.entity.translateLocal(10, 0, 0); ``` ```ts translateLocal(translation: Vec3): void ``` Translates the graph node in local space by the specified translation vector. **Parameters** - `translation` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding local space translation. **Returns** `void` **Example** ```ts const t = new Vec3(10, 0, 0); this.entity.translateLocal(t); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Http.md # Http Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/net/http.js#L28 Used to send and receive HTTP requests. ## Methods ### del ```ts 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`](https://api.playcanvas.com/engine/types/HttpResponseCallback.md)): 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** ```ts http.del("http://example.com/", { "retry": true, "maxRetries": 5 }, (err, response) => { console.log(response); }); ``` ### get ```ts 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`](https://api.playcanvas.com/engine/classes/EventHandler.md), 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`](https://api.playcanvas.com/engine/types/HttpResponseCallback.md)): 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** ```ts http.get("http://example.com/", { "retry": true, "maxRetries": 5 }, (err, response) => { console.log(response); }); ``` ### post ```ts 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`](https://api.playcanvas.com/engine/types/HttpResponseCallback.md)): 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** ```ts http.post("http://example.com/", { "name": "Alex" }, { "retry": true, "maxRetries": 5 }, (err, response) => { console.log(response); }); ``` ### put ```ts 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`](https://api.playcanvas.com/engine/types/HttpResponseCallback.md)): 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** ```ts http.put("http://example.com/", { "name": "Alex" }, { "retry": true, "maxRetries": 5 }, (err, response) => { console.log(response); }); ``` ### request ```ts 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`](https://api.playcanvas.com/engine/types/HttpResponseCallback.md)): 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** ```ts http.request("get", "http://example.com/", { "retry": true, "maxRetries": 5 }, (err, response) => { console.log(response); }); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/I18n.md # I18n Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/i18n/i18n.js#L18 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](https://api.playcanvas.com/engine/classes/I18n.md#gettext) and [getPluralText](https://api.playcanvas.com/engine/classes/I18n.md#getpluraltext). ## Constructors ### constructor ```ts new I18n(app: AppBase) ``` Create a new I18n instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. ## Accessors ### assets ```ts get assets(): number[] | Asset[] set assets(value: number[] | Asset[]) ``` Gets the array of asset ids that contain localization data in the expected format. ### locale ```ts get locale(): string set locale(value: string) ``` Gets the current locale. ## Methods ### addData ```ts 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** ```ts 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 ```ts destroy(): void ``` Frees up memory. ### findAvailableLocale ```ts 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** ```ts const locale = this.app.i18n.getText('en-US'); ``` ### getPluralText ```ts 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** ```ts // manually replace {number} in the resulting translation with our number const localized = this.app.i18n.getPluralText('{number} apples', number).replace("{number}", number); ``` ### getText ```ts 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** ```ts const localized = this.app.i18n.getText('localization-key'); const localizedFrench = this.app.i18n.getText('localization-key', 'fr-FR'); ``` ### removeData ```ts 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](https://api.playcanvas.com/engine/classes/I18n.md#adddata). ## Events ### EVENT_CHANGE ```ts static EVENT_CHANGE: string = 'change' ``` Fired when the locale is changed. **Example** ```ts app.i18n.on('change', (newLocale, oldLocale) => { console.log(`Locale changed from ${oldLocale} to ${newLocale}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RefCountedObject.md # RefCountedObject Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/ref-counted-object.js#L6 Base class that implements reference counting for objects. ## Accessors ### refCount ```ts get refCount(): number ``` Gets the current reference count. ## Methods ### decRefCount ```ts decRefCount(): void ``` Decrements the reference counter. ### incRefCount ```ts incRefCount(): void ``` Increments the reference counter. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Tags.md # Tags Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/tags.js#L14 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 [Asset](https://api.playcanvas.com/engine/classes/Asset.md)s and [Entity](https://api.playcanvas.com/engine/classes/Entity.md)s (see [Asset#tags](https://api.playcanvas.com/engine/classes/Asset.md#tags) and [GraphNode#tags](https://api.playcanvas.com/engine/classes/GraphNode.md#tags)). You can search for specific assets via [AssetRegistry#findByTag](https://api.playcanvas.com/engine/classes/AssetRegistry.md#findbytag) and specific entities via [GraphNode#findByTag](https://api.playcanvas.com/engine/classes/GraphNode.md#findbytag). ## Constructors ### constructor ```ts new Tags(parent?: any) ``` Create a new Tags instance. **Parameters** - `parent` (`any`, optional): Parent object who tags belong to. ## Accessors ### size ```ts get size(): number ``` Number of tags in set. ## Methods ### add ```ts 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** ```ts tags.add('level-1'); ``` **Example** ```ts tags.add('ui', 'settings'); ``` **Example** ```ts tags.add(['level-2', 'mob']); ``` ### clear ```ts clear(): void ``` Remove all tags. **Example** ```ts tags.clear(); ``` ### has ```ts 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** ```ts tags.has('player'); // player ``` **Example** ```ts tags.has('mob', 'player'); // player OR mob ``` **Example** ```ts tags.has(['level-1', 'mob']); // monster AND level-1 ``` **Example** ```ts tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels) ``` ### list ```ts list(): string[] ``` Returns immutable array of tags. **Returns** `string[]`: Copy of tags array. ### remove ```ts 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** ```ts tags.remove('level-1'); ``` **Example** ```ts tags.remove('ui', 'settings'); ``` **Example** ```ts tags.remove(['level-2', 'mob']); ``` ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired for each individual tag that is added. **Example** ```ts tags.on('add', (tag, parent) => { console.log(`${tag} added to ${parent.name}`); }); ``` ### EVENT_CHANGE ```ts 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** ```ts tags.on('change', (parent) => { console.log(`Tags changed on ${parent.name}`); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired for each individual tag that is removed. **Example** ```ts tags.on('remove', (tag, parent) => { console.log(`${tag} removed from ${parent.name}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Template.md # Template Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/template.js#L13 Create a Template resource from raw database data. ## Constructors ### constructor ```ts new Template(app: AppBase, data: any) ``` Create a new Template instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. - `data` (`any`): Asset data from the database. ## Methods ### instantiate ```ts instantiate(): Entity ``` Create an instance of this template. **Returns** [`Entity`](https://api.playcanvas.com/engine/classes/Entity.md): The root entity of the created instance. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/WasmModule.md # WasmModule Class · category: Framework Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L149 A pure static utility class which supports immediate and lazy loading of [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) modules. Note that you can load WebAssembly modules even before instantiating your [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) 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](https://api.playcanvas.com/engine/functions/basisInitialize.md). **Example** ```ts // 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()); }); ``` ## Methods ### getConfig ```ts static getConfig(moduleName: string): any ``` Get a wasm module's configuration. **Parameters** - `moduleName` (`string`): Name of the module. **Returns** `any`: The previously set configuration. ### getInstance ```ts 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`](https://api.playcanvas.com/engine/types/ModuleInstanceCallback.md)): The function called when the instance is available. ### setConfig ```ts 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`](https://api.playcanvas.com/engine/types/ModuleErrorCallback.md), 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Gizmo.md # Gizmo Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Gizmo Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/gizmo.js#L56 The base class for all gizmos. A gizmo is an interactive widget drawn over the scene in its own [Layer](https://api.playcanvas.com/engine/classes/Layer.md); [createLayer](https://api.playcanvas.com/engine/classes/Gizmo.md#createlayer) makes such a layer and adds it to the scene and the camera. Construct a gizmo for a [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md), then [attach](https://api.playcanvas.com/engine/classes/Gizmo.md#attach) the [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md)s it should act on, which are then listed in [nodes](https://api.playcanvas.com/engine/classes/Gizmo.md#nodes); [detach](https://api.playcanvas.com/engine/classes/Gizmo.md#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](https://api.playcanvas.com/engine/classes/Gizmo.md#destroy). [size](https://api.playcanvas.com/engine/classes/Gizmo.md#size) scales the widget, which otherwise keeps a constant apparent size as the camera moves; [coordSpace](https://api.playcanvas.com/engine/classes/Gizmo.md#coordspace) selects `'world'` or `'local'` axes; [enabled](https://api.playcanvas.com/engine/classes/Gizmo.md#enabled) hides it without detaching; and [mouseButtons](https://api.playcanvas.com/engine/classes/Gizmo.md#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](https://api.playcanvas.com/engine/classes/TransformGizmo.md) builds the translate, rotate and scale gizmos on this base. ## Constructors ### constructor ```ts new Gizmo(camera: CameraComponent, layer: Layer, name?: string) ``` Creates a new Gizmo object. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): 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** ```ts const gizmo = new Gizmo(camera, layer); ``` ## Properties ### _app ```ts protected _app: AppBase ``` Internal reference to the app containing the gizmo. ### _camera ```ts protected _camera: CameraComponent ``` Internal reference to camera component to view the gizmo. ### _coordSpace ```ts protected _coordSpace: GizmoSpace = 'world' ``` Internal version of coordinate space. Defaults to 'world'. ### _device ```ts protected _device: GraphicsDevice ``` Internal reference to the graphics device of the app. ### _handles ```ts protected _handles: EventHandle[] = [] ``` Internal list of app event handles for the gizmo. ### _layer ```ts protected _layer: Layer ``` Internal reference to layer to render the gizmo.. ### _mouseButtons ```ts protected _mouseButtons: [boolean, boolean, boolean] ``` Internal array of mouse buttons that can interact with the gizmo. ### _renderUpdate ```ts protected _renderUpdate: boolean = false ``` Internal flag to track if a render update is required. ### _scale ```ts protected _scale: number = 1 ``` Internal version of the gizmo scale. Defaults to 1. ### intersectShapes ```ts intersectShapes: Shape[] = [] ``` The intersection shapes for the gizmo. ### nodes ```ts nodes: GraphNode[] = [] ``` The graph nodes attached to the gizmo. ### preventDefault ```ts preventDefault: boolean = true ``` Flag to indicate whether to call `preventDefault` on pointer events. ### root ```ts root: Entity ``` The root gizmo entity. ## Accessors ### camera ```ts get camera(): CameraComponent set camera(camera: CameraComponent) ``` Gets the camera component to view the gizmo. ### cameraDir ```ts protected get cameraDir(): Vec3 ``` ### coordSpace ```ts get coordSpace(): GizmoSpace set coordSpace(value: GizmoSpace) ``` Gets the gizmo coordinate space. ### enabled ```ts get enabled(): boolean set enabled(state: boolean) ``` Gets the gizmo enabled state. ### facingDir ```ts protected get facingDir(): Vec3 ``` ### layer ```ts get layer(): Layer set layer(layer: Layer) ``` Gets the gizmo render layer. ### mouseButtons ```ts get mouseButtons(): [boolean, boolean, boolean] ``` Array of mouse buttons that can interact with the gizmo. The button indices are defined as: - 0: Left button - 1: Middle button - 2: Right button The full list of button indices can be found here: [https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button) ### size ```ts get size(): number set size(value: number) ``` Gets the gizmo size. ## Methods ### _updatePosition ```ts protected _updatePosition(): void ``` ### _updateRotation ```ts protected _updateRotation(): void ``` ### _updateScale ```ts protected _updateScale(): void ``` ### attach ```ts attach(nodes?: GraphNode | GraphNode[]): void ``` Attach an array of graph nodes to the gizmo. **Parameters** - `nodes` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md) `|` [`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md)`[]`, optional, default `[]`): The graph nodes. Defaults to []. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.attach([boxA, boxB]); ``` ### destroy ```ts destroy(): void ``` Detaches all graph nodes and destroys the gizmo instance. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.attach([boxA, boxB]); gizmo.destroy(); ``` ### detach ```ts detach(): void ``` Detaches all graph nodes from the gizmo. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.attach([boxA, boxB]); gizmo.detach(); ``` ### prerender ```ts prerender(): void ``` Pre-render method. This is called before the gizmo is rendered. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.attach([boxA, boxB]); gizmo.prerender(); ``` ### update ```ts update(): void ``` Updates the gizmo position, rotation, and scale. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.attach([boxA, boxB]); gizmo.update(); ``` ### createLayer ```ts static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer ``` Creates a new gizmo layer and adds it to the scene. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): 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`](https://api.playcanvas.com/engine/classes/Layer.md): The new layer. ## Events ### EVENT_NODESATTACH ```ts static EVENT_NODESATTACH: string = 'nodes:attach' ``` Fired when graph nodes are attached. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.on('nodes:attach', () => { console.log('Graph nodes attached'); }); ``` ### EVENT_NODESDETACH ```ts static EVENT_NODESDETACH: string = 'nodes:detach' ``` Fired when graph nodes are detached. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.on('nodes:detach', () => { console.log('Graph nodes detached'); }); ``` ### EVENT_POINTERDOWN ```ts static EVENT_POINTERDOWN: string = 'pointer:down' ``` Fired when the pointer is down on the gizmo. **Example** ```ts 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}`); }); ``` ### EVENT_POINTERMOVE ```ts static EVENT_POINTERMOVE: string = 'pointer:move' ``` Fired when the pointer is moving over the gizmo. **Example** ```ts 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}`); }); ``` ### EVENT_POINTERUP ```ts static EVENT_POINTERUP: string = 'pointer:up' ``` Fired when the pointer is up off the gizmo. **Example** ```ts 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}`); }) ``` ### EVENT_POSITIONUPDATE ```ts static EVENT_POSITIONUPDATE: string = 'position:update' ``` Fired when the gizmo's position is updated. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.on('position:update', (position) => { console.log(`The gizmo's position was updated to ${position}`); }) ``` ### EVENT_RENDERUPDATE ```ts static EVENT_RENDERUPDATE: string = 'render:update' ``` Fired when the gizmo render has updated. **Example** ```ts const gizmo = new TransformGizmo(camera, layer); gizmo.on('render:update', () => { console.log('Gizmo render has been updated'); }); ``` ### EVENT_ROTATIONUPDATE ```ts static EVENT_ROTATIONUPDATE: string = 'rotation:update' ``` Fired when the gizmo's rotation is updated. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.on('rotation:update', (rotation) => { console.log(`The gizmo's rotation was updated to ${rotation}`); }); ``` ### EVENT_SCALEUPDATE ```ts static EVENT_SCALEUPDATE: string = 'scale:update' ``` Fired when the gizmo's scale is updated. **Example** ```ts const gizmo = new Gizmo(camera, layer); gizmo.on('scale:update', (scale) => { console.log(`The gizmo's scale was updated to ${scale}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RotateGizmo.md # RotateGizmo Class · extends [`TransformGizmo`](https://api.playcanvas.com/engine/classes/TransformGizmo.md) · category: Gizmo Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/rotate-gizmo.js#L68 The RotateGizmo provides interactive 3D manipulation handles for rotating/reorienting [Entity](https://api.playcanvas.com/engine/classes/Entity.md)s in a [Scene](https://api.playcanvas.com/engine/classes/Scene.md). 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. ```javascript // 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: - [Rotate Gizmo](https://playcanvas.github.io/#/gizmos/transform-rotate) - [Editor](https://playcanvas.github.io/#/misc/editor) ## Constructors ### constructor ```ts new RotateGizmo(camera: CameraComponent, layer: Layer) ``` Creates a new RotateGizmo object. Use [Gizmo.createLayer](https://api.playcanvas.com/engine/classes/Gizmo.md#createlayer) to create the layer required to display the gizmo. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): The layer responsible for rendering the gizmo. **Example** ```ts const gizmo = new RotateGizmo(camera, layer); ``` ## Properties ### _shapes ```ts 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 ```ts rotationMode: "absolute" | "orbit" = 'absolute' ``` The rotation mode of the gizmo. This can be either: - 'absolute': The rotation is calculated based on the mouse displacement relative to the initial click point. - 'orbit': The rotation is calculated based on the gizmos position around the center of rotation. ### snapIncrement ```ts snapIncrement: number = 5 ``` ## Accessors ### angleGuideThickness ```ts get angleGuideThickness(): number set angleGuideThickness(value: number) ``` Gets the angle guide line thickness. ### centerRadius ```ts get centerRadius(): number set centerRadius(value: number) ``` Gets the center radius. ### faceRingRadius ```ts get faceRingRadius(): number set faceRingRadius(value: number) ``` Gets the face ring radius. ### faceTubeRadius ```ts get faceTubeRadius(): number set faceTubeRadius(value: number) ``` Gets the face tube radius. ### ringTolerance ```ts get ringTolerance(): number set ringTolerance(value: number) ``` Gets the ring tolerance. ### xyzRingRadius ```ts get xyzRingRadius(): number set xyzRingRadius(value: number) ``` Gets the XYZ ring radius. ### xyzTubeRadius ```ts get xyzTubeRadius(): number set xyzTubeRadius(value: number) ``` Gets the XYZ tube radius. ## Methods ### _calculateArcAngle ```ts protected _calculateArcAngle(point: Vec3, x: number, y: number): number ``` **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point. - `x` (`number`): The x coordinate. - `y` (`number`): The y coordinate. **Returns** `number`: The angle. ### _drawGuideLines ```ts _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void ``` **Parameters** - `pos` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The position. - `rot` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The rotation. - `activeAxis` ([`GizmoAxis`](https://api.playcanvas.com/engine/types/GizmoAxis.md)): The active axis. - `activeIsPlane` (`boolean`): Whether the active axis is a plane. ### _screenToPoint ```ts protected _screenToPoint(x: number, y: number): Vec3 ``` **Parameters** - `x` (`number`): The x coordinate. - `y` (`number`): The y coordinate. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The point (space is [TransformGizmo#coordSpace](https://api.playcanvas.com/engine/classes/TransformGizmo.md#coordspace)). ### destroy ```ts destroy(): void ``` ### prerender ```ts prerender(): void ``` ## Inherited from [TransformGizmo](https://api.playcanvas.com/engine/classes/TransformGizmo.md) - `protected _app: AppBase` - `protected _camera: CameraComponent` - `protected _coordSpace: GizmoSpace = 'world'` - `protected _device: GraphicsDevice` - `protected _handles: EventHandle[] = []` - `protected _layer: Layer` - `protected _mouseButtons: [boolean, boolean, boolean]` - `protected _renderUpdate: boolean = false` - `protected _rootStartPos: Vec3` - `protected _rootStartRot: Quat` - `protected _scale: number = 1` - `protected _selectedAxis: "" | GizmoAxis = ''` - `protected _selectedIsPlane: boolean = false` - `protected _selectionStartPoint: Vec3` - `protected _theme: GizmoTheme` - `dragMode: GizmoDragMode = 'selected'` - `intersectShapes: Shape[] = []` - `nodes: GraphNode[] = []` - `preventDefault: boolean = true` - `root: Entity` - `snap: boolean = false` - `protected get _dragging(): boolean` - `get camera(): CameraComponent` · `set camera(camera: CameraComponent)` - `protected get cameraDir(): Vec3` - `get coordSpace(): GizmoSpace` · `set coordSpace(value: GizmoSpace)` - `get enabled(): boolean` · `set enabled(state: boolean)` - `protected get facingDir(): Vec3` - `get layer(): Layer` · `set layer(layer: Layer)` - `get mouseButtons(): [boolean, boolean, boolean]` - `get size(): number` · `set size(value: number)` - `get theme(): GizmoTheme` - `protected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Plane` - `protected _createRay(mouseWPos: Vec3): Ray` - `protected _createTransform(): void` - `protected _dirFromAxis(axis: string, dir: Vec3): Vec3` - `protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void` - `protected _projectToAxis(point: Vec3, axis: string): void` - `protected _updatePosition(): void` - `protected _updateRotation(): void` - `protected _updateScale(): void` - `attach(nodes?: GraphNode | GraphNode[]): void` - `detach(): void` - `enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `setTheme(partial: object): void` - `update(): void` - `static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer` - `static 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'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScaleGizmo.md # ScaleGizmo Class · extends [`TransformGizmo`](https://api.playcanvas.com/engine/classes/TransformGizmo.md) · category: Gizmo Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/scale-gizmo.js#L60 The ScaleGizmo provides interactive 3D manipulation handles for scaling/resizing [Entity](https://api.playcanvas.com/engine/classes/Entity.md)s in a [Scene](https://api.playcanvas.com/engine/classes/Scene.md). 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. ```javascript // 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: - [Scale Gizmo](https://playcanvas.github.io/#/gizmos/transform-scale) - [Editor](https://playcanvas.github.io/#/misc/editor) ## Constructors ### constructor ```ts new ScaleGizmo(camera: CameraComponent, layer: Layer) ``` Creates a new ScaleGizmo object. Use [Gizmo.createLayer](https://api.playcanvas.com/engine/classes/Gizmo.md#createlayer) to create the layer required to display the gizmo. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): The layer responsible for rendering the gizmo. **Example** ```ts const gizmo = new ScaleGizmo(camera, layer); ``` ## Properties ### _coordSpace ```ts protected _coordSpace: GizmoSpace = 'local' ``` ### _shapes ```ts 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) ### _uniform ```ts protected _uniform: boolean = false ``` Internal state if transform should use uniform scaling. ### flipPlanes ```ts flipPlanes: boolean = true ``` Flips the planes to face the camera. ### lowerBoundScale ```ts lowerBoundScale: Vec3 ``` The lower bound for scaling. ### snapIncrement ```ts snapIncrement: number = 1 ``` ## Accessors ### axisBoxSize ```ts get axisBoxSize(): number set axisBoxSize(value: number) ``` Gets the axis box size. ### axisCenterSize ```ts get axisCenterSize(): number set axisCenterSize(value: number) ``` Gets the axis center size. ### axisGap ```ts get axisGap(): number set axisGap(value: number) ``` Gets the axis gap. ### axisLineLength ```ts get axisLineLength(): number set axisLineLength(value: number) ``` Gets the axis line length. ### axisLineThickness ```ts get axisLineThickness(): number set axisLineThickness(value: number) ``` Gets the axis line thickness. ### axisLineTolerance ```ts get axisLineTolerance(): number set axisLineTolerance(value: number) ``` Gets the axis line tolerance. ### axisPlaneGap ```ts get axisPlaneGap(): number set axisPlaneGap(value: number) ``` Gets the plane gap. ### axisPlaneSize ```ts get axisPlaneSize(): number set axisPlaneSize(value: number) ``` Gets the plane size. ### coordSpace ```ts get coordSpace(): GizmoSpace set coordSpace(value: GizmoSpace) ``` Sets the gizmo coordinate space. Defaults to 'world' ### uniform ```ts get uniform(): boolean set uniform(value: boolean) ``` Gets the uniform scaling state for planes. ## Methods ### _screenToPoint ```ts protected _screenToPoint(x: number, y: number): Vec3 ``` **Parameters** - `x` (`number`): The x coordinate. - `y` (`number`): The y coordinate. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The point (space is [TransformGizmo#coordSpace](https://api.playcanvas.com/engine/classes/TransformGizmo.md#coordspace)). ### prerender ```ts prerender(): void ``` ## Inherited from [TransformGizmo](https://api.playcanvas.com/engine/classes/TransformGizmo.md) - `protected _app: AppBase` - `protected _camera: CameraComponent` - `protected _device: GraphicsDevice` - `protected _handles: EventHandle[] = []` - `protected _layer: Layer` - `protected _mouseButtons: [boolean, boolean, boolean]` - `protected _renderUpdate: boolean = false` - `protected _rootStartPos: Vec3` - `protected _rootStartRot: Quat` - `protected _scale: number = 1` - `protected _selectedAxis: "" | GizmoAxis = ''` - `protected _selectedIsPlane: boolean = false` - `protected _selectionStartPoint: Vec3` - `protected _theme: GizmoTheme` - `dragMode: GizmoDragMode = 'selected'` - `intersectShapes: Shape[] = []` - `nodes: GraphNode[] = []` - `preventDefault: boolean = true` - `root: Entity` - `snap: boolean = false` - `protected get _dragging(): boolean` - `get camera(): CameraComponent` · `set camera(camera: CameraComponent)` - `protected get cameraDir(): Vec3` - `get enabled(): boolean` · `set enabled(state: boolean)` - `protected get facingDir(): Vec3` - `get layer(): Layer` · `set layer(layer: Layer)` - `get mouseButtons(): [boolean, boolean, boolean]` - `get size(): number` · `set size(value: number)` - `get theme(): GizmoTheme` - `protected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Plane` - `protected _createRay(mouseWPos: Vec3): Ray` - `protected _createTransform(): void` - `protected _dirFromAxis(axis: string, dir: Vec3): Vec3` - `protected _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: "" | GizmoAxis, activeIsPlane: boolean): void` - `protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void` - `protected _projectToAxis(point: Vec3, axis: string): void` - `protected _updatePosition(): void` - `protected _updateRotation(): void` - `protected _updateScale(): void` - `attach(nodes?: GraphNode | GraphNode[]): void` - `destroy(): void` - `detach(): void` - `enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `setTheme(partial: object): void` - `update(): void` - `static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer` - `static 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'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TransformGizmo.md # TransformGizmo Class · extends [`Gizmo`](https://api.playcanvas.com/engine/classes/Gizmo.md) · category: Gizmo Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/transform-gizmo.js#L61 The base class for all transform gizmos. It adds to [Gizmo](https://api.playcanvas.com/engine/classes/Gizmo.md) everything the [TranslateGizmo](https://api.playcanvas.com/engine/classes/TranslateGizmo.md), [RotateGizmo](https://api.playcanvas.com/engine/classes/RotateGizmo.md) and [ScaleGizmo](https://api.playcanvas.com/engine/classes/ScaleGizmo.md) share: colored X, Y and Z handles with plane and center shapes, any of which [enableShape](https://api.playcanvas.com/engine/classes/TransformGizmo.md#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](https://api.playcanvas.com/engine/classes/TransformGizmo.md#snap) with [snapIncrement](https://api.playcanvas.com/engine/classes/TransformGizmo.md#snapincrement) to quantize the change; [dragMode](https://api.playcanvas.com/engine/classes/TransformGizmo.md#dragmode) to show, hide or keep only the selected shape while dragging; and a color [theme](https://api.playcanvas.com/engine/classes/TransformGizmo.md#theme) adjusted through [setTheme](https://api.playcanvas.com/engine/classes/TransformGizmo.md#settheme), `xAxisColor`, `yAxisColor`, `zAxisColor` and `colorAlpha`. The subclasses decide what a drag does to the attached nodes. ## Constructors ### constructor ```ts new TransformGizmo(camera: CameraComponent, layer: Layer, name?: string) ``` Creates a new TransformGizmo object. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): The render layer. - `name` (`string`, optional, default `'gizmo:transform'`): The name of the gizmo. **Example** ```ts const gizmo = new TransformGizmo(camera, layer); ``` ## Properties ### _rootStartPos ```ts protected _rootStartPos: Vec3 ``` Internal gizmo starting rotation in world space. ### _rootStartRot ```ts protected _rootStartRot: Quat ``` Internal gizmo starting rotation in world space. ### _selectedAxis ```ts protected _selectedAxis: "" | GizmoAxis = '' ``` Internal currently selected axis. ### _selectedIsPlane ```ts protected _selectedIsPlane: boolean = false ``` Internal state of if currently selected shape is a plane. ### _selectionStartPoint ```ts protected _selectionStartPoint: Vec3 ``` Internal selection starting coordinates in world space. ### _shapes ```ts 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) ### _theme ```ts protected _theme: GizmoTheme ``` Internal theme. ### dragMode ```ts dragMode: GizmoDragMode = 'selected' ``` Whether to hide the shapes when dragging. Defaults to 'selected'. ### snap ```ts snap: boolean = false ``` Whether snapping is enabled. Defaults to false. ### snapIncrement ```ts snapIncrement: number = 1 ``` Snapping increment. Defaults to 1. ## Accessors ### _dragging ```ts protected get _dragging(): boolean ``` ### theme ```ts get theme(): GizmoTheme ``` Gets the current theme for the gizmo. ## Methods ### _createPlane ```ts 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`](https://api.playcanvas.com/engine/classes/Plane.md): - The plane. ### _createRay ```ts protected _createRay(mouseWPos: Vec3): Ray ``` **Parameters** - `mouseWPos` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The mouse world position. **Returns** [`Ray`](https://api.playcanvas.com/engine/classes/Ray.md): - The ray. ### _createTransform ```ts protected _createTransform(): void ``` ### _dirFromAxis ```ts protected _dirFromAxis(axis: string, dir: Vec3): Vec3 ``` **Parameters** - `axis` (`string`): The axis - `dir` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The direction **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): - The direction ### _drawGuideLines ```ts protected _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: "" | GizmoAxis, activeIsPlane: boolean): void ``` **Parameters** - `pos` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The position. - `rot` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The rotation. - `activeAxis` (`"" |` [`GizmoAxis`](https://api.playcanvas.com/engine/types/GizmoAxis.md)): The active axis. - `activeIsPlane` (`boolean`): Whether the active axis is a plane. ### _drawSpanLine ```ts protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void ``` **Parameters** - `pos` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The position. - `rot` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The rotation. - `axis` (`"x" | "y" | "z"`): The axis. ### _projectToAxis ```ts protected _projectToAxis(point: Vec3, axis: string): void ``` **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point to project. - `axis` (`string`): The axis to project to. ### _screenToPoint ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md): The point (space is [Gizmo#coordSpace](https://api.playcanvas.com/engine/classes/Gizmo.md#coordspace)). ### destroy ```ts destroy(): void ``` ### enableShape ```ts enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void ``` Set the shape to be enabled or disabled. **Parameters** - `shapeAxis` (`"face" |` [`GizmoAxis`](https://api.playcanvas.com/engine/types/GizmoAxis.md)): The shape axis. - `enabled` (`boolean`): The enabled state of shape. ### isShapeEnabled ```ts isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean ``` Get the enabled state of the shape. **Parameters** - `shapeAxis` (`"face" |` [`GizmoAxis`](https://api.playcanvas.com/engine/types/GizmoAxis.md)): The shape axis. Can be: **Returns** `boolean`: - Then enabled state of the shape ### prerender ```ts prerender(): void ``` ### setTheme ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md)`>`, 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. ## Events ### EVENT_TRANSFORMEND ```ts static EVENT_TRANSFORMEND: string = 'transform:end' ``` Fired when the transformation has ended. **Example** ```ts const gizmo = new TransformGizmo(camera, layer); gizmo.on('transform:end', () => { console.log('Transformation ended'); }); ``` ### EVENT_TRANSFORMMOVE ```ts static EVENT_TRANSFORMMOVE: string = 'transform:move' ``` Fired during the transformation. **Example** ```ts const gizmo = new TransformGizmo(camera, layer); gizmo.on('transform:move', (pointDelta, angleDelta) => { console.log(`Transformation moved by ${pointDelta} (angle: ${angleDelta})`); }); ``` ### EVENT_TRANSFORMSTART ```ts static EVENT_TRANSFORMSTART: string = 'transform:start' ``` Fired when the transformation has started. **Example** ```ts const gizmo = new TransformGizmo(camera, layer); gizmo.on('transform:start', () => { console.log('Transformation started'); }); ``` ## Inherited from [Gizmo](https://api.playcanvas.com/engine/classes/Gizmo.md) - `protected _app: AppBase` - `protected _camera: CameraComponent` - `protected _coordSpace: GizmoSpace = 'world'` - `protected _device: GraphicsDevice` - `protected _handles: EventHandle[] = []` - `protected _layer: Layer` - `protected _mouseButtons: [boolean, boolean, boolean]` - `protected _renderUpdate: boolean = false` - `protected _scale: number = 1` - `intersectShapes: Shape[] = []` - `nodes: GraphNode[] = []` - `preventDefault: boolean = true` - `root: Entity` - `get camera(): CameraComponent` · `set camera(camera: CameraComponent)` - `protected get cameraDir(): Vec3` - `get coordSpace(): GizmoSpace` · `set coordSpace(value: GizmoSpace)` - `get enabled(): boolean` · `set enabled(state: boolean)` - `protected get facingDir(): Vec3` - `get layer(): Layer` · `set layer(layer: Layer)` - `get mouseButtons(): [boolean, boolean, boolean]` - `get size(): number` · `set size(value: number)` - `protected _updatePosition(): void` - `protected _updateRotation(): void` - `protected _updateScale(): void` - `attach(nodes?: GraphNode | GraphNode[]): void` - `detach(): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `update(): void` - `static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer` - `static 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'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TranslateGizmo.md # TranslateGizmo Class · extends [`TransformGizmo`](https://api.playcanvas.com/engine/classes/TransformGizmo.md) · category: Gizmo Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/translate-gizmo.js#L61 The TranslateGizmo provides interactive 3D manipulation handles for translating/moving [Entity](https://api.playcanvas.com/engine/classes/Entity.md)s in a [Scene](https://api.playcanvas.com/engine/classes/Scene.md). 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. ```javascript // 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: - [Translate Gizmo](https://playcanvas.github.io/#/gizmos/transform-translate) - [Editor](https://playcanvas.github.io/#/misc/editor) ## Constructors ### constructor ```ts new TranslateGizmo(camera: CameraComponent, layer: Layer) ``` Creates a new TranslateGizmo object. Use [Gizmo.createLayer](https://api.playcanvas.com/engine/classes/Gizmo.md#createlayer) to create the layer required to display the gizmo. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): The layer responsible for rendering the gizmo. **Example** ```ts const gizmo = new TranslateGizmo(camera, layer); ``` ## Properties ### _shapes ```ts 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 ```ts flipPlanes: boolean = true ``` Flips the planes to face the camera. ### snapIncrement ```ts snapIncrement: number = 1 ``` ## Accessors ### axisArrowLength ```ts get axisArrowLength(): number set axisArrowLength(value: number) ``` Gets the arrow length. ### axisArrowThickness ```ts get axisArrowThickness(): number set axisArrowThickness(value: number) ``` Gets the arrow thickness. ### axisCenterSize ```ts get axisCenterSize(): number set axisCenterSize(value: number) ``` Gets the axis center size. ### axisGap ```ts get axisGap(): number set axisGap(value: number) ``` Gets the axis gap. ### axisLineLength ```ts get axisLineLength(): number set axisLineLength(value: number) ``` Gets the axis line length. ### axisLineThickness ```ts get axisLineThickness(): number set axisLineThickness(value: number) ``` Gets the axis line thickness. ### axisLineTolerance ```ts get axisLineTolerance(): number set axisLineTolerance(value: number) ``` Gets the axis line tolerance. ### axisPlaneGap ```ts get axisPlaneGap(): number set axisPlaneGap(value: number) ``` Gets the plane gap. ### axisPlaneSize ```ts get axisPlaneSize(): number set axisPlaneSize(value: number) ``` Gets the plane size. ## Methods ### _drawGuideLines ```ts _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void ``` **Parameters** - `pos` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The position. - `rot` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The rotation. - `activeAxis` ([`GizmoAxis`](https://api.playcanvas.com/engine/types/GizmoAxis.md)): The active axis. - `activeIsPlane` (`boolean`): Whether the active axis is a plane. ### _screenToPoint ```ts protected _screenToPoint(x: number, y: number): Vec3 ``` **Parameters** - `x` (`number`): The x coordinate. - `y` (`number`): The y coordinate. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The point (space is [TransformGizmo#coordSpace](https://api.playcanvas.com/engine/classes/TransformGizmo.md#coordspace)). ### prerender ```ts prerender(): void ``` ## Inherited from [TransformGizmo](https://api.playcanvas.com/engine/classes/TransformGizmo.md) - `protected _app: AppBase` - `protected _camera: CameraComponent` - `protected _coordSpace: GizmoSpace = 'world'` - `protected _device: GraphicsDevice` - `protected _handles: EventHandle[] = []` - `protected _layer: Layer` - `protected _mouseButtons: [boolean, boolean, boolean]` - `protected _renderUpdate: boolean = false` - `protected _rootStartPos: Vec3` - `protected _rootStartRot: Quat` - `protected _scale: number = 1` - `protected _selectedAxis: "" | GizmoAxis = ''` - `protected _selectedIsPlane: boolean = false` - `protected _selectionStartPoint: Vec3` - `protected _theme: GizmoTheme` - `dragMode: GizmoDragMode = 'selected'` - `intersectShapes: Shape[] = []` - `nodes: GraphNode[] = []` - `preventDefault: boolean = true` - `root: Entity` - `snap: boolean = false` - `protected get _dragging(): boolean` - `get camera(): CameraComponent` · `set camera(camera: CameraComponent)` - `protected get cameraDir(): Vec3` - `get coordSpace(): GizmoSpace` · `set coordSpace(value: GizmoSpace)` - `get enabled(): boolean` · `set enabled(state: boolean)` - `protected get facingDir(): Vec3` - `get layer(): Layer` · `set layer(layer: Layer)` - `get mouseButtons(): [boolean, boolean, boolean]` - `get size(): number` · `set size(value: number)` - `get theme(): GizmoTheme` - `protected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Plane` - `protected _createRay(mouseWPos: Vec3): Ray` - `protected _createTransform(): void` - `protected _dirFromAxis(axis: string, dir: Vec3): Vec3` - `protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void` - `protected _projectToAxis(point: Vec3, axis: string): void` - `protected _updatePosition(): void` - `protected _updateRotation(): void` - `protected _updateScale(): void` - `attach(nodes?: GraphNode | GraphNode[]): void` - `destroy(): void` - `detach(): void` - `enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `setTheme(partial: object): void` - `update(): void` - `static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer` - `static 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'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Batch.md # Batch Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch.js#L14 Holds information about batched mesh instances. Created in [BatchManager#create](https://api.playcanvas.com/engine/classes/BatchManager.md#create). ## Constructors ### constructor ```ts new Batch(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId: number) ``` Create a new Batch instance. **Parameters** - `meshInstances` ([`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): 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. ## Properties ### batchGroupId ```ts batchGroupId: number ``` Link this batch to a specific batch group. This is done automatically with default batches. ### dynamic ```ts dynamic: boolean ``` Whether this batch is dynamic (supports transforming mesh instances at runtime). ### meshInstance ```ts meshInstance: MeshInstance = null ``` A single combined mesh instance, the result of batching. ### origMeshInstances ```ts origMeshInstances: MeshInstance[] ``` An array of original mesh instances, from which this batch was generated. ## Methods ### destroy ```ts destroy(scene: Scene, layers: number[]): void ``` Removes the batch from the layers and destroys it. **Parameters** - `scene` ([`Scene`](https://api.playcanvas.com/engine/classes/Scene.md)): The scene. - `layers` (`number[]`): The layers to remove the batch from. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BatchGroup.md # BatchGroup Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch-group.js#L8 Holds mesh batching settings and a unique id. Created via [BatchManager#addGroup](https://api.playcanvas.com/engine/classes/BatchManager.md#addgroup). ## Constructors ### constructor ```ts 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](https://api.playcanvas.com/engine/classes/BatchManager.md#prepare) will split objects into local groups based on this size. - `layers` (`number[]`, optional): Layer ID array. Default is [[LAYERID_WORLD](https://api.playcanvas.com/engine/variables/LAYERID_WORLD.md)]. The whole batch group will belong to these layers. Layers of source models will be ignored. ## Properties ### dynamic ```ts dynamic: boolean ``` Whether objects within this batch group should support transforming at runtime. ### id ```ts id: number ``` Unique id. Can be assigned to model, render and element components. ### layers ```ts layers: number[] ``` Layer ID array. Default is [[LAYERID_WORLD](https://api.playcanvas.com/engine/variables/LAYERID_WORLD.md)]. The whole batch group will belong to these layers. Layers of source models will be ignored. ### maxAabbSize ```ts maxAabbSize: number ``` Maximum size of any dimension of a bounding box around batched objects. [BatchManager#prepare](https://api.playcanvas.com/engine/classes/BatchManager.md#prepare) will split objects into local groups based on this size. ### name ```ts name: string ``` Name of the group. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BatchManager.md # BatchManager Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch-manager.js#L66 Glues many mesh instances into a single one for better performance. ## Constructors ### constructor ```ts new BatchManager(device: GraphicsDevice, root: Entity, scene: Scene) ``` Create a new BatchManager instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used by the batch manager. - `root` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): The entity under which batched models are added. - `scene` ([`Scene`](https://api.playcanvas.com/engine/classes/Scene.md)): The scene that the batch manager affects. ## Methods ### addGroup ```ts 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](https://api.playcanvas.com/engine/classes/BatchManager.md#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](https://api.playcanvas.com/engine/variables/LAYERID_WORLD.md)]. The whole batch group will belong to these layers. Layers of source models will be ignored. **Returns** [`BatchGroup`](https://api.playcanvas.com/engine/classes/BatchGroup.md): Group object. ### create ```ts create(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId?: number): Batch ``` Takes a mesh instance list that has been prepared by [prepare](https://api.playcanvas.com/engine/classes/BatchManager.md#prepare), and returns a [Batch](https://api.playcanvas.com/engine/classes/Batch.md) object. This method assumes that all mesh instances provided can be rendered in a single draw call. **Parameters** - `meshInstances` ([`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): 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`](https://api.playcanvas.com/engine/classes/Batch.md): The resulting batch object. ### generate ```ts 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 ```ts getGroupById(id: number): BatchGroup | null ``` Retrieves a [BatchGroup](https://api.playcanvas.com/engine/classes/BatchGroup.md) object with a corresponding id, if it exists, or null otherwise. **Parameters** - `id` (`number`): The batch group id. **Returns** [`BatchGroup`](https://api.playcanvas.com/engine/classes/BatchGroup.md) `| null`: The batch group matching the id or null if not found. ### getGroupByName ```ts getGroupByName(name: string): BatchGroup | null ``` Retrieves a [BatchGroup](https://api.playcanvas.com/engine/classes/BatchGroup.md) object with a corresponding name, if it exists, or null otherwise. **Parameters** - `name` (`string`): Name. **Returns** [`BatchGroup`](https://api.playcanvas.com/engine/classes/BatchGroup.md) `| null`: The batch group matching the name or null if not found. ### markGroupDirty ```ts 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 ```ts 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: - Mesh instances use different materials. - Mesh instances have different parameters (e.g. lightmaps or static lights). - Mesh instances have different shader defines (shadow receiving, being aligned to screen space, etc). - Too many vertices for a single batch (65535 is maximum). - Too many instances for a single batch (hardware-dependent, expect 128 on low-end and 1024 on high-end). - Bounding box of a batch is larger than maxAabbSize in any dimension. - Mesh instances differ in shadow casting ([MeshInstance#castShadow](https://api.playcanvas.com/engine/classes/MeshInstance.md#castshadow)) or directional shadow cascade mask ([MeshInstance#shadowCascadeMask](https://api.playcanvas.com/engine/classes/MeshInstance.md#shadowcascademask)). **Parameters** - `meshInstances` ([`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): Input list of mesh instances - `dynamic` (`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`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[][]`: An array of arrays of mesh instances, each valid to pass to [create](https://api.playcanvas.com/engine/classes/BatchManager.md#create). ### removeGroup ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindBaseFormat.md # BindBaseFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L21 A base class to describe the format of the resource for [BindGroupFormat](https://api.playcanvas.com/engine/classes/BindGroupFormat.md). ## Constructors ### constructor ```ts 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: - [SHADERSTAGE_VERTEX](https://api.playcanvas.com/engine/variables/SHADERSTAGE_VERTEX.md) - [SHADERSTAGE_FRAGMENT](https://api.playcanvas.com/engine/variables/SHADERSTAGE_FRAGMENT.md) - [SHADERSTAGE_COMPUTE](https://api.playcanvas.com/engine/variables/SHADERSTAGE_COMPUTE.md) ## Properties ### name ```ts name: string ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindGroupFormat.md # BindGroupFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L299 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](https://api.playcanvas.com/engine/variables/SHADERLANGUAGE_WGSL.md) language. Call [BindGroupFormat#destroy](https://api.playcanvas.com/engine/classes/BindGroupFormat.md#destroy) when no longer needed. On WebGPU, the graphics device retains bind group formats for device recovery until they are explicitly destroyed. ## Constructors ### constructor ```ts new BindGroupFormat(graphicsDevice: GraphicsDevice, formats: (BindTextureFormat | BindStorageTextureFormat | BindUniformBufferFormat | BindStorageBufferFormat)[]) ``` Create a new instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to manage this vertex format. - `formats` (`(`[`BindTextureFormat`](https://api.playcanvas.com/engine/classes/BindTextureFormat.md) `|` [`BindStorageTextureFormat`](https://api.playcanvas.com/engine/classes/BindStorageTextureFormat.md) `|` [`BindUniformBufferFormat`](https://api.playcanvas.com/engine/classes/BindUniformBufferFormat.md) `|` [`BindStorageBufferFormat`](https://api.playcanvas.com/engine/classes/BindStorageBufferFormat.md)`)[]`): 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. ## Properties ### bufferFormatsMap ```ts bufferFormatsMap: Map ``` ### device ```ts device: GraphicsDevice ``` ### storageBufferFormatsMap ```ts storageBufferFormatsMap: Map ``` ### storageTextureFormatsMap ```ts storageTextureFormatsMap: Map ``` ### textureFormatsMap ```ts textureFormatsMap: Map ``` ## Methods ### destroy ```ts destroy(): void ``` Frees resources associated with this bind group. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindStorageBufferFormat.md # BindStorageBufferFormat Class · extends [`BindBaseFormat`](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L81 A class to describe the format of the storage buffer for [BindGroupFormat](https://api.playcanvas.com/engine/classes/BindGroupFormat.md). ## Constructors ### constructor ```ts 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: - [SHADERSTAGE_VERTEX](https://api.playcanvas.com/engine/variables/SHADERSTAGE_VERTEX.md) - [SHADERSTAGE_FRAGMENT](https://api.playcanvas.com/engine/variables/SHADERSTAGE_FRAGMENT.md) - [SHADERSTAGE_COMPUTE](https://api.playcanvas.com/engine/variables/SHADERSTAGE_COMPUTE.md) - `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. ## Inherited from [BindBaseFormat](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) - `name: string` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindStorageTextureFormat.md # BindStorageTextureFormat Class · extends [`BindBaseFormat`](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L243 A class to describe the format of the storage texture for [BindGroupFormat](https://api.playcanvas.com/engine/classes/BindGroupFormat.md). 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. ## Constructors ### constructor ```ts 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md). - `textureDimension` (`string`, optional, default `TEXTUREDIMENSION_2D`): The dimension of the texture. Defaults to [TEXTUREDIMENSION_2D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md). Can be: - [TEXTUREDIMENSION_1D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_1D.md) - [TEXTUREDIMENSION_2D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md) - [TEXTUREDIMENSION_2D_ARRAY](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D_ARRAY.md) - [TEXTUREDIMENSION_3D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_3D.md) - `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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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. ## Inherited from [BindBaseFormat](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) - `name: string` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindTextureFormat.md # BindTextureFormat Class · extends [`BindBaseFormat`](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L122 A class to describe the format of the texture for [BindGroupFormat](https://api.playcanvas.com/engine/classes/BindGroupFormat.md). ## Constructors ### constructor ```ts 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: - [SHADERSTAGE_VERTEX](https://api.playcanvas.com/engine/variables/SHADERSTAGE_VERTEX.md) - [SHADERSTAGE_FRAGMENT](https://api.playcanvas.com/engine/variables/SHADERSTAGE_FRAGMENT.md) - [SHADERSTAGE_COMPUTE](https://api.playcanvas.com/engine/variables/SHADERSTAGE_COMPUTE.md) - `textureDimension` (`string`, optional, default `TEXTUREDIMENSION_2D`): The dimension of the texture. Defaults to [TEXTUREDIMENSION_2D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md). Can be: - [TEXTUREDIMENSION_1D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_1D.md) - [TEXTUREDIMENSION_2D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md) - [TEXTUREDIMENSION_2D_ARRAY](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D_ARRAY.md) - [TEXTUREDIMENSION_CUBE](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_CUBE.md) - [TEXTUREDIMENSION_CUBE_ARRAY](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_CUBE_ARRAY.md) - [TEXTUREDIMENSION_3D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_3D.md) When `multisampled` is true, must be [TEXTUREDIMENSION_2D](https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md). - `sampleType` (`number`, optional, default `SAMPLETYPE_FLOAT`): The type of the texture samples. Defaults to [SAMPLETYPE_FLOAT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_FLOAT.md). Can be: - [SAMPLETYPE_FLOAT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_FLOAT.md) - [SAMPLETYPE_UNFILTERABLE_FLOAT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_UNFILTERABLE_FLOAT.md) - [SAMPLETYPE_DEPTH](https://api.playcanvas.com/engine/variables/SAMPLETYPE_DEPTH.md) - [SAMPLETYPE_INT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_INT.md) - [SAMPLETYPE_UINT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_UINT.md) When `multisampled` is true, [SAMPLETYPE_FLOAT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_FLOAT.md) is coerced to [SAMPLETYPE_UNFILTERABLE_FLOAT](https://api.playcanvas.com/engine/variables/SAMPLETYPE_UNFILTERABLE_FLOAT.md) (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. ## Properties ### hasSampler ```ts hasSampler: boolean ``` Whether a sampler binding follows this texture. Always false when `multisampled` is true. ### multisampled ```ts multisampled: boolean ``` Whether this is a multisampled (`texture_multisampled_*`) binding. ### samplerName ```ts samplerName: string | null = null ``` Sampler uniform name. `null` when `multisampled` is true; otherwise the provided name or `${name}_sampler`. ## Inherited from [BindBaseFormat](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) - `name: string` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BindUniformBufferFormat.md # BindUniformBufferFormat Class · extends [`BindBaseFormat`](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L69 A class to describe the format of the uniform buffer for [BindGroupFormat](https://api.playcanvas.com/engine/classes/BindGroupFormat.md). ## Inherited from [BindBaseFormat](https://api.playcanvas.com/engine/classes/BindBaseFormat.md) - `new BindUniformBufferFormat(name: string, visibility: number)` ## Inherited from [BindTextureFormat](https://api.playcanvas.com/engine/classes/BindTextureFormat.md) - `name: string` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BlendState.md # BlendState Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/blend-state.js#L69 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](https://api.playcanvas.com/engine/classes/Material.md#blendstate), or in some cases on the graphics device using [GraphicsDevice#setBlendState](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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](https://api.playcanvas.com/engine/classes/BlendState.md#setattachment). This requires [GraphicsDevice#supportsIndependentBlending](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsindependentblending) - on devices without support, the state of the attachment 0 is used for all attachments. ## Constructors ### constructor ```ts 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: - [BLENDMODE_ZERO](https://api.playcanvas.com/engine/variables/BLENDMODE_ZERO.md) - [BLENDMODE_ONE](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE.md) - [BLENDMODE_SRC_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_COLOR.md) - [BLENDMODE_ONE_MINUS_SRC_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC_COLOR.md) - [BLENDMODE_DST_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_DST_COLOR.md) - [BLENDMODE_ONE_MINUS_DST_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_DST_COLOR.md) - [BLENDMODE_SRC_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_ALPHA.md) - [BLENDMODE_SRC_ALPHA_SATURATE](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_ALPHA_SATURATE.md) - [BLENDMODE_ONE_MINUS_SRC_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC_ALPHA.md) - [BLENDMODE_DST_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_DST_ALPHA.md) - [BLENDMODE_ONE_MINUS_DST_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_DST_ALPHA.md) - [BLENDMODE_CONSTANT](https://api.playcanvas.com/engine/variables/BLENDMODE_CONSTANT.md) - [BLENDMODE_ONE_MINUS_CONSTANT](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_CONSTANT.md) - [BLENDMODE_SRC1_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC1_COLOR.md) - [BLENDMODE_ONE_MINUS_SRC1_COLOR](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC1_COLOR.md) - [BLENDMODE_SRC1_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC1_ALPHA.md) - [BLENDMODE_ONE_MINUS_SRC1_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC1_ALPHA.md) All op parameters can take the following values: - [BLENDEQUATION_ADD](https://api.playcanvas.com/engine/variables/BLENDEQUATION_ADD.md) - [BLENDEQUATION_SUBTRACT](https://api.playcanvas.com/engine/variables/BLENDEQUATION_SUBTRACT.md) - [BLENDEQUATION_REVERSE_SUBTRACT](https://api.playcanvas.com/engine/variables/BLENDEQUATION_REVERSE_SUBTRACT.md) - [BLENDEQUATION_MIN](https://api.playcanvas.com/engine/variables/BLENDEQUATION_MIN.md) - [BLENDEQUATION_MAX](https://api.playcanvas.com/engine/variables/BLENDEQUATION_MAX.md) **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](https://api.playcanvas.com/engine/variables/BLENDEQUATION_ADD.md). - `colorSrcFactor` (`number`, optional, default `BLENDMODE_ONE`): Configures source color blending factor. Defaults to [BLENDMODE_ONE](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE.md). - `colorDstFactor` (`number`, optional, default `BLENDMODE_ZERO`): Configures destination color blending factor. Defaults to [BLENDMODE_ZERO](https://api.playcanvas.com/engine/variables/BLENDMODE_ZERO.md). - `alphaOp` (`number`, optional): Configures alpha blending operation. Defaults to [BLENDEQUATION_ADD](https://api.playcanvas.com/engine/variables/BLENDEQUATION_ADD.md). - `alphaSrcFactor` (`number`, optional): Configures source alpha blending factor. Defaults to [BLENDMODE_ONE](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE.md). - `alphaDstFactor` (`number`, optional): Configures destination alpha blending factor. Defaults to [BLENDMODE_ZERO](https://api.playcanvas.com/engine/variables/BLENDMODE_ZERO.md). - `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. ## Properties ### ADDBLEND ```ts static readonly ADDBLEND: BlendState ``` A blend state that does simple additive blending. ### ALPHABLEND ```ts static readonly ALPHABLEND: BlendState ``` A blend state that does simple translucency using alpha channel. ### NOBLEND ```ts static readonly NOBLEND: BlendState ``` A blend state that has blending disabled and writes to all color channels. ### NOWRITE ```ts static readonly NOWRITE: BlendState ``` A blend state that does not write to color channels. ## Accessors ### blend ```ts get blend(): boolean set blend(value: boolean) ``` Gets whether blending is enabled. ### hasAttachmentOverrides ```ts get hasAttachmentOverrides(): boolean ``` Gets whether any color attachment has been given an independent blend state using [BlendState#setAttachment](https://api.playcanvas.com/engine/classes/BlendState.md#setattachment). ## Methods ### clearAttachment ```ts 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 ```ts clone(): BlendState ``` Returns an identical copy of the specified blend state. **Returns** [`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md): The result of the cloning. ### copy ```ts copy(rhs: BlendState): BlendState ``` Copies the contents of a source blend state to this blend state. **Parameters** - `rhs` ([`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md)): A blend state to copy from. **Returns** [`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md): Self for chaining. ### equals ```ts equals(rhs: BlendState): boolean ``` Reports whether two BlendStates are equal. **Parameters** - `rhs` ([`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md)): The blend state to compare to. **Returns** `boolean`: True if the blend states are equal and false otherwise. ### getAttachment ```ts 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`](https://api.playcanvas.com/engine/classes/BlendState.md)): The blend state to store the result in. This avoids allocations, as a single instance can be reused. **Returns** [`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md): The supplied dst, for chaining. ### setAttachment ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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`](https://api.playcanvas.com/engine/classes/BlendState.md) `| null`): The blend state to copy from, or null to make the attachment follow attachment 0 again. **Example** ```ts // 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); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BoxGeometry.md # BoxGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/box-geometry.js#L37 A procedural box-shaped geometry. Typically, you would: 1. Create a BoxGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), 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** ```ts const geometry = new BoxGeometry({ halfExtents: new Vec3(1, 1, 1), widthSegments: 2, lengthSegments: 2, heightSegments: 2 }); ``` ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CameraComponent.md # CameraComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/component.js#L78 The CameraComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#camera) property: ```javascript 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: - [First Person Camera](https://playcanvas.github.io/#/camera/first-person) - [Fly Camera](https://playcanvas.github.io/#/camera/fly) - [Multiple Cameras](https://playcanvas.github.io/#/camera/multi) - [Orbit Camera](https://playcanvas.github.io/#/camera/orbit) ## Accessors ### aperture ```ts get aperture(): number set aperture(value: number) ``` Gets the camera aperture in f-stops. ### aspectRatio ```ts get aspectRatio(): number set aspectRatio(value: number) ``` Gets the aspect ratio (width divided by height) of the camera. ### aspectRatioMode ```ts get aspectRatioMode(): number set aspectRatioMode(value: number) ``` Gets the aspect ratio mode of the camera. ### calculateProjection ```ts get calculateProjection(): CalculateMatrixCallback set calculateProjection(value: CalculateMatrixCallback) ``` Gets the custom function to calculate the camera projection matrix manually. ### calculateTransform ```ts get calculateTransform(): CalculateMatrixCallback set calculateTransform(value: CalculateMatrixCallback) ``` Gets the custom function to calculate the camera transformation matrix manually. ### clearColor ```ts get clearColor(): Color set clearColor(value: Color) ``` Gets the camera component's clear color. ### clearColorBuffer ```ts get clearColorBuffer(): boolean set clearColorBuffer(value: boolean) ``` Gets whether the camera will automatically clear the color buffer before rendering. ### clearDepth ```ts get clearDepth(): number set clearDepth(value: number) ``` Gets the depth value to clear the depth buffer to. ### clearDepthBuffer ```ts get clearDepthBuffer(): boolean set clearDepthBuffer(value: boolean) ``` Gets whether the camera will automatically clear the depth buffer before rendering. ### clearStencilBuffer ```ts get clearStencilBuffer(): boolean set clearStencilBuffer(value: boolean) ``` Gets whether the camera will automatically clear the stencil buffer before rendering. ### cullFaces ```ts get cullFaces(): boolean set cullFaces(value: boolean) ``` Gets whether the camera will cull triangle faces. ### disablePostEffectsLayer ```ts 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. ### farClip ```ts get farClip(): number set farClip(value: number) ``` Gets the distance from the camera after which no rendering will take place. ### flipFaces ```ts get flipFaces(): boolean set flipFaces(value: boolean) ``` Gets whether the camera will flip the face direction of triangles. ### fog ```ts get fog(): FogParams | null set fog(value: FogParams | null) ``` Gets a [FogParams](https://api.playcanvas.com/engine/classes/FogParams.md) that defines fog parameters, or null if those are not set. ### fov ```ts get fov(): number set fov(value: number) ``` Gets the field of view of the camera in degrees. ### frustum ```ts get frustum(): Frustum ``` Gets the camera's frustum shape. ### frustumCulling ```ts get frustumCulling(): boolean set frustumCulling(value: boolean) ``` Gets whether frustum culling is enabled. ### gammaCorrection ```ts get gammaCorrection(): number set gammaCorrection(value: number) ``` Gets the gamma correction used when rendering the scene. ### horizontalFov ```ts get horizontalFov(): boolean set horizontalFov(value: boolean) ``` Gets whether the camera's field of view ([fov](https://api.playcanvas.com/engine/classes/CameraComponent.md#fov)) is horizontal or vertical. ### jitter ```ts get jitter(): number set jitter(value: number) ``` Gets the jitter intensity applied in the projection matrix. ### layers ```ts get layers(): readonly number[] set layers(newValue: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this camera belongs. ### nearClip ```ts get nearClip(): number set nearClip(value: number) ``` Gets the distance from the camera before which no rendering will take place. ### orthoHeight ```ts get orthoHeight(): number set orthoHeight(value: number) ``` Gets the half-height of the orthographic view window (in the Y-axis). ### postEffects ```ts get postEffects(): PostEffectQueue ``` Gets the post effects queue for this camera. Use this to add or remove post effects from the camera. ### priority ```ts get priority(): number set priority(newValue: number) ``` Gets the priority to control the render order of this camera. ### projection ```ts get projection(): number set projection(value: number) ``` Gets the type of projection used to render the camera. ### projectionMatrix ```ts get projectionMatrix(): Mat4 ``` Gets the camera's projection matrix. ### projectionOffset ```ts get projectionOffset(): Vec2 set projectionOffset(value: Vec2) ``` Gets the offset of the projection window. ### rect ```ts get rect(): Readonly set rect(value: Readonly) ``` Gets the rendering rectangle for the camera. ### renderTarget ```ts get renderTarget(): RenderTarget set renderTarget(value: RenderTarget) ``` Gets the render target to which rendering of the camera is performed. ### scissorRect ```ts get scissorRect(): Vec4 set scissorRect(value: Vec4) ``` Gets the scissor rectangle for the camera. ### sensitivity ```ts get sensitivity(): number set sensitivity(value: number) ``` Gets the camera sensitivity in ISO. ### shutter ```ts get shutter(): number set shutter(value: number) ``` Gets the camera shutter speed in seconds. ### toneMapping ```ts get toneMapping(): number set toneMapping(value: number) ``` Gets the tonemapping transform applied to the rendered color buffer. ### viewMatrix ```ts get viewMatrix(): Mat4 ``` Gets the camera's view matrix. ## Methods ### calculateAspectRatio ```ts 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#rendertarget) is used, and if that is also null, the backbuffer is used. The camera's [CameraComponent#rect](https://api.playcanvas.com/engine/classes/CameraComponent.md#rect) viewport is taken into account. **Parameters** - `rt` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md) `| 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 ```ts endXr(callback?: XrErrorCallback): void ``` Attempt to end XR session of this camera. **Parameters** - `callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), optional): Optional callback function called once session is ended. The callback has one argument Error - it is null if successfully ended XR session. **Example** ```ts // On an entity with a camera component this.entity.camera.endXr((err) => { // not anymore in XR }); ``` ### getClearColor ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md): The clear color of the attachment. ### getShaderPass ```ts getShaderPass(): string | undefined ``` Shader pass name. **Returns** `string | undefined`: The name of the shader pass, or undefined if no shader pass is set. ### requestSceneColorMap ```ts 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 ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): 3D vector to receive world coordinate result. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space coordinate. **Example** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/RenderTarget.md) with multiple color buffers to clear to different colors. The attachment 0 clears to [CameraComponent#clearColor](https://api.playcanvas.com/engine/classes/CameraComponent.md#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`](https://api.playcanvas.com/engine/classes/Color.md) `| null`): The clear color, specified in sRGB space, or null to clear to the color of the attachment 0. **Example** ```ts // 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 ```ts 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. ```javascript 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](https://api.playcanvas.com/engine/variables/SHADERPASS_FORWARD.md). Can be: - [SHADERPASS_FORWARD](https://api.playcanvas.com/engine/variables/SHADERPASS_FORWARD.md) - [SHADERPASS_ALBEDO](https://api.playcanvas.com/engine/variables/SHADERPASS_ALBEDO.md) - [SHADERPASS_OPACITY](https://api.playcanvas.com/engine/variables/SHADERPASS_OPACITY.md) - [SHADERPASS_WORLDNORMAL](https://api.playcanvas.com/engine/variables/SHADERPASS_WORLDNORMAL.md) - [SHADERPASS_SPECULARITY](https://api.playcanvas.com/engine/variables/SHADERPASS_SPECULARITY.md) - [SHADERPASS_GLOSS](https://api.playcanvas.com/engine/variables/SHADERPASS_GLOSS.md) - [SHADERPASS_METALNESS](https://api.playcanvas.com/engine/variables/SHADERPASS_METALNESS.md) - [SHADERPASS_AO](https://api.playcanvas.com/engine/variables/SHADERPASS_AO.md) - [SHADERPASS_EMISSION](https://api.playcanvas.com/engine/variables/SHADERPASS_EMISSION.md) - [SHADERPASS_LIGHTING](https://api.playcanvas.com/engine/variables/SHADERPASS_LIGHTING.md) - [SHADERPASS_UV0](https://api.playcanvas.com/engine/variables/SHADERPASS_UV0.md) The returned index can be used with [MeshInstance#shaderPassMask](https://api.playcanvas.com/engine/classes/MeshInstance.md#shaderpassmask) to control which mesh instances are rendered in this pass. **Returns** `number`: The id of the shader pass. ### startXr ```ts 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: - [XRTYPE_INLINE](https://api.playcanvas.com/engine/variables/XRTYPE_INLINE.md): Inline - always available type of session. It has limited feature availability and is rendered into HTML element. - [XRTYPE_VR](https://api.playcanvas.com/engine/variables/XRTYPE_VR.md): Immersive VR - session that provides exclusive access to the VR device with the best available tracking features. - [XRTYPE_AR](https://api.playcanvas.com/engine/variables/XRTYPE_AR.md): Immersive AR - session that provides exclusive access to the VR/AR device that is intended to be blended with the real-world environment. - `spaceType` (`string`): Reference space type. Can be one of the following: - [XRSPACE_VIEWER](https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md): Viewer - always supported space with some basic tracking capabilities. - [XRSPACE_LOCAL](https://api.playcanvas.com/engine/variables/XRSPACE_LOCAL.md): Local - represents a tracking space with a native origin near the viewer at the time of creation. It is meant for seated or basic local XR sessions. - [XRSPACE_LOCALFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_LOCALFLOOR.md): 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. Floor level value might be estimated by the underlying platform. It is meant for seated or basic local XR sessions. - [XRSPACE_BOUNDEDFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_BOUNDEDFLOOR.md): 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. - [XRSPACE_UNBOUNDED](https://api.playcanvas.com/engine/variables/XRSPACE_UNBOUNDED.md): Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially long distances from their starting point. - `options` (`object`, optional): Object with options for XR session initialization. - `options.anchors` (`boolean`, optional): Optional boolean to attempt to enable [XrAnchors](https://api.playcanvas.com/engine/classes/XrAnchors.md). - `options.callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), 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](https://api.playcanvas.com/engine/classes/XrImageTracking.md). - `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](https://api.playcanvas.com/engine/classes/XrPlaneDetection.md). **Example** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#viewmatrix) and discard it when the resulting `z` is zero or greater. **Parameters** - `worldCoord` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space coordinate. - `screenCoord` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): 3D vector to receive screen coordinate result. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The screen space coordinate. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CameraComponentSystem.md # CameraComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/system.js#L77 Used to add and remove [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md)s from Entities. It also holds an array of all active cameras. ## Properties ### cameras ```ts cameras: CameraComponent[] = [] ``` Holds all the active camera components. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CameraFrame.md # CameraFrame Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L300 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](https://api.playcanvas.com/engine/classes/ShaderChunks.md) map before creating the `CameraFrame`. Those chunks will be picked up by the compose pass and preserved. Example (GLSL): **Example** ```ts // 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. ``` ## Constructors ### constructor ```ts new CameraFrame(app: AppBase, cameraComponent: CameraComponent) ``` Creates a new CameraFrame instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. - `cameraComponent` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. ## Properties ### bloom ```ts bloom: Bloom ``` Bloom settings. ### colorEnhance ```ts colorEnhance: ColorEnhance ``` Color enhancement settings. ### colorLUT ```ts colorLUT: ColorLUT ``` Color LUT settings. ### debug ```ts 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 ```ts dof: Dof ``` DoF settings. ### fringing ```ts fringing: Fringing ``` Fringing settings. ### grading ```ts grading: Grading ``` Grading settings. ### rendering ```ts rendering: Rendering ``` Rendering settings. ### ssao ```ts ssao: Ssao ``` SSAO settings. ### taa ```ts taa: Taa ``` Taa settings. ### vignette ```ts vignette: Vignette ``` Vignette settings. ### volumetricFog ```ts volumetricFog: VolumetricFog ``` Volumetric fog settings. ## Accessors ### enabled ```ts get enabled(): boolean set enabled(value: boolean) ``` Gets the enabled state of the camera frame. ## Methods ### createRenderPass ```ts 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 ```ts destroy(): void ``` Destroys the camera frame, removing all render passes. ### update ```ts update(): void ``` Applies any changes made to the properties of this instance. ### isSplatSceneDepthSupported ```ts 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](https://api.playcanvas.com/engine/classes/GSplatParams.md#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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. **Returns** `boolean`: True if the splats can contribute to the scene depth. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CapsuleGeometry.md # CapsuleGeometry Class · extends [`ConeBaseGeometry`](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/capsule-geometry.js#L33 A procedural capsule-shaped geometry. Typically, you would: 1. Create a CapsuleGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new CapsuleGeometry({ radius: 1, height: 2, heightSegments: 2, sides: 20 }); ``` ## Inherited from [ConeBaseGeometry](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CircleGeometry.md # CircleGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/circle-geometry.js#L33 A procedural circle-shaped geometry - a flat disc in the XZ plane. Typically, you would: 1. Create a CircleGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new CircleGeometry({ radius: 100, sectors: 128, rings: 64, ringExponent: 2 }); ``` ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Compute.md # Compute Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/compute.js#L34 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](https://api.playcanvas.com/engine/classes/Compute.md#destroy) when no longer needed. The graphics device retains compute instances for device recovery until they are explicitly destroyed. ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `shader` ([`Shader`](https://api.playcanvas.com/engine/classes/Shader.md)): The compute shader. - `name` (`string`, optional, default `'Unnamed'`): The name of the compute instance, used for debugging only. ## Properties ### name ```ts name: string ``` The non-unique name of an instance of the class. Defaults to 'Unnamed'. ## Methods ### deleteParameter ```ts deleteParameter(name: string): void ``` Deletes a shader parameter from the compute instance. **Parameters** - `name` (`string`): The name of the parameter to delete. ### destroy ```ts destroy(): void ``` Frees resources associated with this compute instance. ### getParameter ```ts getParameter(name: string): number | number[] | Float32Array | 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 |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md) `|` [`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md) `|` [`IndexBuffer`](https://api.playcanvas.com/engine/classes/IndexBuffer.md) `|` [`TextureView`](https://api.playcanvas.com/engine/classes/TextureView.md) `| undefined`: The value of the specified parameter. ### setParameter ```ts setParameter(name: string, value: number | number[] | Float32Array | 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 |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md) `|` [`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md) `|` [`IndexBuffer`](https://api.playcanvas.com/engine/classes/IndexBuffer.md) `|` [`TextureView`](https://api.playcanvas.com/engine/classes/TextureView.md)): The value for the specified parameter. ### setupDispatch ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#getindirectdispatchslot). - `buffer` ([`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md) `| null`, optional, default `null`): Optional custom storage buffer containing dispatch parameters. If not provided, uses the device's built-in [GraphicsDevice#indirectDispatchBuffer](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#indirectdispatchbuffer). When providing a custom buffer, the user is responsible for its lifetime and contents. **Example** ```ts // 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]); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md # ConeBaseGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cone-base-geometry.js#L13 Shared superclass of [CapsuleGeometry](https://api.playcanvas.com/engine/classes/CapsuleGeometry.md), [ConeGeometry](https://api.playcanvas.com/engine/classes/ConeGeometry.md) and [CylinderGeometry](https://api.playcanvas.com/engine/classes/CylinderGeometry.md). Use those classes instead of this one. ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ConeGeometry.md # ConeGeometry Class · extends [`ConeBaseGeometry`](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cone-geometry.js#L33 A procedural cone-shaped geometry. Typically, you would: 1. Create a ConeGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new ConeGeometry({ baseRadius: 1, height: 2, heightSegments: 2, capSegments: 20 }); ``` ## Inherited from [ConeBaseGeometry](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ContainerResource.md # ContainerResource Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/container.js#L18 Container for a list of animations, textures, materials, renders, gsplats and a model. ## Properties ### animations ```ts animations: Asset<"animation">[] = [] ``` An array of the animation assets. Each resource is an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md). ### gsplats ```ts gsplats: Asset<"gsplat">[] = [] ``` An array of the gsplat assets, created for meshes using the KHR_gaussian_splatting glTF extension. ### materials ```ts materials: Asset<"material">[] = [] ``` An array of the [Material](https://api.playcanvas.com/engine/classes/Material.md) and/or [StandardMaterial](https://api.playcanvas.com/engine/classes/StandardMaterial.md) assets. ### renders ```ts renders: Asset<"render">[] = [] ``` An array of the render assets. Each holds the meshes of one glTF mesh. ### textures ```ts textures: Asset<"texture">[] = [] ``` An array of the [Texture](https://api.playcanvas.com/engine/classes/Texture.md) assets. ## Methods ### applyMaterialVariant ```ts applyMaterialVariant(entity: Entity, name?: string): void ``` Applies a material variant to an entity hierarchy. **Parameters** - `entity` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): 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** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): 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** ```ts // 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 ```ts getMaterialVariants(): string[] ``` Queries the list of available material variants. **Returns** `string[]`: An array of variant names. ### instantiateModelEntity ```ts instantiateModelEntity(options?: any): Entity ``` Instantiates an entity with a model component. **Parameters** - `options` (`any`, optional): The initialization data for the model component type [ModelComponent](https://api.playcanvas.com/engine/classes/ModelComponent.md). **Returns** [`Entity`](https://api.playcanvas.com/engine/classes/Entity.md): A single entity with a model component. Model component internally contains a hierarchy based on [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md). **Example** ```ts // 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 ```ts instantiateRenderEntity(options?: any): Entity ``` Instantiates an entity with a render component. **Parameters** - `options` (`any`, optional): The initialization data for the render component type [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md). **Returns** [`Entity`](https://api.playcanvas.com/engine/classes/Entity.md): A hierarchy of entities with render components on entities containing renderable geometry. **Example** ```ts // 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(); }); }); }); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CylinderGeometry.md # CylinderGeometry Class · extends [`ConeBaseGeometry`](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cylinder-geometry.js#L33 A procedural cylinder-shaped geometry. Typically, you would: 1. Create a CylinderGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new CylinderGeometry({ radius: 1, height: 2, heightSegments: 2, capSegments: 10 }); ``` ## Inherited from [ConeBaseGeometry](https://api.playcanvas.com/engine/classes/ConeBaseGeometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/DepthState.md # DepthState Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/depth-state.js#L26 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](https://api.playcanvas.com/engine/classes/Material.md#depthstate), or in some cases on the graphics device using [GraphicsDevice#setDepthState](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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. ## Constructors ### constructor ```ts 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](https://api.playcanvas.com/engine/classes/DepthState.md#func) for details. Defaults to [FUNC_LESSEQUAL](https://api.playcanvas.com/engine/variables/FUNC_LESSEQUAL.md). - `write` (`boolean`, optional, default `true`): If true, depth values are written to the depth buffer of the currently active render target. Defaults to true. ## Properties ### key ```ts 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. ### DEFAULT ```ts static readonly DEFAULT: DepthState ``` A default depth state that has the depth testing function set to [FUNC_LESSEQUAL](https://api.playcanvas.com/engine/variables/FUNC_LESSEQUAL.md) and depth writes enabled. ### NODEPTH ```ts static readonly NODEPTH: DepthState ``` A depth state that always passes the fragment but does not write depth to the depth buffer. ### WRITEDEPTH ```ts static readonly WRITEDEPTH: DepthState ``` A depth state that always passes the fragment and writes depth to the depth buffer. ## Accessors ### depthBias ```ts get depthBias(): number set depthBias(value: number) ``` Gets the constant depth bias added to each fragment's depth. ### depthBiasSlope ```ts get depthBiasSlope(): number set depthBiasSlope(value: number) ``` Gets the depth bias that scales with the fragment's slope. ### func ```ts get func(): number set func(value: number) ``` Gets the depth testing function. ### test ```ts get test(): boolean set test(value: boolean) ``` Gets whether depth testing is performed. ### write ```ts get write(): boolean set write(value: boolean) ``` Gets whether depth writing is performed. ## Methods ### clone ```ts clone(): DepthState ``` Returns an identical copy of the specified depth state. **Returns** [`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md): The result of the cloning. ### copy ```ts copy(rhs: DepthState): DepthState ``` Copies the contents of a source depth state to this depth state. **Parameters** - `rhs` ([`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md)): A depth state to copy from. **Returns** [`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md): Self for chaining. ### equals ```ts equals(rhs: DepthState): boolean ``` Reports whether two DepthStates are equal. **Parameters** - `rhs` ([`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md)): The depth state to compare to. **Returns** `boolean`: True if the depth states are equal and false otherwise. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/DomeGeometry.md # DomeGeometry Class · extends [`SphereGeometry`](https://api.playcanvas.com/engine/classes/SphereGeometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/dome-geometry.js#L33 A procedural dome-shaped geometry. Typically, you would: 1. Create a DomeGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new DomeGeometry({ latitudeBands: 32, longitudeBands: 32 }); ``` ## Inherited from [SphereGeometry](https://api.playcanvas.com/engine/classes/SphereGeometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/DrawCommands.md # DrawCommands Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/draw-commands.js#L11 Container holding parameters for multi-draw commands. Obtain an instance via [MeshInstance#setMultiDraw](https://api.playcanvas.com/engine/classes/MeshInstance.md#setmultidraw) and populate it using [add](https://api.playcanvas.com/engine/classes/DrawCommands.md#add) followed by [update](https://api.playcanvas.com/engine/classes/DrawCommands.md#update). ## Accessors ### count ```ts get count(): number ``` Number of draw calls to perform. ### maxCount ```ts get maxCount(): number ``` Maximum number of multi-draw calls the space is allocated for. ## Methods ### add ```ts 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 ```ts update(count: number): void ``` Finalize and set draw count after all commands have been added. **Parameters** - `count` (`number`): Number of draws to execute. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/FogParams.md # FogParams Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/fog-params.js#L9 Fog parameters. ## Properties ### color ```ts color: Color ``` The color of the fog (if enabled), specified in sRGB color space. Defaults to black (0, 0, 0). ### density ```ts density: number = 0 ``` The density of the fog (if enabled). This property is only valid if the fog property is set to [FOG_EXP](https://api.playcanvas.com/engine/variables/FOG_EXP.md) or [FOG_EXP2](https://api.playcanvas.com/engine/variables/FOG_EXP2.md). Defaults to 0. ### end ```ts 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](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md). Defaults to 1000. ### start ```ts 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](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md). Defaults to 1. ### type ```ts type: string = FOG_NONE ``` The type of fog used by the scene. Can be: - [FOG_NONE](https://api.playcanvas.com/engine/variables/FOG_NONE.md) - [FOG_LINEAR](https://api.playcanvas.com/engine/variables/FOG_LINEAR.md) - [FOG_EXP](https://api.playcanvas.com/engine/variables/FOG_EXP.md) - [FOG_EXP2](https://api.playcanvas.com/engine/variables/FOG_EXP2.md) Defaults to [FOG_NONE](https://api.playcanvas.com/engine/variables/FOG_NONE.md). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Geometry.md # Geometry Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry.js#L10 The Geometry class serves as a container for storing geometric information. It encapsulates data such as positions, normals, colors, and indices. ## Properties ### blendIndices ```ts blendIndices: ArrayLike | undefined ``` Blend indices. ### blendWeights ```ts blendWeights: ArrayLike | undefined ``` Blend weights. ### colors ```ts colors: ArrayLike | undefined ``` Colors. ### indices ```ts indices: number[] | Uint8Array | Uint16Array | Uint32Array | undefined ``` Indices. ### normals ```ts normals: ArrayLike | undefined ``` Normals. ### positions ```ts positions: ArrayLike | undefined ``` Positions. ### tangents ```ts tangents: ArrayLike | undefined ``` Tangents. ### uvs ```ts uvs: ArrayLike | undefined ``` UVs. ### uvs1 ```ts uvs1: ArrayLike | undefined ``` Additional Uvs. ## Methods ### calculateNormals ```ts calculateNormals(): void ``` Generates normal information from the positions and triangle indices. ### calculateTangents ```ts calculateTangents(): void ``` Generates tangent information from the positions, normals, texture coordinates and triangle indices. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GraphicsDevice.md # GraphicsDevice Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/graphics-device.js#L58 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. ## Properties ### backBufferAntialias ```ts backBufferAntialias: boolean = false ``` True if the back buffer should use anti-aliasing. ### canvas ```ts readonly canvas: HTMLCanvasElement ``` The canvas DOM element that provides the underlying WebGL context used by the graphics device. ### gpuProfiler ```ts gpuProfiler: GpuProfiler ``` The GPU profiler. ### insideRenderPass ```ts insideRenderPass: boolean = false ``` ### isHdr ```ts 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](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_HDR.md) when creating the graphics device using [createGraphicsDevice](https://api.playcanvas.com/engine/functions/createGraphicsDevice.md), and HDR is supported by the device. ### isNull ```ts readonly isNull: boolean = false ``` True if the deviceType is Null ### isWebGL2 ```ts readonly isWebGL2: boolean = false ``` True if the deviceType is WebGL2 ### isWebGPU ```ts readonly isWebGPU: boolean = false ``` True if the deviceType is WebGPU ### maxAnisotropy ```ts readonly maxAnisotropy: number ``` The maximum supported texture anisotropy setting. ### maxColorAttachments ```ts readonly maxColorAttachments: number = 1 ``` The maximum supported number of color buffers attached to a render target. ### maxCubeMapSize ```ts readonly maxCubeMapSize: number ``` The maximum supported dimension of a cube map. ### maxIndirectDispatchCount ```ts 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 ```ts 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. ### maxSamples ```ts readonly maxSamples: number = 1 ``` The maximum supported number of hardware anti-aliasing samples. ### maxSubgroupSize ```ts 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. ### maxTextureSize ```ts readonly maxTextureSize: number ``` The maximum supported dimension of a texture. ### maxVolumeSize ```ts readonly maxVolumeSize: number ``` The maximum supported dimension of a 3D texture (any axis). ### minSubgroupSize ```ts 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. ### precision ```ts readonly precision: string ``` The highest shader precision supported by this graphics device. Can be 'highp', 'mediump' or 'lowp'. ### samples ```ts readonly samples: number ``` The number of hardware anti-aliasing samples used by the frame buffer. ### scope ```ts readonly scope: ScopeSpace ``` The scope namespace for shader attributes and variables. ### supportsClipDistances ```ts 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. ### supportsCompute ```ts readonly supportsCompute: boolean = false ``` True if the device supports compute shaders. ### supportsDualSourceBlending ```ts 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. ### supportsHtmlTextures ```ts readonly supportsHtmlTextures: boolean = false ``` True if HTML elements (e.g. `
`) 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](https://api.playcanvas.com/engine/classes/Texture.md#setsource) and rendered as a live texture in the 3D scene. ### supportsIndependentBlending ```ts 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](https://api.playcanvas.com/engine/classes/BlendState.md#setattachment). When false, the state of the attachment 0 is used for all attachments. ### supportsIndirectDraw ```ts 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](https://api.playcanvas.com/engine/classes/MeshInstance.md#setindirect). ### supportsLinearIndexing ```ts 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 ```ts 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. ### supportsPacked4x8IntegerDotProduct ```ts 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. ### supportsPointerCompositeAccess ```ts 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. ### supportsPrimitiveIndex ```ts 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. ### supportsShaderF16 ```ts 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. ### supportsStorageTextureRead ```ts 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. ```wgsl requires readonly_and_readwrite_storage_textures; ``` ### supportsSubgroupId ```ts 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. ### supportsSubgroups ```ts 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. ### supportsSubgroupSizeControl ```ts readonly supportsSubgroupSizeControl: boolean = false ``` True if the device supports subgroup size control (WebGPU only). This depends on [supportsSubgroups](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportssubgroups) and, when available, allows a compute shader to pin its execution to a specific subgroup size (a power of two within the [minSubgroupSize](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#minsubgroupsize) to [maxSubgroupSize](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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. ### supportsSubgroupUniformity ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportssubgroups) is true. ### supportsTextureAndSamplerLet ```ts 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. ### supportsTextureFormatsTier1 ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportstextureformatstier2). ### supportsTextureFormatsTier2 ```ts 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. ### supportsTransientAttachments ```ts 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](https://api.playcanvas.com/engine/classes/RenderTarget.md) and [createGraphicsDevice](https://api.playcanvas.com/engine/functions/createGraphicsDevice.md). ### supportsUnrestrictedPointerParameters ```ts 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. ### textureFloatBlendable ```ts 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. ### textureFloatFilterable ```ts readonly textureFloatFilterable: boolean = false ``` True if filtering can be applied when sampling float textures. ### textureFloatRenderable ```ts readonly textureFloatRenderable: boolean ``` True if 32-bit floating-point textures can be used as a frame buffer. ### textureHalfFloatRenderable ```ts readonly textureHalfFloatRenderable: boolean ``` True if 16-bit floating-point textures can be used as a frame buffer. ### textureRG11B10Renderable ```ts readonly textureRG11B10Renderable: boolean = false ``` True if small-float textures with format [PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md) can be used as a frame buffer. This is always true on WebGL2, but optional on WebGPU device. ## Accessors ### deviceType ```ts get deviceType(): "webgl2" | "webgpu" ``` Gets the type of the device. Can be: - [DEVICETYPE_WEBGL2](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md) - [DEVICETYPE_WEBGPU](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md) ### fullscreen ```ts get fullscreen(): boolean set fullscreen(fullscreen: boolean) ``` Gets whether the device is currently in fullscreen mode. ### height ```ts get height(): number ``` Height of the back buffer in pixels. ### indirectDispatchBuffer ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#maxindirectdispatchcount) property. This buffer can be passed to a [Compute](https://api.playcanvas.com/engine/classes/Compute.md) shader along with a slot obtained by calling [getIndirectDispatchSlot](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#getindirectdispatchslot), in order to prepare indirect dispatch parameters. Only available on WebGPU, returns null on other platforms. ### indirectDrawBuffer ```ts 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#maxindirectdrawcount) property. This buffer can be passed to a [Compute](https://api.playcanvas.com/engine/classes/Compute.md) shader along with a slot obtained by calling [getIndirectDrawSlot](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#getindirectdrawslot), in order to prepare indirect draw parameters. Also see [MeshInstance#setIndirect](https://api.playcanvas.com/engine/classes/MeshInstance.md#setindirect). Only available on WebGPU, returns null on other platforms. ### maxPixelRatio ```ts get maxPixelRatio(): number set maxPixelRatio(ratio: number) ``` Gets the maximum pixel ratio. ### width ```ts get width(): number ``` Width of the back buffer in pixels. ## Methods ### computeDispatch ```ts computeDispatch(computes: Compute[], name?: string): void ``` Dispatch multiple compute shaders inside a single compute shader pass. **Parameters** - `computes` ([`Compute`](https://api.playcanvas.com/engine/classes/Compute.md)`[]`): An array of compute shaders to dispatch. - `name` (`string`, optional, default `'Unnamed'`): The name of the dispatch, used for debugging and reporting only. ### destroy ```ts destroy(): void ``` Destroy the graphics device. ### getIndirectDispatchSlot ```ts getIndirectDispatchSlot(count?: number): number ``` Retrieves the first available slot in the [indirectDispatchBuffer](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#indirectdispatchbuffer) used for indirect compute dispatch, which can be utilized by a [Compute](https://api.playcanvas.com/engine/classes/Compute.md) 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 ```ts getIndirectDrawSlot(count?: number): number ``` Retrieves the first available slot in the [indirectDrawBuffer](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#indirectdrawbuffer) used for indirect rendering, which can be utilized by a [Compute](https://api.playcanvas.com/engine/classes/Compute.md) shader to generate indirect draw parameters and by [MeshInstance#setIndirect](https://api.playcanvas.com/engine/classes/MeshInstance.md#setindirect) to configure indirect draw calls. When reserving multiple consecutive slots, specify the optional `count` parameter. Only available on WebGPU, see [GraphicsDevice#supportsIndirectDraw](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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 ```ts getRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefined ``` Get a renderable HDR pixel format supported by the graphics device. Note: - When the `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%). - When the `filterable` parameter is set to true, the function returns a format on a considerably lower number of devices (70%). - Support is determined by the precision of a format and not by its number of channels, and so all the half float formats are supported wherever any of them is, and similarly for the 32bit float formats. **Parameters** - `formats` (`number[]`, optional): An array of pixel formats to check for support. Can contain: - [PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md) - [PIXELFORMAT_R16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R16F.md) - [PIXELFORMAT_R32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) - [PIXELFORMAT_RG16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG16F.md) - [PIXELFORMAT_RG32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG32F.md) - [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md) - [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md) 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md) 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 ```ts getRenderTarget(): RenderTarget ``` Queries the currently set render target on the device. **Returns** [`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md): The current render target. **Example** ```ts // Get the current render target const renderTarget = device.getRenderTarget(); ``` ### postInit ```ts postInit(): void ``` Function that executes after the device has been created. ### setBlendColor ```ts setBlendColor(r: number, g: number, b: number, a: number): void ``` Sets the constant blend color and alpha values used with [BLENDMODE_CONSTANT](https://api.playcanvas.com/engine/variables/BLENDMODE_CONSTANT.md) and [BLENDMODE_ONE_MINUS_CONSTANT](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_CONSTANT.md) factors specified in [BlendState](https://api.playcanvas.com/engine/classes/BlendState.md). 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 ```ts setBlendState(blendState: BlendState): void ``` Sets the specified blend state. **Parameters** - `blendState` ([`BlendState`](https://api.playcanvas.com/engine/classes/BlendState.md)): New blend state. ### setCullMode ```ts setCullMode(cullMode: number): void ``` Controls how triangles are culled based on their face direction. The default cull mode is [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md). **Parameters** - `cullMode` (`number`): The cull mode to set. Can be: - [CULLFACE_NONE](https://api.playcanvas.com/engine/variables/CULLFACE_NONE.md) - [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md) - [CULLFACE_FRONT](https://api.playcanvas.com/engine/variables/CULLFACE_FRONT.md) ### setDepthState ```ts setDepthState(depthState: DepthState): void ``` Sets the specified depth state. **Parameters** - `depthState` ([`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md)): New depth state. ### setDrawStates ```ts 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`](https://api.playcanvas.com/engine/classes/BlendState.md), optional, default `BlendState.NOBLEND`): Blend state. Defaults to [BlendState.NOBLEND](https://api.playcanvas.com/engine/classes/BlendState.md#noblend). - `depthState` ([`DepthState`](https://api.playcanvas.com/engine/classes/DepthState.md), optional, default `DepthState.NODEPTH`): Depth state. Defaults to [DepthState.NODEPTH](https://api.playcanvas.com/engine/classes/DepthState.md#nodepth). - `cullMode` (`number`, optional, default `CULLFACE_NONE`): Cull mode. Defaults to [CULLFACE_NONE](https://api.playcanvas.com/engine/variables/CULLFACE_NONE.md). - `frontFace` (`number`, optional, default `FRONTFACE_CCW`): Front face winding. Defaults to [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md). - `stencilFront` ([`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md), optional): Front stencil parameters. - `stencilBack` ([`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md), optional): Back stencil parameters. ### setFrontFace ```ts setFrontFace(frontFace: number): void ``` Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md). **Parameters** - `frontFace` (`number`): The front face to set. Can be: - [FRONTFACE_CW](https://api.playcanvas.com/engine/variables/FRONTFACE_CW.md) - [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md) ### setRenderTarget ```ts 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`](https://api.playcanvas.com/engine/classes/RenderTarget.md) `| null`): The render target to activate. **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/StencilParameters.md), optional): The front stencil parameters. Defaults to [StencilParameters.DEFAULT](https://api.playcanvas.com/engine/classes/StencilParameters.md#default) if not specified. - `stencilBack` ([`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md), optional): The back stencil parameters. Defaults to [StencilParameters.DEFAULT](https://api.playcanvas.com/engine/classes/StencilParameters.md#default) if not specified. ### validateAttributes ```ts 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`](https://api.playcanvas.com/engine/classes/Shader.md)): The shader to validate. - `vertexBuffers` (`(`[`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md) `| null | undefined)[]`): The vertex buffers of the draw. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatComponent.md # GSplatComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/gsplat/component.js#L71 The GSplatComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to render 3D Gaussian Splats. Splats are always loaded from [Asset](https://api.playcanvas.com/engine/classes/Asset.md)s 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#gsplat) property: ```javascript entity.gsplat.customAabb = new BoundingBox(new Vec3(), new Vec3(10, 10, 10)); console.log(entity.gsplat.customAabb); ``` Relevant Engine API examples: - [Simple Splat Loading](https://playcanvas.github.io/#/gaussian-splatting/simple) - [Billions of Splats](https://playcanvas.github.io/#/gaussian-splatting/billions) - [Downtown Streaming](https://playcanvas.github.io/#/gaussian-splatting/downtown) - [Global Sorting](https://playcanvas.github.io/#/gaussian-splatting/global-sorting) - [LOD Instances](https://playcanvas.github.io/#/gaussian-splatting/lod-instances) - [LOD Streaming](https://playcanvas.github.io/#/gaussian-splatting/lod-streaming) - [LOD Streaming with Spherical Harmonics](https://playcanvas.github.io/#/gaussian-splatting/lod-streaming-sh) - [Multi-Splat](https://playcanvas.github.io/#/gaussian-splatting/multi-splat) - [Multi-View](https://playcanvas.github.io/#/gaussian-splatting/multi-view) - [Picking](https://playcanvas.github.io/#/gaussian-splatting/picking) - [Reveal Effect](https://playcanvas.github.io/#/gaussian-splatting/reveal) - [Shader Effects](https://playcanvas.github.io/#/gaussian-splatting/shader-effects) - [Spherical Harmonics](https://playcanvas.github.io/#/gaussian-splatting/spherical-harmonics) ## Accessors ### asset ```ts get asset(): number | Asset set asset(value: number | Asset) ``` Gets the gsplat asset id for this gsplat component. ### castShadows ```ts get castShadows(): boolean set castShadows(value: boolean) ``` Gets whether gsplat will cast shadows for lights that have shadow casting enabled. ### customAabb ```ts 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. ### id ```ts 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. ### layers ```ts get layers(): number[] set layers(value: number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this gsplat belongs. ### lodBaseDistance ```ts get lodBaseDistance(): number set lodBaseDistance(value: number) ``` Gets the base distance for the first LOD transition. ### lodMultiplier ```ts get lodMultiplier(): number set lodMultiplier(value: number) ``` Gets the geometric multiplier between successive LOD distance thresholds. ### lodRangeMax ```ts get lodRangeMax(): number set lodRangeMax(value: number) ``` Gets the maximum allowed LOD index. ### lodRangeMin ```ts get lodRangeMin(): number set lodRangeMin(value: number) ``` Gets the minimum allowed LOD index. ### resource ```ts 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. ### workBufferUpdate ```ts get workBufferUpdate(): number set workBufferUpdate(value: number) ``` Gets the work buffer update mode. ## Methods ### deleteParameter ```ts deleteParameter(name: string): void ``` Deletes a shader parameter previously set with [setParameter](https://api.playcanvas.com/engine/classes/GSplatComponent.md#setparameter). **Parameters** - `name` (`string`): The name of the parameter to delete. ### getInstanceTexture ```ts 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`](https://api.playcanvas.com/engine/classes/Texture.md) `| null`: The texture, or null if not found. **Example** ```ts // 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 ```ts getParameter(name: string): number | number[] | ArrayBufferView | undefined ``` Gets a shader parameter value previously set with [setParameter](https://api.playcanvas.com/engine/classes/GSplatComponent.md#setparameter). **Parameters** - `name` (`string`): The name of the parameter. **Returns** `number | number[] | ArrayBufferView | undefined`: The parameter value, or undefined if not set. ### hide ```ts hide(): void ``` Stop rendering this component without removing its mesh instance from the scene hierarchy. ### setParameter ```ts setParameter(name: string, data: number | number[] | ArrayBufferView | 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 |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md)): The value for the parameter. ### setWorkBufferModifier ```ts 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 position - `modifySplatRotationScale`: Modify the splat rotation and scale - `modifySplatColor`: Modify the splat color Calling 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** ```ts 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) {} fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr, scale: ptr) {} fn modifySplatColor(center: vec3f, color: ptr) { (*color).r = 1.0; (*color).g = 0.0; (*color).b = 0.0; } ` }); ``` ### show ```ts show(): void ``` Enable rendering of the component if hidden using [hide](https://api.playcanvas.com/engine/classes/GSplatComponent.md#hide). ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatComponentSystem.md # GSplatComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/gsplat/system.js#L65 Manages the [GSplatComponent](https://api.playcanvas.com/engine/classes/GSplatComponent.md)s of an application. Reach it through `app.systems.gsplat`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Methods ### getMaterial ```ts 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`](https://api.playcanvas.com/engine/classes/Layer.md)): The layer instance. **Returns** [`ShaderMaterial`](https://api.playcanvas.com/engine/classes/ShaderMaterial.md) `| null`: The material, or null if not created yet. **Example** ```ts app.systems.gsplat.on('material:created', (material, camera, layer) => { // Material is now available material.setParameter('myParam', value); }); ``` ## Events ### EVENT_FRAMEREADY ```ts static EVENT_FRAMEREADY: string = 'frame:ready' ``` Fired every frame for each camera and layer combination rendering GSplats. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md), the [Layer](https://api.playcanvas.com/engine/classes/Layer.md), 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** ```ts // 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** ```ts // 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)}%`); }); ``` ### EVENT_FRAMEREQUEST ```ts 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](https://api.playcanvas.com/engine/classes/AppBase.md#autorender) set to false: a typical handler sets [AppBase#renderNextFrame](https://api.playcanvas.com/engine/classes/AppBase.md#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** ```ts app.autoRender = false; app.systems.gsplat.on('frame:request', () => { app.renderNextFrame = true; }); ``` ### EVENT_MATERIALCREATED ```ts 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](https://api.playcanvas.com/engine/classes/ShaderMaterial.md), the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md), and the [Layer](https://api.playcanvas.com/engine/classes/Layer.md). This event is useful for setting up custom material chunks and parameters before the first render. **Example** ```ts 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); }); ``` ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatContainer.md # GSplatContainer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-container.js#L66 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](https://api.playcanvas.com/engine/classes/GSplatFormat.md#createdefaultformat) which uses float textures for easy CPU population. **Example** ```ts // 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** ```ts // 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); ``` ## Constructors ### constructor ```ts new GSplatContainer(device: GraphicsDevice, maxSplats: number, format: GSplatFormat) ``` Creates a new GSplatContainer instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `maxSplats` (`number`): Maximum number of splats this container can hold. - `format` ([`GSplatFormat`](https://api.playcanvas.com/engine/classes/GSplatFormat.md)): The format descriptor with streams and read code. Use [GSplatFormat.createDefaultFormat](https://api.playcanvas.com/engine/classes/GSplatFormat.md#createdefaultformat) for the built-in format, or create a custom [GSplatFormat](https://api.playcanvas.com/engine/classes/GSplatFormat.md). ## Accessors ### centers ```ts get centers(): Float32Array set centers(value: Float32Array) ``` CPU-side splat center positions (xyz per splat), or null when not built for this resource. ### maxSplats ```ts get maxSplats(): number ``` Maximum number of splats this container can hold. ### numSplats ```ts get numSplats(): number ``` Gets the number of splats to render. ## Methods ### update ```ts 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](https://api.playcanvas.com/engine/classes/GSplatContainer.md#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). ## Inherited from GSplatResourceBase - `protected _centers: Float32Array | null` - `aabb: BoundingBox` - `get format(): GSplatFormat` - `get hasCenters(): boolean` - `get textureDimensions(): Vec2` - `protected _actualDestroy(): void` - `destroy(): void` - `getTexture(name: string): Texture | null` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatFormat.md # GSplatFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-format.js#L89 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](https://api.playcanvas.com/engine/classes/GSplatFormat.md#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](https://api.playcanvas.com/engine/classes/GSplatContainer.md), users define both base and extra streams to specify the complete data layout. ## Constructors ### constructor ```ts new GSplatFormat(device: GraphicsDevice, streams: GSplatStreamDescriptor[], options: object) ``` Creates a new GSplatFormat instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `streams` ([`GSplatStreamDescriptor`](https://api.playcanvas.com/engine/interfaces/GSplatStreamDescriptor.md)`[]`): 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. ## Properties ### streams ```ts readonly streams: GSplatStreamDescriptor[] ``` Array of stream descriptors. ## Accessors ### extraStreams ```ts get extraStreams(): GSplatStreamDescriptor[] ``` Gets the extra streams array. Streams can only be added via [addExtraStreams](https://api.playcanvas.com/engine/classes/GSplatFormat.md#addextrastreams), not removed. Do not modify the returned array directly. ## Methods ### addExtraStreams ```ts 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`](https://api.playcanvas.com/engine/interfaces/GSplatStreamDescriptor.md)`[]`): Array of stream descriptors to add. ### createDefaultFormat ```ts 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](https://api.playcanvas.com/engine/classes/GSplatProcessor.md) when supported. Check [GraphicsDevice#textureFloatRenderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatrenderable) (for RGBA32F) and [GraphicsDevice#textureHalfFloatRenderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturehalffloatrenderable) (for RGBA16F). The format stores: - `dataColor` (RGBA16F): color.rgba as half floats - `dataCenter` (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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. **Returns** [`GSplatFormat`](https://api.playcanvas.com/engine/classes/GSplatFormat.md): The default format. ### createSimpleFormat ```ts static createSimpleFormat(device: GraphicsDevice): GSplatFormat ``` Creates a simple format with uniform-scale splats and no rotation. Streams: - `dataCenter` (RGBA32F): center.xyz + uniform size in w - `dataColor` (RGBA16F): color.rgba as half floats **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. **Returns** [`GSplatFormat`](https://api.playcanvas.com/engine/classes/GSplatFormat.md): The simple format. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatParams.md # GSplatParams Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-params.js#L40 Parameters for the GSplat system. ## Constructors ### constructor ```ts new GSplatParams(device: GraphicsDevice) ``` Creates a new GSplatParams instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. ## Properties ### colorRampIntensity ```ts 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 ```ts 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 ```ts 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 ```ts dither: string = DITHER_BLUENOISE ``` The noise pattern the coverage of a [GSplatParams#stochastic](https://api.playcanvas.com/engine/classes/GSplatParams.md#stochastic) splat is dithered against, ignored when `stochastic` is false. Can be: - [DITHER_BAYER2](https://api.playcanvas.com/engine/variables/DITHER_BAYER2.md): Coverage is dithered using a Bayer 2 matrix. - [DITHER_BAYER4](https://api.playcanvas.com/engine/variables/DITHER_BAYER4.md): Coverage is dithered using a Bayer 4 matrix. - [DITHER_BAYER8](https://api.playcanvas.com/engine/variables/DITHER_BAYER8.md): Coverage is dithered using a Bayer 8 matrix. - [DITHER_BAYER16](https://api.playcanvas.com/engine/variables/DITHER_BAYER16.md): Coverage is dithered using a Bayer 16 matrix. - [DITHER_BLUENOISE](https://api.playcanvas.com/engine/variables/DITHER_BLUENOISE.md): Coverage is dithered using a blue noise. - [DITHER_IGNNOISE](https://api.playcanvas.com/engine/variables/DITHER_IGNNOISE.md): Coverage is dithered using an interleaved gradient noise. Defaults to [DITHER_BLUENOISE](https://api.playcanvas.com/engine/variables/DITHER_BLUENOISE.md), which looks best under temporal anti-aliasing. [DITHER_NONE](https://api.playcanvas.com/engine/variables/DITHER_NONE.md) is not a coverage pattern, so it is not accepted here - turn `stochastic` off instead. ### lodUpdateAngle ```ts 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](https://api.playcanvas.com/engine/classes/GSplatParams.md#lodbehindpenalty), so rotation-based updates also stop when the penalty is 1. Defaults to 90. ### lodUpdateDistance ```ts lodUpdateDistance: number = 1 ``` Distance threshold in world units to trigger LOD updates for camera and gsplat instances. Defaults to 1. ### radialSorting ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/CameraFrame.md) - see [CameraFrame.isSplatSceneDepthSupported](https://api.playcanvas.com/engine/classes/CameraFrame.md#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 ```ts 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 ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/Scene.md#exposure) and the camera's [CameraComponent#toneMapping](https://api.playcanvas.com/engine/classes/CameraComponent.md#tonemapping). Fog, when enabled, still applies. Defaults to true. ## Accessors ### alphaClip ```ts get alphaClip(): number set alphaClip(value: number) ``` Gets the alpha threshold for shadow, pick, and prepass rendering. ### alphaClipForward ```ts get alphaClipForward(): number set alphaClipForward(value: number) ``` Gets the forward-pass alpha threshold. ### antiAlias ```ts get antiAlias(): boolean set antiAlias(value: boolean) ``` Gets whether anti-aliasing compensation is enabled. ### colorizeColorUpdate ```ts get colorizeColorUpdate(): boolean set colorizeColorUpdate(value: boolean) ``` **Deprecated**: Use [debug](https://api.playcanvas.com/engine/classes/GSplatParams.md#debug) with [GSPLAT_DEBUG_SH_UPDATE](https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_SH_UPDATE.md) instead. ### colorRamp ```ts get colorRamp(): Texture | null set colorRamp(value: Texture | null) ``` Gets the color ramp texture for overdraw visualization. ### currentRenderer ```ts get currentRenderer(): number ``` The current rendering pipeline in effect after platform-based fallback resolution. When [renderer](https://api.playcanvas.com/engine/classes/GSplatParams.md#renderer) is set to a mode requiring WebGPU on a WebGL device, this returns the fallback mode actually being used. ### dataFormat ```ts get dataFormat(): string set dataFormat(value: string) ``` Gets the work buffer data format. ### debug ```ts get debug(): number set debug(value: number) ``` Gets the debug rendering mode for Gaussian splats. ### enableIds ```ts get enableIds(): boolean set enableIds(value: boolean) ``` Gets the ID storage enabled state. ### fisheye ```ts get fisheye(): number set fisheye(value: number) ``` Gets the fisheye projection strength. ### format ```ts 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](https://api.playcanvas.com/engine/classes/GSplatFormat.md#addextrastreams) for custom per-splat data. **Example** ```ts // Add a custom stream to store per-splat component IDs app.scene.gsplat.format.addExtraStreams([{ name: 'splatId', format: PIXELFORMAT_R32U }]); ``` ### foveationCenter ```ts get foveationCenter(): number set foveationCenter(value: number) ``` Gets the protected centre radius for foveated contribution culling. ### foveationStrength ```ts get foveationStrength(): number set foveationStrength(value: number) ``` Gets the foveated contribution culling strength. ### lodBehindPenalty ```ts get lodBehindPenalty(): number set lodBehindPenalty(value: number) ``` Gets behind-camera LOD penalty multiplier. ### lodUnderfillLimit ```ts get lodUnderfillLimit(): number set lodUnderfillLimit(value: number) ``` Gets the maximum allowed underfill LOD range. ### material ```ts 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](https://api.playcanvas.com/engine/classes/Material.md#update) to for the changes to be applied on the next frame. **Example** ```ts // Set a custom parameter on all GSplat materials app.scene.gsplat.material.setParameter('myCustomParam', 1.0); app.scene.gsplat.material.update(); ``` ### minContribution ```ts get minContribution(): number set minContribution(value: number) ``` Gets the minimum contribution threshold. ### minPixelSize ```ts get minPixelSize(): number set minPixelSize(value: number) ``` Gets the minimum pixel size threshold. ### renderer ```ts get renderer(): number set renderer(value: number) ``` Gets the requested rendering pipeline for gaussian splatting. This may differ from [currentRenderer](https://api.playcanvas.com/engine/classes/GSplatParams.md#currentrenderer) when a WebGPU mode falls back on a WebGL device. ### splatBudget ```ts get splatBudget(): number set splatBudget(value: number) ``` Gets the number of splats across all GSplats in the scene. ### splatBudgetMode ```ts get splatBudgetMode(): string set splatBudgetMode(value: string) ``` Gets how the splat budget is used. ### twoDimensional ```ts get twoDimensional(): boolean set twoDimensional(value: boolean) ``` Gets whether 2D Gaussian Splatting mode is enabled. ### varyings ```ts 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](https://api.playcanvas.com/engine/classes/GSplatVaryings.md). **Example** ```ts // 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 }]); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatProcessor.md # GSplatProcessor Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/gsplat/gsplat-processor.js#L104 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](https://api.playcanvas.com/engine/classes/GSplatFormat.md#addextrastreams), or you can create fully procedural splat data using [GSplatContainer](https://api.playcanvas.com/engine/classes/GSplatContainer.md). 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](https://api.playcanvas.com/engine/classes/GSplatProcessor.md#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 resource - `dstNumSplats` (uint) - Number of splats in destination resource **Example** ```ts // 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(); ``` ## Constructors ### constructor ```ts new GSplatProcessor(device: GraphicsDevice, source: GSplatProcessorBinding, destination: GSplatProcessorBinding, options: object) ``` Creates a new GSplatProcessor instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `source` ([`GSplatProcessorBinding`](https://api.playcanvas.com/engine/interfaces/GSplatProcessorBinding.md)): Source configuration specifying where to read from. Can specify resource directly or component (for instance textures). - `destination` ([`GSplatProcessorBinding`](https://api.playcanvas.com/engine/interfaces/GSplatProcessorBinding.md)): 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. ## Properties ### blendState ```ts 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. ## Methods ### deleteParameter ```ts deleteParameter(name: string): void ``` Removes a shader parameter. **Parameters** - `name` (`string`): The name of the parameter to remove. ### destroy ```ts destroy(): void ``` Destroys this processor and releases all resources. ### getParameter ```ts getParameter(name: string): number | number[] | ArrayBufferView | Texture | StorageBuffer | undefined ``` Gets a shader parameter value previously set with [setParameter](https://api.playcanvas.com/engine/classes/GSplatProcessor.md#setparameter). **Parameters** - `name` (`string`): The name of the parameter. **Returns** `number | number[] | ArrayBufferView |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md) `| undefined`: The parameter value, or undefined if not set. ### process ```ts process(): void ``` Executes the processing, reading from source streams and writing to destination streams. ### setParameter ```ts setParameter(name: string, data: number | number[] | ArrayBufferView | 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 |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md)): The value for the parameter. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GSplatVaryings.md # GSplatVaryings Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-varyings.js#L89 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](https://api.playcanvas.com/engine/classes/GSplatParams.md#varyings). ## Accessors ### streams ```ts get streams(): GSplatVaryingDescriptor[] ``` Gets the varying stream descriptors. Do not modify the returned array. ## Methods ### add ```ts add(streams: GSplatVaryingDescriptor[]): void ``` Adds varying streams. For each stream, a set function (`set`) is generated and made available to the `gsplatModifyVS` shader chunk, where it runs once per splat, and a matching get function (`get`) 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](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md), [TYPE_INT32](https://api.playcanvas.com/engine/variables/TYPE_INT32.md) and [TYPE_UINT32](https://api.playcanvas.com/engine/variables/TYPE_UINT32.md), 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`](https://api.playcanvas.com/engine/interfaces/GSplatVaryingDescriptor.md)`[]`): The streams to add. **Example** ```ts // 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 ```ts remove(names: string[]): void ``` Removes varying streams previously added by [GSplatVaryings#add](https://api.playcanvas.com/engine/classes/GSplatVaryings.md#add). **Parameters** - `names` (`string[]`): The names of the streams to remove. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ImgParser.md # ImgParser Class · extends [`TextureParser`](https://api.playcanvas.com/engine/classes/TextureParser.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/texture/img.js#L20 Parser for browser-supported image formats. ## Methods ### load ```ts 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 ```ts open(url: any, data: any, device: any, textureOptions?: {}): Texture ``` Convert raw resource data into a [Texture](https://api.playcanvas.com/engine/classes/Texture.md). **Parameters** - `url` (`any`): The URL of the resource to open. - `data` (`any`): The raw resource data passed by callback from [ResourceHandler#load](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `device` (`any`): The graphics device. - `textureOptions` (`{}`, optional, default `{}`) **Returns** [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md): The parsed resource data. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/IndexBuffer.md # IndexBuffer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/index-buffer.js#L23 An index buffer stores index values into a [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md). Indexed graphical primitives can normally utilize less memory that unindexed primitives (if vertices are shared). Typically, index buffers are set on [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) objects. ## Constructors ### constructor ```ts new IndexBuffer(graphicsDevice: GraphicsDevice, format: number, numIndices: number, usage?: number, initialData?: ArrayBuffer | ArrayBufferView, options?: object) ``` Create a new IndexBuffer instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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: - [INDEXFORMAT_UINT8](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT8.md) - [INDEXFORMAT_UINT16](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT16.md) - [INDEXFORMAT_UINT32](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT32.md) - `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: - [BUFFER_DYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md) - [BUFFER_STATIC](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md) - [BUFFER_STREAM](https://api.playcanvas.com/engine/variables/BUFFER_STREAM.md) Defaults to [BUFFER_STATIC](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md). - `initialData` (`ArrayBuffer | ArrayBufferView`, optional): Initial data. Can be an [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or a typed array (for example a [Uint16Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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** ```ts // 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); ``` ## Methods ### destroy ```ts destroy(): void ``` Frees resources associated with this index buffer. ### getFormat ```ts getFormat(): number ``` Returns the data format of the specified index buffer. **Returns** `number`: The data format of the specified index buffer. Can be: - [INDEXFORMAT_UINT8](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT8.md) - [INDEXFORMAT_UINT16](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT16.md) - [INDEXFORMAT_UINT32](https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT32.md) ### getNumIndices ```ts 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 ```ts lock(): ArrayBuffer | ArrayBufferView ``` Gives access to the block of memory that stores the buffer's indices. **Returns** `ArrayBuffer | ArrayBufferView`: The memory that stores the buffer's indices. This matches whatever was supplied as the initial data: an [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) when none was provided, otherwise the [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or typed array that was passed in. Use [ArrayBufferConstructor.isView](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView) to distinguish the two before accessing it. ### unlock ```ts 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** ```ts // After modifying bytes 16 through 31 of the CPU storage: indexBuffer.unlock(16, 16); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Layer.md # Layer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/layer.js#L93 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](https://api.playcanvas.com/engine/classes/LayerComposition.md) 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#layers). Components place their mesh instances by layer id, for example through [RenderComponent#layers](https://api.playcanvas.com/engine/classes/RenderComponent.md#layers), and lights through [LightComponent#layers](https://api.playcanvas.com/engine/classes/LightComponent.md#layers); mesh instances you create yourself go in with [addMeshInstances](https://api.playcanvas.com/engine/classes/Layer.md#addmeshinstances) and out with [removeMeshInstances](https://api.playcanvas.com/engine/classes/Layer.md#removemeshinstances). The application creates five layers, reachable by id from [Scene#layers](https://api.playcanvas.com/engine/classes/Scene.md#layers): [LAYERID_WORLD](https://api.playcanvas.com/engine/variables/LAYERID_WORLD.md) for the scene itself, [LAYERID_DEPTH](https://api.playcanvas.com/engine/variables/LAYERID_DEPTH.md), [LAYERID_SKYBOX](https://api.playcanvas.com/engine/variables/LAYERID_SKYBOX.md), [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md) for debug drawing and [LAYERID_UI](https://api.playcanvas.com/engine/variables/LAYERID_UI.md). Within a layer, opaque and transparent mesh instances are drawn as two separate parts, ordered by [opaqueSortMode](https://api.playcanvas.com/engine/classes/Layer.md#opaquesortmode) and [transparentSortMode](https://api.playcanvas.com/engine/classes/Layer.md#transparentsortmode), and the composition decides where each part falls in the frame. Set [enabled](https://api.playcanvas.com/engine/classes/Layer.md#enabled) to false to skip a layer entirely, and use [onEnable](https://api.playcanvas.com/engine/classes/Layer.md#onenable) and [onDisable](https://api.playcanvas.com/engine/classes/Layer.md#ondisable) to react to that. **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts 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. ## Properties ### id ```ts id: number ``` A unique ID of the layer. Layer IDs are stored inside [ModelComponent#layers](https://api.playcanvas.com/engine/classes/ModelComponent.md#layers), [RenderComponent#layers](https://api.playcanvas.com/engine/classes/RenderComponent.md#layers), [CameraComponent#layers](https://api.playcanvas.com/engine/classes/CameraComponent.md#layers), [LightComponent#layers](https://api.playcanvas.com/engine/classes/LightComponent.md#layers) and [ElementComponent#layers](https://api.playcanvas.com/engine/classes/ElementComponent.md#layers) instead of names. Can be used in [LayerComposition#getLayerById](https://api.playcanvas.com/engine/classes/LayerComposition.md#getlayerbyid). ### name ```ts name: string ``` Name of the layer. Can be used in [LayerComposition#getLayerByName](https://api.playcanvas.com/engine/classes/LayerComposition.md#getlayerbyname). ### onDisable ```ts onDisable: Function ``` Custom function that is called after the layer has been disabled. This happens when: - [enabled](https://api.playcanvas.com/engine/classes/Layer.md#enabled) was changed from true to false - `decrementCounter` was called and set the counter to zero. ### onEnable ```ts onEnable: Function ``` Custom function that is called after the layer has been enabled. This happens when: - The layer is created with [enabled](https://api.playcanvas.com/engine/classes/Layer.md#enabled) set to true (which is the default value). - [enabled](https://api.playcanvas.com/engine/classes/Layer.md#enabled) was changed from false to true ### opaqueSortMode ```ts opaqueSortMode: number = SORTMODE_MATERIALMESH ``` Defines the method used for sorting opaque (that is, not semi-transparent) mesh instances before rendering. Can be: - [SORTMODE_NONE](https://api.playcanvas.com/engine/variables/SORTMODE_NONE.md) - [SORTMODE_MANUAL](https://api.playcanvas.com/engine/variables/SORTMODE_MANUAL.md) - [SORTMODE_MATERIALMESH](https://api.playcanvas.com/engine/variables/SORTMODE_MATERIALMESH.md) - [SORTMODE_BACK2FRONT](https://api.playcanvas.com/engine/variables/SORTMODE_BACK2FRONT.md) - [SORTMODE_FRONT2BACK](https://api.playcanvas.com/engine/variables/SORTMODE_FRONT2BACK.md) Defaults to [SORTMODE_MATERIALMESH](https://api.playcanvas.com/engine/variables/SORTMODE_MATERIALMESH.md). ### transparentSortMode ```ts transparentSortMode: number = SORTMODE_BACK2FRONT ``` Defines the method used for sorting semi-transparent mesh instances before rendering. Can be: - [SORTMODE_NONE](https://api.playcanvas.com/engine/variables/SORTMODE_NONE.md) - [SORTMODE_MANUAL](https://api.playcanvas.com/engine/variables/SORTMODE_MANUAL.md) - [SORTMODE_MATERIALMESH](https://api.playcanvas.com/engine/variables/SORTMODE_MATERIALMESH.md) - [SORTMODE_BACK2FRONT](https://api.playcanvas.com/engine/variables/SORTMODE_BACK2FRONT.md) - [SORTMODE_FRONT2BACK](https://api.playcanvas.com/engine/variables/SORTMODE_FRONT2BACK.md) Defaults to [SORTMODE_BACK2FRONT](https://api.playcanvas.com/engine/variables/SORTMODE_BACK2FRONT.md). ## Accessors ### clearColorBuffer ```ts get clearColorBuffer(): boolean set clearColorBuffer(val: boolean) ``` Gets whether the camera will clear the color buffer when it renders this layer. ### clearDepthBuffer ```ts get clearDepthBuffer(): boolean set clearDepthBuffer(val: boolean) ``` Gets whether the camera will clear the depth buffer when it renders this layer. ### clearStencilBuffer ```ts get clearStencilBuffer(): boolean set clearStencilBuffer(val: boolean) ``` Gets whether the camera will clear the stencil buffer when it renders this layer. ### enabled ```ts get enabled(): boolean set enabled(val: boolean) ``` Gets the enabled state of the layer. ## Methods ### addCamera ```ts addCamera(camera: CameraComponent): void ``` Adds a camera to this layer. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): A [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md). ### addLight ```ts addLight(light: LightComponent): void ``` Adds a light to this layer. **Parameters** - `light` ([`LightComponent`](https://api.playcanvas.com/engine/classes/LightComponent.md)): A [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md). ### addMeshInstances ```ts addMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void ``` Adds an array of mesh instances to this layer. **Parameters** - `meshInstances` ([`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): Array of [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md). - `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 ```ts 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`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): Array of [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md). ### clearCameras ```ts clearCameras(): void ``` Removes all cameras from this layer. ### clearLights ```ts clearLights(): void ``` Removes all lights from this layer. ### clearMeshInstances ```ts 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 ```ts removeCamera(camera: CameraComponent): void ``` Removes a camera from this layer. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): A [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md). ### removeLight ```ts removeLight(light: LightComponent): void ``` Removes a light from this layer. **Parameters** - `light` ([`LightComponent`](https://api.playcanvas.com/engine/classes/LightComponent.md)): A [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md). ### removeMeshInstances ```ts removeMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void ``` Removes multiple mesh instances from this layer. **Parameters** - `meshInstances` ([`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): Array of [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md). 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 ```ts 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`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`[]`): Array of [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md). If they were added to this layer, they will be removed. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LayerComposition.md # LayerComposition Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/composition/layer-composition.js#L41 Layer Composition is a collection of [Layer](https://api.playcanvas.com/engine/classes/Layer.md) that is fed to [Scene#layers](https://api.playcanvas.com/engine/classes/Scene.md#layers) to define rendering order. Each layer is rendered as two parts, its opaque mesh instances and its transparent ones, and [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist) holds the sequence of parts in the order they are drawn. [push](https://api.playcanvas.com/engine/classes/LayerComposition.md#push) and [insert](https://api.playcanvas.com/engine/classes/LayerComposition.md#insert) add both parts of a layer together, while [pushOpaque](https://api.playcanvas.com/engine/classes/LayerComposition.md#pushopaque), [pushTransparent](https://api.playcanvas.com/engine/classes/LayerComposition.md#pushtransparent), [insertOpaque](https://api.playcanvas.com/engine/classes/LayerComposition.md#insertopaque) and [insertTransparent](https://api.playcanvas.com/engine/classes/LayerComposition.md#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](https://api.playcanvas.com/engine/classes/LayerComposition.md#getlayerbyid) and [getLayerByName](https://api.playcanvas.com/engine/classes/LayerComposition.md#getlayerbyname), find where a part sits with [getOpaqueIndex](https://api.playcanvas.com/engine/classes/LayerComposition.md#getopaqueindex) and [getTransparentIndex](https://api.playcanvas.com/engine/classes/LayerComposition.md#gettransparentindex), and take a layer out with [remove](https://api.playcanvas.com/engine/classes/LayerComposition.md#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](https://api.playcanvas.com/engine/classes/LayerComposition.md#getopaqueindex) or [getTransparentIndex](https://api.playcanvas.com/engine/classes/LayerComposition.md#gettransparentindex). **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts 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. ## Properties ### layerList ```ts layerList: Layer[] = [] ``` A read-only array of [Layer](https://api.playcanvas.com/engine/classes/Layer.md) sorted in the order they will be rendered. ### subLayerEnabled ```ts subLayerEnabled: boolean[] = [] ``` A read-only array of boolean values, matching [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). True means the layer is rendered, false means it's skipped. ## Methods ### getLayerById ```ts 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`](https://api.playcanvas.com/engine/classes/Layer.md) `| null`: The layer corresponding to the specified ID. Returns null if layer is not found. ### getLayerByName ```ts 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`](https://api.playcanvas.com/engine/classes/Layer.md) `| null`: The layer corresponding to the specified name. Returns null if layer is not found. ### getOpaqueIndex ```ts getOpaqueIndex(layer: Layer): number ``` Gets index of the opaque part of the supplied layer in the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to find index of. **Returns** `number`: The index of the opaque part of the specified layer, or -1 if it is not part of the composition. ### getTransparentIndex ```ts getTransparentIndex(layer: Layer): number ``` Gets index of the semi-transparent part of the supplied layer in the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to find index of. **Returns** `number`: The index of the semi-transparent part of the specified layer, or -1 if it is not part of the composition. ### insert ```ts insert(layer: Layer, index: number): void ``` Inserts a layer (both opaque and semi-transparent parts) at the chosen index in the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. - `index` (`number`): Insertion position. ### insertOpaque ```ts 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](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. - `index` (`number`): Insertion position. ### insertTransparent ```ts insertTransparent(layer: Layer, index: number): void ``` Inserts a semi-transparent part of the layer at the chosen index in the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. - `index` (`number`): Insertion position. ### push ```ts push(layer: Layer): void ``` Adds a layer (both opaque and semi-transparent parts) to the end of the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#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](https://api.playcanvas.com/engine/classes/LayerComposition.md#insert) with an index from [LayerComposition#getOpaqueIndex](https://api.playcanvas.com/engine/classes/LayerComposition.md#getopaqueindex). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. ### pushOpaque ```ts pushOpaque(layer: Layer): void ``` Adds part of the layer with opaque (non semi-transparent) objects to the end of the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. ### pushTransparent ```ts pushTransparent(layer: Layer): void ``` Adds part of the layer with semi-transparent objects to the end of the [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to add. ### remove ```ts remove(layer: Layer): void ``` Removes a layer (both opaque and semi-transparent parts) from [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to remove. ### removeOpaque ```ts removeOpaque(layer: Layer): void ``` Removes an opaque part of the layer (non semi-transparent mesh instances) from [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to remove. ### removeTransparent ```ts removeTransparent(layer: Layer): void ``` Removes a transparent part of the layer from [layerList](https://api.playcanvas.com/engine/classes/LayerComposition.md#layerlist). **Parameters** - `layer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): A [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to remove. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LightComponent.md # LightComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/light/component.js#L136 The LightComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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](https://api.playcanvas.com/engine/classes/GraphNode.md#lookat) orients an entity's negative z-axis, which aims a camera but not a light: ```javascript // 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#light) property: ```javascript 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: - [Area Lights](https://playcanvas.github.io/#/graphics/area-lights) - [Clustered Area Lights](https://playcanvas.github.io/#/graphics/clustered-area-lights) - [Clustered Lighting](https://playcanvas.github.io/#/graphics/clustered-lighting) - [Clustered Omni Shadows](https://playcanvas.github.io/#/graphics/clustered-omni-shadows) - [Clustered Spot Shadows](https://playcanvas.github.io/#/graphics/clustered-spot-shadows) - [Lights](https://playcanvas.github.io/#/graphics/lights) ## Accessors ### affectDynamic ```ts get affectDynamic(): boolean set affectDynamic(value: boolean) ``` Gets whether the light will affect non-lightmapped objects. ### affectLightmapped ```ts get affectLightmapped(): boolean set affectLightmapped(value: boolean) ``` Gets whether the light will affect lightmapped objects. ### affectSpecularity ```ts get affectSpecularity(): boolean set affectSpecularity(value: boolean) ``` Gets whether material specularity will be affected by this light. ### bake ```ts get bake(): boolean set bake(value: boolean) ``` Gets whether the light will be rendered into lightmaps. ### bakeArea ```ts 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. ### bakeDir ```ts get bakeDir(): boolean set bakeDir(value: boolean) ``` Gets whether the light's direction will contribute to directional lightmaps. ### bakeNumSamples ```ts get bakeNumSamples(): number set bakeNumSamples(value: number) ``` Gets the number of samples used to bake this light into the lightmap. ### cascadeBlend ```ts get cascadeBlend(): number set cascadeBlend(value: number) ``` Gets the blend factor for cascaded shadow maps. ### cascadeDistribution ```ts get cascadeDistribution(): number set cascadeDistribution(value: number) ``` Gets the distribution of subdivision of the camera frustum for individual shadow cascades. ### castShadows ```ts get castShadows(): boolean set castShadows(value: boolean) ``` Gets whether the light will cast shadows. ### color ```ts get color(): Readonly set color(value: Readonly) ``` Gets the color of the light. Use the setter to update the color. ### cookie ```ts get cookie(): Texture | null set cookie(value: Texture | null) ``` Gets the texture to be used as the cookie for this light. ### cookieAngle ```ts get cookieAngle(): number set cookieAngle(value: number) ``` Gets the angle for spotlight cookie rotation (in degrees). ### cookieAsset ```ts 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. ### cookieChannel ```ts get cookieChannel(): string set cookieChannel(value: string) ``` Gets the color channels of the cookie texture to use. ### cookieFalloff ```ts get cookieFalloff(): boolean set cookieFalloff(value: boolean) ``` Gets whether normal spotlight falloff is active when a cookie texture is set. ### cookieIntensity ```ts get cookieIntensity(): number set cookieIntensity(value: number) ``` Gets the cookie texture intensity. ### cookieOffset ```ts get cookieOffset(): Vec2 | null set cookieOffset(value: Vec2 | null) ``` Gets the spotlight cookie position offset. ### cookieScale ```ts get cookieScale(): Vec2 | null set cookieScale(value: Vec2 | null) ``` Gets the spotlight cookie scale. ### falloffMode ```ts get falloffMode(): number set falloffMode(value: number) ``` Gets the fall off mode for the light. ### innerConeAngle ```ts 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. ### intensity ```ts get intensity(): number set intensity(value: number) ``` Gets the brightness of the light. ### isStatic ```ts get isStatic(): boolean set isStatic(value: boolean) ``` Gets whether the light ever moves. ### layers ```ts get layers(): readonly number[] set layers(value: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this light should belong. ### luminance ```ts get luminance(): number set luminance(value: number) ``` Gets the physically-based luminance. ### mask ```ts get mask(): number set mask(value: number) ``` Gets the mask to determine which [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s are lit by this light. ### normalOffsetBias ```ts get normalOffsetBias(): number set normalOffsetBias(value: number) ``` Gets the normal offset depth bias. ### numCascades ```ts get numCascades(): number set numCascades(value: number) ``` Gets the number of shadow cascades. ### outerConeAngle ```ts 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. ### penumbraFalloff ```ts get penumbraFalloff(): number set penumbraFalloff(value: number) ``` Gets the falloff rate for shadow penumbra for contact hardening shadows. ### penumbraSize ```ts get penumbraSize(): number set penumbraSize(value: number) ``` Gets the size of penumbra for contact hardening shadows. ### range ```ts get range(): number set range(value: number) ``` Gets the range of the light. ### shadowBias ```ts get shadowBias(): number set shadowBias(value: number) ``` Get the depth bias for tuning the appearance of the shadow mapping generated by this light. ### shadowBlockerSamples ```ts get shadowBlockerSamples(): number set shadowBlockerSamples(value: number) ``` Gets the number of blocker samples used for contact hardening shadows. ### shadowDistance ```ts get shadowDistance(): number set shadowDistance(value: number) ``` Gets the distance from the viewpoint beyond which shadows are no longer rendered. ### shadowIntensity ```ts get shadowIntensity(): number set shadowIntensity(value: number) ``` Gets the intensity of the shadow darkening. ### shadowResolution ```ts get shadowResolution(): number set shadowResolution(value: number) ``` Gets the size of the texture used for the shadow map. ### shadowSamples ```ts get shadowSamples(): number set shadowSamples(value: number) ``` Gets the number of shadow samples used for soft shadows. ### shadowType ```ts get shadowType(): number set shadowType(value: number) ``` Gets the type of shadows being rendered by this light. ### shadowUpdateMode ```ts get shadowUpdateMode(): number set shadowUpdateMode(value: number) ``` Gets the shadow update mode. ### shadowUpdateOverrides ```ts get shadowUpdateOverrides(): number[] | null set shadowUpdateOverrides(values: number[] | null) ``` Gets an array of SHADOWUPDATE_ settings per shadow cascade. ### shape ```ts get shape(): number set shape(value: number) ``` Gets the light source shape. ### type ```ts get type(): string set type(value: string) ``` Gets the type of the light. ### volumetricScattering ```ts get volumetricScattering(): number set volumetricScattering(value: number) ``` Gets the multiplier of the light's contribution to the volumetric fog. ### vsmBias ```ts get vsmBias(): number set vsmBias(value: number) ``` Gets the VSM bias value. ### vsmBlurMode ```ts get vsmBlurMode(): number set vsmBlurMode(value: number) ``` Gets the blurring mode for variance shadow maps. ### vsmBlurSize ```ts get vsmBlurSize(): number set vsmBlurSize(value: number) ``` Gets the number of samples used for blurring a variance shadow map. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LightComponentSystem.md # LightComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/light/system.js#L34 Manages the [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md)s of an application. Reach it through `app.systems.light`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LightingParams.md # LightingParams Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/lighting/lighting-params.js#L11 Lighting parameters, allow configuration of the global lighting parameters. For details see [Clustered Lighting](https://developer.playcanvas.com/user-manual/graphics/lighting/clustered-lighting/). ## Properties ### atlasSplit ```ts 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](https://developer.playcanvas.com/user-manual/graphics/lighting/clustered-lighting/#configuring-atlas). ### debugLayer ```ts 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. ## Accessors ### areaLightsEnabled ```ts get areaLightsEnabled(): boolean set areaLightsEnabled(value: boolean) ``` Gets whether clustered lighting supports area lights. ### cells ```ts get cells(): Vec3 set cells(value: Vec3) ``` Gets the number of cells along each world space axis the space containing lights is subdivided into. ### cookieAtlasResolution ```ts get cookieAtlasResolution(): number set cookieAtlasResolution(value: number) ``` Gets the resolution of the atlas texture storing all non-directional cookie textures. ### cookiesEnabled ```ts get cookiesEnabled(): boolean set cookiesEnabled(value: boolean) ``` Gets whether clustered lighting supports cookie textures. ### maxLights ```ts get maxLights(): number set maxLights(value: number) ``` Gets the maximum number of lights the clustered lighting can use in a single frame. ### maxLightsPerCell ```ts get maxLightsPerCell(): number set maxLightsPerCell(value: number) ``` Gets the maximum number of lights a cell can store. ### shadowAtlasResolution ```ts get shadowAtlasResolution(): number set shadowAtlasResolution(value: number) ``` Gets the resolution of the atlas texture storing all non-directional shadow textures. ### shadowsEnabled ```ts get shadowsEnabled(): boolean set shadowsEnabled(value: boolean) ``` Gets whether clustered lighting supports shadow casting. ### shadowType ```ts get shadowType(): number set shadowType(value: number) ``` Gets the type of shadow filtering used by all shadows. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Lightmapper.md # Lightmapper Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/lightmapper/lightmapper.js#L66 The lightmapper is used to bake scene lights into textures. ## Methods ### bake ```ts bake(nodes: Entity[] | null, mode?: number): void ``` Generates and applies the lightmaps. **Parameters** - `nodes` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)`[] | 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: - [BAKE_COLOR](https://api.playcanvas.com/engine/variables/BAKE_COLOR.md): single color lightmap - [BAKE_COLORDIR](https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md): single color lightmap + dominant light direction (used for bump/specular) Only lights with bakeDir=true will be used for generating the dominant light direction. Defaults to [BAKE_COLORDIR](https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LitShaderOptions.md # LitShaderOptions Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/programs/lit-shader-options.js#L20 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](https://api.playcanvas.com/engine/classes/StandardMaterial.md) 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](https://api.playcanvas.com/engine/classes/StandardMaterial.md) 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](https://api.playcanvas.com/engine/classes/StandardMaterial.md#onupdateshader). ## Properties ### alphaTest ```ts alphaTest: boolean = false ``` Enable alpha testing. See [Material#alphaTest](https://api.playcanvas.com/engine/classes/Material.md#alphatest). ### alphaToCoverage ```ts alphaToCoverage: boolean = false ``` Enable alpha to coverage. See [Material#alphaToCoverage](https://api.playcanvas.com/engine/classes/Material.md#alphatocoverage). ### ambientSH ```ts ambientSH: boolean = false ``` If ambient spherical harmonics are used. Ambient SH replace prefiltered cubemap ambient on certain platforms (mostly Android) for performance reasons. ### ambientSource ```ts ambientSource: string = 'constant' ``` One of "ambientSH", "envAtlas", "constant". ### blendType ```ts blendType: number = BLEND_NONE ``` The value of [Material#blendType](https://api.playcanvas.com/engine/classes/Material.md#blendtype). ### cubeMapProjection ```ts cubeMapProjection: number = 0 ``` The value of [StandardMaterial#cubeMapProjection](https://api.playcanvas.com/engine/classes/StandardMaterial.md#cubemapprojection). ### fog ```ts fog: string = FOG_NONE ``` The type of fog being applied in the shader. See [Scene#fog](https://api.playcanvas.com/engine/classes/Scene.md#fog) for the list of possible values. ### fresnelModel ```ts fresnelModel: number = 0 ``` The value of [StandardMaterial#fresnelModel](https://api.playcanvas.com/engine/classes/StandardMaterial.md#fresnelmodel). ### gamma ```ts gamma: number = GAMMA_NONE ``` The type of gamma correction being applied in the shader. See [CameraComponent#gammaCorrection](https://api.playcanvas.com/engine/classes/CameraComponent.md#gammacorrection) for the list of possible values. ### linearDepth ```ts linearDepth: boolean = false ``` Make vLinearDepth available in the shader. ### occludeDirect ```ts occludeDirect: boolean = false ``` The value of [StandardMaterial#occludeDirect](https://api.playcanvas.com/engine/classes/StandardMaterial.md#occludedirect). ### occludeSpecular ```ts occludeSpecular: number = 0 ``` The value of [StandardMaterial#occludeSpecular](https://api.playcanvas.com/engine/classes/StandardMaterial.md#occludespecular). ### occludeSpecularFloat ```ts occludeSpecularFloat: boolean = false ``` Defines if [StandardMaterial#occludeSpecularIntensity](https://api.playcanvas.com/engine/classes/StandardMaterial.md#occludespecularintensity) constant should affect specular occlusion. ### opacityDither ```ts opacityDither: string = DITHER_NONE ``` Enable opacity dithering. See [StandardMaterial#opacityDither](https://api.playcanvas.com/engine/classes/StandardMaterial.md#opacitydither). ### opacityFadesSpecular ```ts opacityFadesSpecular: boolean = false ``` Enable specular fade. See [StandardMaterial#opacityFadesSpecular](https://api.playcanvas.com/engine/classes/StandardMaterial.md#opacityfadesspecular). ### opacityShadowDither ```ts opacityShadowDither: string = DITHER_NONE ``` Enable opacity shadow dithering. See [StandardMaterial#opacityShadowDither](https://api.playcanvas.com/engine/classes/StandardMaterial.md#opacityshadowdither). ### reflectionSource ```ts reflectionSource: string = REFLECTIONSRC_NONE ``` One of REFLECTIONSRC_*** constants. ### shaderChunks ```ts shaderChunks: ShaderChunks | null = null ``` Custom shader chunks that will replace default ones. ### shadowCatcher ```ts shadowCatcher: boolean = false ``` Shader outputs the accumulated shadow value, used for shadow catcher materials. ### skyboxIntensity ```ts skyboxIntensity: number = 1.0 ``` Skybox intensity factor. ### ssao ```ts ssao: boolean = false ``` Apply SSAO during the lighting. ### toneMap ```ts toneMap: number = -1 ``` The type of tone mapping being applied in the shader. See [CameraComponent#toneMapping](https://api.playcanvas.com/engine/classes/CameraComponent.md#tonemapping) for the list of possible values. ### twoSidedLighting ```ts twoSidedLighting: boolean = false ``` The value of [StandardMaterial#twoSidedLighting](https://api.playcanvas.com/engine/classes/StandardMaterial.md#twosidedlighting). ### useCubeMapRotation ```ts useCubeMapRotation: boolean = false ``` If cube map rotation is enabled. ### useInstancing ```ts useInstancing: boolean = false ``` If hardware instancing compatible shader should be generated. Transform is read from per-instance [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md) instead of shader's uniforms. ### useMetalness ```ts useMetalness: boolean = false ``` The value of [StandardMaterial#useMetalness](https://api.playcanvas.com/engine/classes/StandardMaterial.md#usemetalness). ### useMorphNormal ```ts useMorphNormal: boolean = false ``` If morphing code should be generated to morph normals. ### useMorphPosition ```ts useMorphPosition: boolean = false ``` If morphing code should be generated to morph positions. ### userAttributes ```ts userAttributes: {} = {} ``` Object containing a map of user defined vertex attributes to attached shader semantics. ### useRefraction ```ts useRefraction: boolean = false ``` If refraction is used. ### useSceneEnv ```ts 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 ```ts useSpecular: boolean = false ``` If any specular or reflections are needed at all. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Material.md # Material Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/material.js#L108 A material determines how a particular [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) 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](https://api.playcanvas.com/engine/classes/ShaderMaterial.md) and [StandardMaterial](https://api.playcanvas.com/engine/classes/StandardMaterial.md) can be used to define materials for rendering. Choose [StandardMaterial](https://api.playcanvas.com/engine/classes/StandardMaterial.md) for a physically based surface described by properties and textures, and [ShaderMaterial](https://api.playcanvas.com/engine/classes/ShaderMaterial.md) to supply your own vertex and fragment shaders. Both share the state defined here: blending through [blendType](https://api.playcanvas.com/engine/classes/Material.md#blendtype), depth behavior through [depthTest](https://api.playcanvas.com/engine/classes/Material.md#depthtest), [depthWrite](https://api.playcanvas.com/engine/classes/Material.md#depthwrite) and [depthFunc](https://api.playcanvas.com/engine/classes/Material.md#depthfunc), face culling through [cull](https://api.playcanvas.com/engine/classes/Material.md#cull), alpha testing through [alphaTest](https://api.playcanvas.com/engine/classes/Material.md#alphatest), shader uniforms through [setParameter](https://api.playcanvas.com/engine/classes/Material.md#setparameter), and preprocessor defines through [setDefine](https://api.playcanvas.com/engine/classes/Material.md#setdefine). [getShaderChunks](https://api.playcanvas.com/engine/classes/Material.md#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](https://api.playcanvas.com/engine/classes/Material.md#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](https://api.playcanvas.com/engine/classes/Material.md#clone) makes an independent copy. **Example** ```ts // Make a material additive and double-sided, then apply the change material.blendType = BLEND_ADDITIVE; material.cull = CULLFACE_NONE; material.update(); ``` ## Constructors ### constructor ```ts protected new Material() ``` ## Properties ### alphaToCoverage ```ts 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md), the default HDR format used by [CameraFrame](https://api.playcanvas.com/engine/classes/CameraFrame.md), has no alpha channel. ### cull ```ts cull: number = CULLFACE_BACK ``` Controls how triangles are culled based on their face direction with respect to the viewpoint. Can be: - [CULLFACE_NONE](https://api.playcanvas.com/engine/variables/CULLFACE_NONE.md): Do not cull triangles based on face direction. - [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md): Cull the back faces of triangles (do not render triangles facing away from the view point). - [CULLFACE_FRONT](https://api.playcanvas.com/engine/variables/CULLFACE_FRONT.md): Cull the front faces of triangles (do not render triangles facing towards the view point). Defaults to [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md). ### frontFace ```ts frontFace: number = FRONTFACE_CCW ``` Controls whether polygons are front- or back-facing by setting a winding orientation. Can be: - [FRONTFACE_CW](https://api.playcanvas.com/engine/variables/FRONTFACE_CW.md): The clock-wise winding. - [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md): The counterclockwise winding. Defaults to [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md). ### name ```ts name: string = 'Untitled' ``` The name of the material. ### stencilBack ```ts stencilBack: StencilParameters | null = null ``` Stencil parameters for back faces (default is null). ### stencilFront ```ts stencilFront: StencilParameters | null = null ``` Stencil parameters for front faces (default is null). ### userId ```ts 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. ## Accessors ### alphaTest ```ts get alphaTest(): number set alphaTest(value: number) ``` Gets the alpha test reference value. ### alphaWrite ```ts get alphaWrite(): boolean set alphaWrite(value: boolean) ``` Gets whether the alpha channel is written to the color buffer. ### blendState ```ts get blendState(): Readonly set blendState(value: Readonly) ``` Gets the blend state for this material. Use the setter to update transparency and sort state. ### blendType ```ts get blendType(): number set blendType(type: number) ``` Gets the blend mode for this material. ### blueWrite ```ts get blueWrite(): boolean set blueWrite(value: boolean) ``` Gets whether the blue channel is written to the color buffer. ### depthBias ```ts get depthBias(): number set depthBias(value: number) ``` Gets the offset for the output depth buffer value. ### depthFunc ```ts get depthFunc(): number set depthFunc(value: number) ``` Gets the depth test function. ### depthState ```ts get depthState(): DepthState set depthState(value: DepthState) ``` Gets the depth state. ### depthTest ```ts get depthTest(): boolean set depthTest(value: boolean) ``` Gets whether depth testing is enabled. ### depthWrite ```ts get depthWrite(): boolean set depthWrite(value: boolean) ``` Gets whether depth writing is enabled. ### flatShading ```ts get flatShading(): boolean set flatShading(value: boolean) ``` Gets whether flat shading is enabled. ### greenWrite ```ts get greenWrite(): boolean set greenWrite(value: boolean) ``` Gets whether the green channel is written to the color buffer. ### redWrite ```ts get redWrite(): boolean set redWrite(value: boolean) ``` Gets whether the red channel is written to the color buffer. ### shaderChunksVersion ```ts get shaderChunksVersion(): string set shaderChunksVersion(value: string) ``` Returns the version of the shader chunks. ### slopeDepthBias ```ts 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. ## Methods ### _markLayoutDirty ```ts 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. ### _markPropertyModified ```ts 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](https://api.playcanvas.com/engine/classes/Material.md#update). **Parameters** - `property` (`MaterialProperty`): The property. ### _markPropertyMutable ```ts 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](https://api.playcanvas.com/engine/classes/Material.md#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 ```ts clone(): Material ``` Clone a material. **Returns** [`Material`](https://api.playcanvas.com/engine/classes/Material.md): A newly cloned material. ### copy ```ts copy(source: Material): Material ``` Copy a material. **Parameters** - `source` ([`Material`](https://api.playcanvas.com/engine/classes/Material.md)): The material to copy. **Returns** [`Material`](https://api.playcanvas.com/engine/classes/Material.md): The destination material. ### deleteParameter ```ts deleteParameter(name: string): void ``` Deletes a shader parameter on a material. **Parameters** - `name` (`string`): The name of the parameter to delete. ### destroy ```ts 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 ```ts 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 ```ts 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 ```ts 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: - If GLSL chunks are provided, they are used directly. On the WebGPU platform: - If WGSL chunks are provided, they are used directly. - If only GLSL chunks are provided, a GLSL shader is generated and then transpiled to WGSL, which is less efficient. 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: ```javascript 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](https://api.playcanvas.com/engine/variables/SHADERLANGUAGE_GLSL.md). **Returns** [`ShaderChunkMap`](https://api.playcanvas.com/engine/classes/ShaderChunkMap.md): - The shader chunks for the specified shader language. ### setDefine ```ts 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. ```javascript material.setDefine('MY_DEFINE', true); // call update to apply the changes, which will recompile the shader using the new define material.update(); ``` ### setParameter ```ts setParameter(name: string, data: number | number[] | ArrayBufferView | Texture | StorageBuffer): void ``` Sets a shader parameter on a material. **Parameters** - `name` (`string`): The name of the parameter to set. - `data` (`number | number[] | ArrayBufferView |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `|` [`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md)): The value for the specified parameter. ### update ```ts 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: - Modified material properties require a different shader variant (e.g., enabling/disabling textures or other properties that affect shader generation) - Material-specific shader chunks (from [getShaderChunks](https://api.playcanvas.com/engine/classes/Material.md#getshaderchunks)) have been modified - Global shader chunks (from [ShaderChunks.get](https://api.playcanvas.com/engine/classes/ShaderChunks.md#get)) have been modified - Material defines have been changed 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Mesh.md # Mesh Class · extends [`RefCountedObject`](https://api.playcanvas.com/engine/classes/RefCountedObject.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh.js#L203 A graphical primitive. The mesh is defined by a [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md) and an optional [IndexBuffer](https://api.playcanvas.com/engine/classes/IndexBuffer.md). 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](https://api.playcanvas.com/engine/classes/Material.md) in a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) and give that instance to a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) or a [Layer](https://api.playcanvas.com/engine/classes/Layer.md); one mesh can back any number of instances. [Mesh.fromGeometry](https://api.playcanvas.com/engine/classes/Mesh.md#fromgeometry) builds a mesh from a [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) such as [BoxGeometry](https://api.playcanvas.com/engine/classes/BoxGeometry.md) in one call. Meshes are reference counted: every [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) holds a reference to its mesh, so call [destroy](https://api.playcanvas.com/engine/classes/Mesh.md#destroy) on a mesh you created only once no instance uses it. ## Mesh APIs There are two ways a mesh can be generated or updated. ### Simple Mesh API [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) class provides interfaces such as [setPositions](https://api.playcanvas.com/engine/classes/Mesh.md#setpositions) and [setUvs](https://api.playcanvas.com/engine/classes/Mesh.md#setuvs) that provide a simple way to provide vertex and index data for the Mesh, and hiding the complexity of creating the [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md). 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. ```javascript 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. ```javascript 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. - [https://playcanvas.github.io/#graphics/mesh-decals](https://playcanvas.github.io/#graphics/mesh-decals) - [https://playcanvas.github.io/#graphics/mesh-deformation](https://playcanvas.github.io/#graphics/mesh-deformation) - [https://playcanvas.github.io/#graphics/mesh-generation](https://playcanvas.github.io/#graphics/mesh-generation) - [https://playcanvas.github.io/#graphics/point-cloud-simulation](https://playcanvas.github.io/#graphics/point-cloud-simulation) ### Update Vertex and Index buffers 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](https://api.playcanvas.com/engine/classes/VertexBuffer.md), [IndexBuffer](https://api.playcanvas.com/engine/classes/IndexBuffer.md) and [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md) for details. ## Constructors ### constructor ```ts new Mesh(graphicsDevice: GraphicsDevice, options?: object) ``` Create a new Mesh instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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. ## Properties ### indexBuffer ```ts 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 [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s with a `renderStyle` property set to [RENDERSTYLE_SOLID](https://api.playcanvas.com/engine/variables/RENDERSTYLE_SOLID.md). The second index buffer in the array is used if `renderStyle` is set to [RENDERSTYLE_WIREFRAME](https://api.playcanvas.com/engine/variables/RENDERSTYLE_WIREFRAME.md). ### primitive ```ts 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: - [PRIMITIVE_POINTS](https://api.playcanvas.com/engine/variables/PRIMITIVE_POINTS.md) - [PRIMITIVE_LINES](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINES.md) - [PRIMITIVE_LINELOOP](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINELOOP.md) - [PRIMITIVE_LINESTRIP](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINESTRIP.md) - [PRIMITIVE_TRIANGLES](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIANGLES.md) - [PRIMITIVE_TRISTRIP](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRISTRIP.md) - [PRIMITIVE_TRIFAN](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIFAN.md) - `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 ```ts skin: Skin | null = null ``` The skin data (if any) that drives skinned mesh animations for this mesh. ### vertexBuffer ```ts vertexBuffer: VertexBuffer = null ``` The vertex buffer holding the vertex data of the mesh. ## Accessors ### aabb ```ts get aabb(): BoundingBox set aabb(aabb: BoundingBox) ``` Gets the axis-aligned bounding box for the object space vertices of this mesh. ### morph ```ts get morph(): Morph | null set morph(morph: Morph | null) ``` Gets the morph data that drives morph target animations for this mesh. ## Methods ### clear ```ts clear(verticesDynamic?: boolean, indicesDynamic?: boolean, maxVertices?: number, maxIndices?: number): void ``` Clears the mesh of existing vertices and indices and resets the [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md) associated with the mesh. This call is typically followed by calls to methods such as [setPositions](https://api.playcanvas.com/engine/classes/Mesh.md#setpositions), [setVertexStream](https://api.playcanvas.com/engine/classes/Mesh.md#setvertexstream) or [setIndices](https://api.playcanvas.com/engine/classes/Mesh.md#setindices) and finally [update](https://api.playcanvas.com/engine/classes/Mesh.md#update) to rebuild the mesh, allowing different [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md). **Parameters** - `verticesDynamic` (`boolean`, optional): Indicates the [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md) should be created with [BUFFER_DYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md) usage. If not specified, [BUFFER_STATIC](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md) is used. - `indicesDynamic` (`boolean`, optional): Indicates the [IndexBuffer](https://api.playcanvas.com/engine/classes/IndexBuffer.md) should be created with [BUFFER_DYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md) usage. If not specified, [BUFFER_STATIC](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md) is used. - `maxVertices` (`number`, optional, default `0`): A [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md) 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](https://api.playcanvas.com/engine/classes/IndexBuffer.md) 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 ```ts destroy(): void ``` Destroys the [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md) and [IndexBuffer](https://api.playcanvas.com/engine/classes/IndexBuffer.md)s associated with the mesh. This is normally called by [Model#destroy](https://api.playcanvas.com/engine/classes/Model.md#destroy) and does not need to be called manually. ### getColors ```ts getColors(colors: NumericArray): number ``` Gets the vertex color data. **Parameters** - `colors` ([`NumericArray`](https://api.playcanvas.com/engine/types/NumericArray.md)): 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 ```ts getIndices(indices: number[] | Uint8Array | Uint16Array | Uint32Array): number ``` Gets the index data. **Parameters** - `indices` (`number[] | Uint8Array | Uint16Array | Uint32Array`): 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 ```ts getNormals(normals: NumericArray): number ``` Gets the vertex normals data. **Parameters** - `normals` ([`NumericArray`](https://api.playcanvas.com/engine/types/NumericArray.md)): 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 ```ts getPositions(positions: NumericArray): number ``` Gets the vertex positions data. **Parameters** - `positions` ([`NumericArray`](https://api.playcanvas.com/engine/types/NumericArray.md)): 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 ```ts getUvs(channel: number, uvs: NumericArray): number ``` Gets the vertex uv data. **Parameters** - `channel` (`number`): The uv channel in [0..7] range. - `uvs` ([`NumericArray`](https://api.playcanvas.com/engine/types/NumericArray.md)): 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 ```ts 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](https://api.playcanvas.com/engine/classes/VertexFormat.md). - `data` ([`NumericArray`](https://api.playcanvas.com/engine/types/NumericArray.md)): 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 ```ts setColors(colors: ArrayLike, componentCount?: number, numVertices?: number): void ``` Sets the vertex color array. Colors are stored using [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) format, which is useful for HDR colors. **Parameters** - `colors` (`ArrayLike`): 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 ```ts setColors32(colors: ArrayLike, numVertices?: number): void ``` Sets the vertex color array. Colors are stored using [TYPE_UINT8](https://api.playcanvas.com/engine/variables/TYPE_UINT8.md) 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`): 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 ```ts setIndices(indices: number[] | Uint8Array | Uint16Array | Uint32Array, 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 | Uint16Array | Uint32Array`): 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 ```ts setNormals(normals: ArrayLike, componentCount?: number, numVertices?: number): void ``` Sets the vertex normals array. Normals are stored using [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) format. **Parameters** - `normals` (`ArrayLike`): 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 ```ts setPositions(positions: ArrayLike, componentCount?: number, numVertices?: number): void ``` Sets the vertex positions array. Vertices are stored using [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) format. **Parameters** - `positions` (`ArrayLike`): 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 ```ts setUvs(channel: number, uvs: ArrayLike, componentCount?: number, numVertices?: number): void ``` Sets the vertex uv array. Uvs are stored using [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) format. **Parameters** - `channel` (`number`): The uv channel in [0..7] range. - `uvs` (`ArrayLike`): 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 ```ts setVertexStream(semantic: string, data: ArrayLike, 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](https://api.playcanvas.com/engine/classes/VertexFormat.md). - `data` (`ArrayLike`): 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](https://api.playcanvas.com/engine/classes/VertexBuffer.md), see TYPE_* in [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md). When not specified, [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) 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 ```ts update(primitiveType?: number, updateBoundingBox?: boolean): void ``` Applies any changes to vertex stream and indices to mesh. This allocates or reallocates [vertexBuffer](https://api.playcanvas.com/engine/classes/Mesh.md#vertexbuffer) or [indexBuffer](https://api.playcanvas.com/engine/classes/Mesh.md#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: - [PRIMITIVE_POINTS](https://api.playcanvas.com/engine/variables/PRIMITIVE_POINTS.md) - [PRIMITIVE_LINES](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINES.md) - [PRIMITIVE_LINELOOP](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINELOOP.md) - [PRIMITIVE_LINESTRIP](https://api.playcanvas.com/engine/variables/PRIMITIVE_LINESTRIP.md) - [PRIMITIVE_TRIANGLES](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIANGLES.md) - [PRIMITIVE_TRISTRIP](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRISTRIP.md) - [PRIMITIVE_TRIFAN](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIFAN.md) Defaults to [PRIMITIVE_TRIANGLES](https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIANGLES.md) 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](https://api.playcanvas.com/engine/classes/Mesh.md#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. ### fromGeometry ```ts static fromGeometry(graphicsDevice: GraphicsDevice, geometry: Geometry, options?: object): Mesh ``` Create a new Mesh instance from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) object. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to manage this mesh. - `geometry` ([`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md)): 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`](https://api.playcanvas.com/engine/classes/Mesh.md): A new mesh. ## Inherited from [RefCountedObject](https://api.playcanvas.com/engine/classes/RefCountedObject.md) - `get refCount(): number` - `decRefCount(): void` - `incRefCount(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MeshInstance.md # MeshInstance Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh-instance.js#L285 An instance of a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md). 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](https://api.playcanvas.com/engine/classes/Mesh.md), a [Material](https://api.playcanvas.com/engine/classes/Material.md) and the [GraphNode](https://api.playcanvas.com/engine/classes/GraphNode.md) whose world transform places it, and it is drawn only once it belongs to a [Layer](https://api.playcanvas.com/engine/classes/Layer.md). Components such as [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) 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](https://api.playcanvas.com/engine/classes/RenderComponent.md#meshinstances) or by adding it to a layer directly with [Layer#addMeshInstances](https://api.playcanvas.com/engine/classes/Layer.md#addmeshinstances). Per-instance rendering state lives here rather than on the shared mesh or material: [visible](https://api.playcanvas.com/engine/classes/MeshInstance.md#visible), [castShadow](https://api.playcanvas.com/engine/classes/MeshInstance.md#castshadow) and `receiveShadow`, [cull](https://api.playcanvas.com/engine/classes/MeshInstance.md#cull) for frustum culling, [drawOrder](https://api.playcanvas.com/engine/classes/MeshInstance.md#draworder) for manual sorting, and [setParameter](https://api.playcanvas.com/engine/classes/MeshInstance.md#setparameter) for shader uniforms that override the material's. [aabb](https://api.playcanvas.com/engine/classes/MeshInstance.md#aabb) is the world-space bounds derived from the mesh bounds and the node's transform, and can be assigned to override it. ### Instancing Hardware instancing lets the GPU draw many copies of the same geometry with a single draw call. Use [setInstancing](https://api.playcanvas.com/engine/classes/MeshInstance.md#setinstancing) to attach a vertex buffer that holds per-instance data (for example a mat4 world-matrix for every instance). Set [instancingCount](https://api.playcanvas.com/engine/classes/MeshInstance.md#instancingcount) to control how many instances are rendered. Passing `null` to [setInstancing](https://api.playcanvas.com/engine/classes/MeshInstance.md#setinstancing) disables instancing once again. ```javascript // vb is a vertex buffer with one 4×4 matrix per instance meshInstance.setInstancing(vb); meshInstance.instancingCount = numInstances; ``` The default matrix format, [VertexFormat.getDefaultInstancingFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md#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** - [graphics/instancing-basic](https://playcanvas.github.io/#graphics/instancing-basic) - [graphics/instancing-custom](https://playcanvas.github.io/#graphics/instancing-custom) ### GPU-Driven Indirect Rendering (WebGPU Only) 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: ```javascript const slot = app.graphicsDevice.getIndirectDrawSlot(count); meshInstance.setIndirect(null, slot, count); // first arg can be a CameraComponent or null ``` **Example** - [compute/indirect-draw](https://playcanvas.github.io/#compute/indirect-draw) ### Multi-draw 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](https://api.playcanvas.com/engine/classes/MeshInstance.md#setmultidraw) to allocate a [DrawCommands](https://api.playcanvas.com/engine/classes/DrawCommands.md) container, fill it with sub-draws using [DrawCommands#add](https://api.playcanvas.com/engine/classes/DrawCommands.md#add) and finalize with [DrawCommands#update](https://api.playcanvas.com/engine/classes/DrawCommands.md#update) whenever the data changes. Support: [GraphicsDevice#supportsMultiDraw](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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. ```javascript // 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); ``` ### Precedence When draw commands (indirect or multi-draw, see [setIndirect](https://api.playcanvas.com/engine/classes/MeshInstance.md#setindirect) and [setMultiDraw](https://api.playcanvas.com/engine/classes/MeshInstance.md#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](https://api.playcanvas.com/engine/classes/MeshInstance.md#instancingcount) is ignored. In this case setting [instancingCount](https://api.playcanvas.com/engine/classes/MeshInstance.md#instancingcount) to 0 does not skip rendering. [instancingCount](https://api.playcanvas.com/engine/classes/MeshInstance.md#instancingcount) only takes effect for plain hardware instancing, when no draw commands are bound. ## Constructors ### constructor ```ts new MeshInstance(mesh: Mesh, material: Material, node?: GraphNode) ``` Create a new MeshInstance instance. **Parameters** - `mesh` ([`Mesh`](https://api.playcanvas.com/engine/classes/Mesh.md)): The graphics mesh to instance. - `material` ([`Material`](https://api.playcanvas.com/engine/classes/Material.md)): The material to use for this mesh instance. - `node` ([`GraphNode`](https://api.playcanvas.com/engine/classes/GraphNode.md), optional, default `null`): The graph node defining the transform for this instance. This parameter is optional when used with [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and will use the node the component is attached to. **Example** ```ts // 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); ``` ## Properties ### castShadow ```ts 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](https://api.playcanvas.com/engine/classes/Layer.md), but allows mesh to be skipped from shadow casting while it is in the list already. Defaults to false. ### cull ```ts cull: boolean = true ``` Controls whether the mesh instance can be culled by frustum culling (see [CameraComponent#frustumCulling](https://api.playcanvas.com/engine/classes/CameraComponent.md#frustumculling)). Defaults to true. ### drawOrder ```ts drawOrder: number = 0 ``` Determines the rendering order of mesh instances. Only used when mesh instances are added to a [Layer](https://api.playcanvas.com/engine/classes/Layer.md) with [Layer#opaqueSortMode](https://api.playcanvas.com/engine/classes/Layer.md#opaquesortmode) or [Layer#transparentSortMode](https://api.playcanvas.com/engine/classes/Layer.md#transparentsortmode) (depending on the material) set to [SORTMODE_MANUAL](https://api.playcanvas.com/engine/variables/SORTMODE_MANUAL.md). ### shaderPassMask ```ts 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](https://api.playcanvas.com/engine/variables/SHADER_FORWARD.md), and indices for custom shader passes are obtained from [CameraComponent#setShaderPass](https://api.playcanvas.com/engine/classes/CameraComponent.md#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** ```ts // 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** ```ts // set the forward (color) pass bit, leaving all other pass bits unchanged meshInstance.shaderPassMask |= (1 << SHADER_FORWARD); ``` **Example** ```ts // 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** ```ts // test whether the forward (color) pass bit is set const forwardBitSet = (meshInstance.shaderPassMask & (1 << SHADER_FORWARD)) !== 0; ``` **Example** ```ts // set every pass bit (the default value) meshInstance.shaderPassMask = 0xFFFFFFFF; ``` ### shadowCascadeMask ```ts shadowCascadeMask: number = SHADOW_CASCADE_ALL ``` Specifies a bitmask that controls which shadow cascades a mesh instance contributes to when rendered with a [LIGHTTYPE_DIRECTIONAL](https://api.playcanvas.com/engine/variables/LIGHTTYPE_DIRECTIONAL.md) light source. This setting is only effective if the [castShadow](https://api.playcanvas.com/engine/classes/MeshInstance.md#castshadow) property is enabled. Defaults to [SHADOW_CASCADE_ALL](https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_ALL.md), which means the mesh casts shadows into all available cascades. ### visible ```ts 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 ```ts visibleThisFrame: boolean = false ``` Read this value in the [Scene.EVENT_POSTCULL](https://api.playcanvas.com/engine/classes/Scene.md#event_postcull) event to determine if the object is actually going to be rendered. ## Accessors ### aabb ```ts get aabb(): BoundingBox set aabb(aabb: BoundingBox) ``` Gets the world space axis-aligned bounding box for this mesh instance. ### calculateSortDistance ```ts get calculateSortDistance(): CalculateSortDistanceCallback | null set calculateSortDistance(calculateSortDistance: CalculateSortDistanceCallback | null) ``` Gets the callback to calculate sort distance. ### drawBucket ```ts get drawBucket(): number set drawBucket(bucket: number) ``` Gets the draw bucket for mesh instance. ### instancingCount ```ts get instancingCount(): number set instancingCount(value: number) ``` Gets the number of instances when using hardware instancing to render the mesh. ### mask ```ts get mask(): number set mask(val: number) ``` Gets the light mask of this mesh instance: which [LightComponent](https://api.playcanvas.com/engine/classes/LightComponent.md)s light it. ### material ```ts get material(): Material | null set material(material: Material | null) ``` Gets the material used by this mesh instance. ### mesh ```ts get mesh(): Mesh | null set mesh(mesh: Mesh | null) ``` Gets the graphics mesh being instanced. ### morphInstance ```ts get morphInstance(): MorphInstance | null set morphInstance(val: MorphInstance | null) ``` Gets the morph instance managing morphing of this mesh instance. ### node ```ts get node(): GraphNode set node(node: GraphNode) ``` Gets the graph node defining the transform for this instance. ### renderStyle ```ts get renderStyle(): number set renderStyle(renderStyle: number) ``` Gets the render style of the mesh instance. ### skinInstance ```ts get skinInstance(): SkinInstance | null set skinInstance(val: SkinInstance | null) ``` Gets the skin instance managing skinning of this mesh instance. ## Methods ### deleteParameter ```ts deleteParameter(name: string): void ``` Deletes a shader parameter on a mesh instance. **Parameters** - `name` (`string`): The name of the parameter to delete. ### getIndirectMetaData ```ts getIndirectMetaData(): Int32Array ``` Retrieves the mesh metadata needed for indirect rendering. **Returns** `Int32Array`: - 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](https://api.playcanvas.com/engine/classes/Mesh.md#primitive), stored in this order: [count, base, baseVertex, 0]. The last value is always zero and is reserved for future use. ### getParameter ```ts 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 ```ts setIndirect(camera: CameraComponent | null, slot: number, count?: number): void ``` Sets the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsindirectdraw)), and ignored on other platforms, where the mesh instance renders as a normal draw call. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md) `| 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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 ```ts setInstancing(vertexBuffer: true | VertexBuffer | null, cull?: boolean): void ``` Sets up [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to be rendered using Hardware Instancing. Note that [instancingCount](https://api.playcanvas.com/engine/classes/MeshInstance.md#instancingcount) is automatically set to the number of vertices of the vertex buffer when it is provided. **Parameters** - `vertexBuffer` (`true |` [`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md) `| 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](https://api.playcanvas.com/engine/classes/MeshInstance.md#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](https://api.playcanvas.com/engine/classes/RenderComponent.md#customaabb) containing all instances. Defaults to false, which means the whole instance is always rendered. ### setMultiDraw ```ts setMultiDraw(camera: CameraComponent | null, maxCount?: number): DrawCommands | undefined ``` Sets the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) 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`](https://api.playcanvas.com/engine/classes/CameraComponent.md) `| 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`](https://api.playcanvas.com/engine/classes/DrawCommands.md) `| undefined`: The commands container to populate with sub-draw commands. ### setParameter ```ts setParameter(name: string, data: number | number[] | Float32Array | 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 |` [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md)): The value for the specified parameter. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Model.md # Model Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/model.js#L16 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. ## Constructors ### constructor ```ts new Model() ``` Creates a new model. **Example** ```ts // Create a new model const model = new Model(); ``` ## Properties ### graph ```ts graph: GraphNode | null = null ``` The root node of the model's graph node hierarchy. ### meshInstances ```ts meshInstances: MeshInstance[] = [] ``` An array of MeshInstances contained in this model. ### morphInstances ```ts morphInstances: MorphInstance[] = [] ``` An array of MorphInstances contained in this model. ### skinInstances ```ts skinInstances: SkinInstance[] = [] ``` An array of SkinInstances contained in this model. ## Methods ### clone ```ts 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`](https://api.playcanvas.com/engine/classes/Model.md): A clone of the specified model. **Example** ```ts const clonedModel = model.clone(); ``` ### destroy ```ts 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 ```ts 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](https://api.playcanvas.com/engine/variables/RENDERSTYLE_WIREFRAME.md). **Example** ```ts model.generateWireframe(); for (let i = 0; i < model.meshInstances.length; i++) { model.meshInstances[i].renderStyle = RENDERSTYLE_WIREFRAME; } ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ModelComponent.md # ModelComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/model/component.js#L54 The ModelComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to render 3D models. The [type](https://api.playcanvas.com/engine/classes/ModelComponent.md#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](https://api.playcanvas.com/engine/classes/Model.md). This can either be created programmatically or loaded from an [Asset](https://api.playcanvas.com/engine/classes/Asset.md). The [Model](https://api.playcanvas.com/engine/classes/Model.md) managed by this component is positioned, rotated, and scaled in world space by the world transformation matrix of the owner [Entity](https://api.playcanvas.com/engine/classes/Entity.md). 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](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#model) property: ```javascript entity.model.type = 'capsule'; // Set the model component's type console.log(entity.model.type); // Get the model component's type and print it ``` ## Properties ### isStatic ```ts isStatic: boolean = false ``` Mark meshes as non-movable (optimization). ## Accessors ### asset ```ts get asset(): number | Asset | null set asset(value: number | Asset | null) ``` Gets the model asset id for the component. ### batchGroupId ```ts get batchGroupId(): number set batchGroupId(value: number) ``` Gets the batch group for the mesh instances in this component (see [BatchGroup](https://api.playcanvas.com/engine/classes/BatchGroup.md)). ### castShadows ```ts get castShadows(): boolean set castShadows(value: boolean) ``` Gets whether attached meshes will cast shadows for lights that have shadow casting enabled. ### castShadowsLightmap ```ts get castShadowsLightmap(): boolean set castShadowsLightmap(value: boolean) ``` Gets whether meshes instances will cast shadows when rendering lightmaps. ### customAabb ```ts 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. ### layers ```ts get layers(): readonly number[] set layers(value: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which the mesh instances belong. ### lightmapped ```ts get lightmapped(): boolean set lightmapped(value: boolean) ``` Gets whether the component is affected by the runtime lightmapper. ### lightmapSizeMultiplier ```ts get lightmapSizeMultiplier(): number set lightmapSizeMultiplier(value: number) ``` Gets the lightmap resolution multiplier. ### mapping ```ts get mapping(): Readonly> set mapping(value: Readonly>) ``` Gets the dictionary that holds material overrides for each mesh instance. ### material ```ts get material(): Material set material(value: Material) ``` Gets the [Material](https://api.playcanvas.com/engine/classes/Material.md) that will be used to render the model. ### materialAsset ```ts get materialAsset(): number | Asset | null set materialAsset(value: number | Asset | null) ``` Gets the material [Asset](https://api.playcanvas.com/engine/classes/Asset.md) that will be used to render the component. ### meshInstances ```ts 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. ### model ```ts 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. ### receiveShadows ```ts get receiveShadows(): boolean set receiveShadows(value: boolean) ``` Gets whether shadows will be cast on attached meshes. ### type ```ts 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. ## Methods ### hide ```ts hide(): void ``` Stop rendering model without removing it from the scene hierarchy. This method sets the [MeshInstance#visible](https://api.playcanvas.com/engine/classes/MeshInstance.md#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** ```ts 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 ```ts show(): void ``` Enable rendering of the model if hidden using [hide](https://api.playcanvas.com/engine/classes/ModelComponent.md#hide). This method sets all the [MeshInstance#visible](https://api.playcanvas.com/engine/classes/MeshInstance.md#visible) property on all mesh instances to true. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ModelComponentSystem.md # ModelComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/model/system.js#L53 Allows an Entity to render a model or a primitive shape like a box, capsule, sphere, cylinder, cone etc. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Morph.md # Morph Class · extends [`RefCountedObject`](https://api.playcanvas.com/engine/classes/RefCountedObject.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph.js#L25 Contains a list of [MorphTarget](https://api.playcanvas.com/engine/classes/MorphTarget.md)s, a combined delta AABB and some associated data. ## Constructors ### constructor ```ts new Morph(targets: MorphTarget[], graphicsDevice: GraphicsDevice, options?: object) ``` Create a new Morph instance. **Parameters** - `targets` ([`MorphTarget`](https://api.playcanvas.com/engine/classes/MorphTarget.md)`[]`): A list of morph targets. - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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. ## Properties ### preferHighPrecision ```ts preferHighPrecision: boolean ``` ## Accessors ### targets ```ts get targets(): MorphTarget[] ``` Gets the array of morph targets. ## Methods ### destroy ```ts destroy(): void ``` Frees video memory allocated by this object. ## Inherited from [RefCountedObject](https://api.playcanvas.com/engine/classes/RefCountedObject.md) - `get refCount(): number` - `decRefCount(): void` - `incRefCount(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MorphInstance.md # MorphInstance Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph-instance.js#L20 An instance of [Morph](https://api.playcanvas.com/engine/classes/Morph.md). Contains weights to assign to every [MorphTarget](https://api.playcanvas.com/engine/classes/MorphTarget.md), manages selection of active morph targets. ## Constructors ### constructor ```ts new MorphInstance(morph: Morph) ``` Create a new MorphInstance instance. **Parameters** - `morph` ([`Morph`](https://api.playcanvas.com/engine/classes/Morph.md)): The [Morph](https://api.playcanvas.com/engine/classes/Morph.md) to instance. ## Properties ### morph ```ts morph: Morph ``` The morph with its targets, which is being instanced. ## Methods ### clone ```ts clone(): MorphInstance ``` Clones a MorphInstance. The returned clone uses the same [Morph](https://api.playcanvas.com/engine/classes/Morph.md) and weights are set to defaults. **Returns** [`MorphInstance`](https://api.playcanvas.com/engine/classes/MorphInstance.md): A clone of the specified MorphInstance. ### destroy ```ts destroy(): void ``` Frees video memory allocated by this object. ### getWeight ```ts 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 ```ts 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 ```ts update(): void ``` Selects active morph targets and prepares morph for rendering. Called automatically by renderer. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MorphTarget.md # MorphTarget Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph-target.js#L11 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. ## Constructors ### constructor ```ts new MorphTarget(options: object, ...args: any[]) ``` Create a new MorphTarget instance. **Parameters** - `options` (`object`): Object for passing optional arguments. - `options.aabb` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md), 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`, optional): An array of 3-dimensional vertex normal offsets. - `options.deltaPositions` (`ArrayLike`): 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[]`) ## Properties ### used ```ts used: boolean = false ``` A used flag. A morph target can be used / owned by the Morph class only one time. ## Accessors ### defaultWeight ```ts get defaultWeight(): number ``` Gets the default weight of the morph target. ### name ```ts get name(): string ``` Gets the name of the morph target. ## Methods ### clone ```ts 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`](https://api.playcanvas.com/engine/classes/MorphTarget.md): A morph target instance containing the result of the cloning. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/OutlineRenderer.md # OutlineRenderer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/outline-renderer.js#L160 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: - An internal camera renders the mesh instances of the added entities into an offscreen texture matching the resolution of the scene camera, with each object drawn in its outline color. - The edges of the objects in the texture are detected and expanded to form the outlines. - The outlines are composited on top of the scene, just before the scene camera renders the layer passed to [OutlineRenderer#frameUpdate](https://api.playcanvas.com/engine/classes/OutlineRenderer.md#frameupdate). 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](https://api.playcanvas.com/engine/classes/OutlineRenderer.md#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](https://api.playcanvas.com/engine/classes/StandardMaterial.md). Relevant Engine API examples: - [Outlines Colored](https://playcanvas.github.io/#/graphics/outlines-colored) - [Editor](https://playcanvas.github.io/#/misc/editor) **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts new OutlineRenderer(app: AppBase, renderingLayer?: Layer, priority?: number) ``` Create a new OutlineRenderer. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. - `renderingLayer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md), 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. ## Methods ### addEntity ```ts 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`](https://api.playcanvas.com/engine/classes/Entity.md)): The entity to add. - `color` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)): 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** ```ts // outline an entity and its descendants in orange outlineRenderer.addEntity(entity, new Color(1, 0.5, 0)); ``` ### destroy ```ts destroy(): void ``` Destroy the outline renderer and its resources. All entities are removed from the outline renderer first. ### frameUpdate ```ts 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`](https://api.playcanvas.com/engine/classes/Entity.md)): The entity with the camera component used to render the scene. - `blendLayer` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)): 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** ```ts const immediateLayer = app.scene.layers.getLayerByName('Immediate'); app.on('update', () => { outlineRenderer.frameUpdate(cameraEntity, immediateLayer, false); }); ``` ### removeAllEntities ```ts removeAllEntities(): void ``` Remove all entities from the outline renderer, for example to clear the selection. **Example** ```ts // outline only the newly selected entity outlineRenderer.removeAllEntities(); outlineRenderer.addEntity(selectedEntity, Color.WHITE); ``` ### removeEntity ```ts 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`](https://api.playcanvas.com/engine/classes/Entity.md)): 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** ```ts outlineRenderer.removeEntity(entity); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ParticleSystemComponent.md # ParticleSystemComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/particle-system/component.js#L137 The ParticleSystemComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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](https://api.playcanvas.com/engine/classes/Curve.md) or [CurveSet](https://api.playcanvas.com/engine/classes/CurveSet.md). 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#particlesystem) property: ```javascript 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: - [Particle Animated Index](https://playcanvas.github.io/#/graphics/particles-anim-index) - [Particle Mesh](https://playcanvas.github.io/#/graphics/particles-mesh) - [Particle Random Sprites](https://playcanvas.github.io/#/graphics/particles-random-sprites) - [Particle Snow](https://playcanvas.github.io/#/graphics/particles-snow) - [Particle Spark](https://playcanvas.github.io/#/graphics/particles-spark) - [Particles in a user interface](https://playcanvas.github.io/#/user-interface/particle-system) ## Accessors ### alignToMotion ```ts get alignToMotion(): boolean set alignToMotion(arg: boolean) ``` Gets whether particles are oriented in their direction of motion or not. ### alphaGraph ```ts get alphaGraph(): Curve set alphaGraph(arg: Curve) ``` Gets the alpha graph. ### alphaGraph2 ```ts get alphaGraph2(): Curve set alphaGraph2(arg: Curve) ``` Gets the second alpha graph. ### animIndex ```ts get animIndex(): number set animIndex(arg: number) ``` Gets the index of the animation to play. ### animLoop ```ts get animLoop(): boolean set animLoop(arg: boolean) ``` Gets whether the sprite sheet animation plays once or loops continuously. ### animNumAnimations ```ts get animNumAnimations(): number set animNumAnimations(arg: number) ``` Gets the number of sprite sheet animations contained within the current sprite sheet. ### animNumFrames ```ts get animNumFrames(): number set animNumFrames(arg: number) ``` Gets the number of sprite sheet frames in the current sprite sheet animation. ### animSpeed ```ts get animSpeed(): number set animSpeed(arg: number) ``` Gets the sprite sheet animation speed. ### animStartFrame ```ts get animStartFrame(): number set animStartFrame(arg: number) ``` Gets the sprite sheet frame that the animation should begin playing from. ### animTilesX ```ts get animTilesX(): number set animTilesX(arg: number) ``` Gets the number of horizontal tiles in the sprite sheet. ### animTilesY ```ts get animTilesY(): number set animTilesY(arg: number) ``` Gets the number of vertical tiles in the sprite sheet. ### autoPlay ```ts get autoPlay(): boolean set autoPlay(arg: boolean) ``` Gets whether the particle system plays automatically on creation. ### blendType ```ts get blendType(): number set blendType(arg: number) ``` Gets how particles are blended when being written to the currently active render target. ### colorGraph ```ts get colorGraph(): CurveSet set colorGraph(arg: CurveSet) ``` Gets the color graph. ### colorGraph2 ```ts get colorGraph2(): CurveSet set colorGraph2(arg: CurveSet) ``` Gets the second color graph. ### colorMap ```ts get colorMap(): Texture set colorMap(arg: Texture) ``` Gets the color map texture to apply to all particles in the system. ### colorMapAsset ```ts get colorMapAsset(): Asset | null set colorMapAsset(arg: Asset | null) ``` Gets the [Asset](https://api.playcanvas.com/engine/classes/Asset.md) used to set the colorMap. ### depthSoftening ```ts get depthSoftening(): number set depthSoftening(arg: number) ``` Gets whether depth softening is enabled. ### depthWrite ```ts get depthWrite(): boolean set depthWrite(arg: boolean) ``` Gets whether depth writes is enabled. ### drawOrder ```ts get drawOrder(): number set drawOrder(drawOrder: number) ``` Gets the draw order of the component. ### emitterExtents ```ts get emitterExtents(): Vec3 set emitterExtents(arg: Vec3) ``` Gets the extents of a local space bounding box within which particles are spawned at random positions. ### emitterExtentsInner ```ts get emitterExtentsInner(): Vec3 set emitterExtentsInner(arg: Vec3) ``` Gets the exception of extents of a local space bounding box within which particles are not spawned. ### emitterRadius ```ts get emitterRadius(): number set emitterRadius(arg: number) ``` Gets the radius within which particles are spawned at random positions. ### emitterRadiusInner ```ts get emitterRadiusInner(): number set emitterRadiusInner(arg: number) ``` Gets the inner radius within which particles are not spawned. ### emitterShape ```ts get emitterShape(): number set emitterShape(arg: number) ``` Gets the shape of the emitter. ### halfLambert ```ts get halfLambert(): boolean set halfLambert(arg: boolean) ``` Gets whether Half Lambert lighting is enabled. ### initialVelocity ```ts get initialVelocity(): number set initialVelocity(arg: number) ``` Gets the magnitude of the initial emitter velocity. ### intensity ```ts get intensity(): number set intensity(arg: number) ``` Gets the color multiplier. ### layers ```ts get layers(): readonly number[] set layers(arg: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this particle system belongs. ### lifetime ```ts get lifetime(): number set lifetime(arg: number) ``` Gets the length of time in seconds between a particle's birth and its death. ### lighting ```ts get lighting(): boolean set lighting(arg: boolean) ``` Gets whether particles will be lit by ambient and directional lights. ### localSpace ```ts get localSpace(): boolean set localSpace(arg: boolean) ``` Gets whether particles move with respect to the emitter's transform rather then world space. ### localVelocityGraph ```ts get localVelocityGraph(): CurveSet set localVelocityGraph(arg: CurveSet) ``` Gets the local space velocity graph. ### localVelocityGraph2 ```ts get localVelocityGraph2(): CurveSet set localVelocityGraph2(arg: CurveSet) ``` Gets the second velocity graph. ### loop ```ts get loop(): boolean set loop(arg: boolean) ``` Gets whether the particle system loops. ### mesh ```ts get mesh(): Mesh set mesh(arg: Mesh) ``` Gets the polygonal mesh to be used as a particle. ### meshAsset ```ts get meshAsset(): Asset | null set meshAsset(arg: Asset | null) ``` Gets the [Asset](https://api.playcanvas.com/engine/classes/Asset.md) used to set the mesh. ### normalMap ```ts get normalMap(): Texture set normalMap(arg: Texture) ``` Gets the normal map texture to apply to all particles in the system. ### normalMapAsset ```ts get normalMapAsset(): Asset | null set normalMapAsset(arg: Asset | null) ``` Gets the [Asset](https://api.playcanvas.com/engine/classes/Asset.md) used to set the normalMap. ### numParticles ```ts get numParticles(): number set numParticles(arg: number) ``` Gets the maximum number of simulated particles. ### orientation ```ts get orientation(): number set orientation(arg: number) ``` Gets the particle orientation mode. ### particleNormal ```ts get particleNormal(): Vec3 set particleNormal(arg: Vec3) ``` Gets the particle normal. ### preWarm ```ts get preWarm(): boolean set preWarm(arg: boolean) ``` Gets whether the particle system will be initialized as though it has already completed a full cycle. ### radialSpeedGraph ```ts get radialSpeedGraph(): Curve set radialSpeedGraph(arg: Curve) ``` Gets the radial speed graph. ### radialSpeedGraph2 ```ts get radialSpeedGraph2(): Curve set radialSpeedGraph2(arg: Curve) ``` Gets the second radial speed graph. ### randomizeAnimIndex ```ts 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`. ### rate ```ts get rate(): number set rate(arg: number) ``` Gets the minimal interval in seconds between particle births. ### rate2 ```ts get rate2(): number set rate2(arg: number) ``` Gets the maximal interval in seconds between particle births. ### renderAsset ```ts get renderAsset(): Asset | null set renderAsset(arg: Asset | null) ``` Gets the Render [Asset](https://api.playcanvas.com/engine/classes/Asset.md) used to set the mesh. ### rotationSpeedGraph ```ts get rotationSpeedGraph(): Curve set rotationSpeedGraph(arg: Curve) ``` Gets the rotation speed graph. ### rotationSpeedGraph2 ```ts get rotationSpeedGraph2(): Curve set rotationSpeedGraph2(arg: Curve) ``` Gets the second rotation speed graph. ### scaleGraph ```ts get scaleGraph(): Curve set scaleGraph(arg: Curve) ``` Gets the scale graph. ### scaleGraph2 ```ts get scaleGraph2(): Curve set scaleGraph2(arg: Curve) ``` Gets the second scale graph. ### screenSpace ```ts get screenSpace(): boolean set screenSpace(arg: boolean) ``` Gets whether particles are rendered in 2D screen space. ### sort ```ts get sort(): number set sort(arg: number) ``` Gets the particle sorting mode. ### startAngle ```ts get startAngle(): number set startAngle(arg: number) ``` Gets the minimal initial Euler angle of a particle. ### startAngle2 ```ts get startAngle2(): number set startAngle2(arg: number) ``` Gets the maximal initial Euler angle of a particle. ### stretch ```ts get stretch(): number set stretch(arg: number) ``` Gets how much particles are stretched in their direction of motion. ### useFog ```ts get useFog(): boolean set useFog(arg: boolean) ``` Gets whether the camera's fog is applied to the particles. ### useTonemap ```ts get useTonemap(): boolean set useTonemap(arg: boolean) ``` Gets whether the camera's tonemapping and the scene exposure are applied to the particles. ### velocityGraph ```ts get velocityGraph(): CurveSet set velocityGraph(arg: CurveSet) ``` Gets the world space velocity graph. ### velocityGraph2 ```ts get velocityGraph2(): CurveSet set velocityGraph2(arg: CurveSet) ``` Gets the second world space velocity graph. ### wrap ```ts get wrap(): boolean set wrap(arg: boolean) ``` Gets whether particles wrap based on the set wrap bounds. ### wrapBounds ```ts get wrapBounds(): Vec3 set wrapBounds(arg: Vec3) ``` Gets the wrap bounds of the particle system. ## Methods ### isPlaying ```ts isPlaying(): boolean ``` Checks if simulation is in progress. **Returns** `boolean`: True if the particle system is currently playing and false otherwise. ### pause ```ts pause(): void ``` Freezes the simulation. ### play ```ts play(): void ``` Enables/unfreezes the simulation. ### reset ```ts reset(): void ``` Resets particle state, doesn't affect playing. ### stop ```ts stop(): void ``` Disables the emission of new particles, lets existing to finish their simulation. ### unpause ```ts unpause(): void ``` Unfreezes the simulation. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ParticleSystemComponentSystem.md # ParticleSystemComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/particle-system/system.js#L104 Manages the [ParticleSystemComponent](https://api.playcanvas.com/engine/classes/ParticleSystemComponent.md)s of an application. Reach it through `app.systems.particlesystem`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Picker.md # Picker Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/graphics/picker.js#L72 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:** - [prepare](https://api.playcanvas.com/engine/classes/Picker.md#prepare) - Renders the pick buffer (call once per frame before picking) - [getSelectionAsync](https://api.playcanvas.com/engine/classes/Picker.md#getselectionasync) - Get mesh instances in a screen area - [getWorldPointAsync](https://api.playcanvas.com/engine/classes/Picker.md#getworldpointasync) - Get world position at screen coordinates (requires depth) **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** ```ts // 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](http://playcanvas.github.io/#/graphics/area-picker|Area) - [Splatting Picking Example](https://playcanvas.github.io/#gaussian-splatting/picking|Gaussian) ## Constructors ### constructor ```ts new Picker(app: AppBase, width: number, height: number, depth?: boolean) ``` Create a new Picker instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): 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. ## Properties ### height ```ts height: number ``` ### width ```ts width: number ``` ## Methods ### destroy ```ts destroy(): void ``` Frees resources associated with this picker. ### getSelection ```ts 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](https://api.playcanvas.com/engine/classes/Picker.md#getselectionasync) instead. Note: This function is blocks the main thread while reading pixels from GPU memory. It's recommended to use [getSelectionAsync](https://api.playcanvas.com/engine/classes/Picker.md#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`](https://api.playcanvas.com/engine/classes/GSplatComponent.md) `|` [`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`)[]`: An array of mesh instances or gsplat components that are in the selection. **Example** ```ts // Get the selection at the point (10,20) const selection = picker.getSelection(10, 20); ``` **Example** ```ts // Get all models in rectangle with corners at (10,20) and (20,40) const selection = picker.getSelection(10, 20, 10, 20); ``` ### getSelectionAsync ```ts 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`](https://api.playcanvas.com/engine/classes/GSplatComponent.md) `|` [`MeshInstance`](https://api.playcanvas.com/engine/classes/MeshInstance.md)`)[]>`: - Promise that resolves with an array of mesh instances or gsplat components that are in the selection. **Example** ```ts // 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 ```ts getWorldPointAsync(x: number, y: number): Promise ``` 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`](https://api.playcanvas.com/engine/classes/Vec3.md) `| null>`: Promise that resolves with the world position of the picked point, or null if no depth is available or nothing was picked. **Example** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/Picker.md#getselection) can be called multiple times on the same picker object. Therefore, if the models or camera do not change in any way, [prepare](https://api.playcanvas.com/engine/classes/Picker.md#prepare) does not need to be called again. **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component used to render the scene. - `scene` ([`Scene`](https://api.playcanvas.com/engine/classes/Scene.md)): The scene containing the pickable mesh instances. - `layers` ([`Layer`](https://api.playcanvas.com/engine/classes/Layer.md)`[]`, optional): Layers from which objects will be picked. If not supplied, all layers of the specified camera will be used. ### resize ```ts 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](https://api.playcanvas.com/engine/classes/Picker.md#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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/PlaneGeometry.md # PlaneGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/plane-geometry.js#L34 A procedural plane-shaped geometry. Typically, you would: 1. Create a PlaneGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/Vec2.md), 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** ```ts const geometry = new PlaneGeometry({ halfExtents: new Vec2(1, 1), widthSegments: 10, lengthSegments: 10 }); ``` ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/PostEffect.md # PostEffect Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/post-effect.js#L20 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. ## Constructors ### constructor ```ts new PostEffect(graphicsDevice: GraphicsDevice) ``` Create a new PostEffect instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device of the application. ## Properties ### device ```ts device: GraphicsDevice ``` The graphics device of the application. ### needsDepthBuffer ```ts 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). ### quadVertexShader ```ts 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. ## Methods ### drawQuad ```ts 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`](https://api.playcanvas.com/engine/classes/RenderTarget.md) `| null`): The output render target. - `shader` ([`Shader`](https://api.playcanvas.com/engine/classes/Shader.md)): The shader to be used for drawing the rectangle. - `rect` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), 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 ```ts render(inputTarget: RenderTarget, outputTarget: RenderTarget, rect?: Vec4): void ``` Render the post effect using the specified inputTarget to the specified outputTarget. **Parameters** - `inputTarget` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md)): The input render target. - `outputTarget` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md)): The output render target. If null then this will be the screen. - `rect` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The rect of the current camera. If not specified, it will default to `[0, 0, 1, 1]`. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/PostEffectQueue.md # PostEffectQueue Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/post-effect-queue.js#L30 Used to manage multiple post effects for a camera. This is the legacy post-processing path. For new work use [CameraFrame](https://api.playcanvas.com/engine/classes/CameraFrame.md), 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. ## Constructors ### constructor ```ts new PostEffectQueue(app: AppBase, camera: CameraComponent) ``` Create a new PostEffectQueue instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera component. ## Methods ### addEffect ```ts 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`](https://api.playcanvas.com/engine/classes/PostEffect.md)): The post effect to add to the queue. ### destroy ```ts destroy(): void ``` Removes all the effects from the queue and disables it. ### disable ```ts disable(): void ``` Disables the queue and all of its effects. ### enable ```ts enable(): void ``` Enables the queue and all of its effects. If there are no effects then the queue will not be enabled. ### removeEffect ```ts removeEffect(effect: PostEffect): void ``` Removes a post effect from the queue. If the queue becomes empty it will be disabled automatically. **Parameters** - `effect` ([`PostEffect`](https://api.playcanvas.com/engine/classes/PostEffect.md)): The post effect to remove. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/QuadRender.md # QuadRender Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/quad-render.js#L54 An object that renders a quad using a [Shader](https://api.playcanvas.com/engine/classes/Shader.md). Note: QuadRender does not modify render states. Before calling [render](https://api.playcanvas.com/engine/classes/QuadRender.md#render), you should set up the required states using [GraphicsDevice#setDrawStates](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setdrawstates), or the individual setters ([GraphicsDevice#setBlendState](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setblendstate), [GraphicsDevice#setCullMode](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setcullmode), [GraphicsDevice#setFrontFace](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setfrontface), [GraphicsDevice#setDepthState](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setdepthstate), [GraphicsDevice#setStencilState](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#setstencilstate)). Otherwise previously set states will be used. Example: ```javascript 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(); ``` ## Constructors ### constructor ```ts new QuadRender(shader: Shader) ``` Create a new QuadRender instance. **Parameters** - `shader` ([`Shader`](https://api.playcanvas.com/engine/classes/Shader.md)): The shader to be used to render the quad. ## Methods ### destroy ```ts destroy(): void ``` Destroys the resources associated with this instance. ### render ```ts 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`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The viewport rectangle of the quad, in pixels. The viewport is not changed if not provided. - `scissor` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RenderComponent.md # RenderComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/render/component.js#L61 The RenderComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to render 3D meshes. The [type](https://api.playcanvas.com/engine/classes/RenderComponent.md#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 [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s. These can either be created programmatically or loaded from an [Asset](https://api.playcanvas.com/engine/classes/Asset.md). The [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s managed by this component are positioned, rotated, and scaled in world space by the world transformation matrix of the owner [Entity](https://api.playcanvas.com/engine/classes/Entity.md). 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](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#render) property: ```javascript 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: - [Loading Render Assets](https://playcanvas.github.io/#/graphics/render-asset) - [Primitive Shapes](https://playcanvas.github.io/#/graphics/shapes) - [Spinning Cube](https://playcanvas.github.io/#/misc/hello-world) ## Properties ### isStatic ```ts isStatic: boolean = false ``` Mark meshes as non-movable (optimization). ## Accessors ### asset ```ts get asset(): number | null set asset(value: number | null) ``` Gets the render asset id for the render component. ### batchGroupId ```ts get batchGroupId(): number set batchGroupId(value: number) ``` Gets the batch group for the mesh instances in this component (see [BatchGroup](https://api.playcanvas.com/engine/classes/BatchGroup.md)). ### castShadows ```ts get castShadows(): boolean set castShadows(value: boolean) ``` Gets whether attached meshes will cast shadows for lights that have shadow casting enabled. ### castShadowsLightmap ```ts get castShadowsLightmap(): boolean set castShadowsLightmap(value: boolean) ``` Gets whether meshes instances will cast shadows when rendering lightmaps. ### customAabb ```ts 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. ### layers ```ts get layers(): readonly number[] set layers(value: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which the mesh instances belong. ### lightmapped ```ts get lightmapped(): boolean set lightmapped(value: boolean) ``` Gets whether the component is affected by the runtime lightmapper. ### lightmapSizeMultiplier ```ts get lightmapSizeMultiplier(): number set lightmapSizeMultiplier(value: number) ``` Gets the lightmap resolution multiplier. ### material ```ts get material(): Material set material(value: Material) ``` Gets the material [Material](https://api.playcanvas.com/engine/classes/Material.md) that will be used to render the component. ### materialAssets ```ts get materialAssets(): number[] | Asset[] set materialAssets(value?: number[] | Asset[]) ``` Gets the material assets that will be used to render the component. ### meshInstances ```ts 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. ### receiveShadows ```ts get receiveShadows(): boolean set receiveShadows(value: boolean) ``` Gets whether shadows will be cast on attached meshes. ### renderStyle ```ts get renderStyle(): number set renderStyle(renderStyle: number) ``` Gets the render style of this component's [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s. ### rootBone ```ts get rootBone(): Entity | null set rootBone(value: Entity | null) ``` Gets the root bone entity for the render component. ### shadowCascadeMask ```ts get shadowCascadeMask(): number set shadowCascadeMask(value: number) ``` Gets the bitmask that controls which shadow cascades the attached meshes contribute to. ### type ```ts 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. ## Methods ### hide ```ts hide(): void ``` Stop rendering [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s without removing them from the scene hierarchy. This method sets the [MeshInstance#visible](https://api.playcanvas.com/engine/classes/MeshInstance.md#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 ```ts show(): void ``` Enable rendering of the component's [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md)s if hidden using [hide](https://api.playcanvas.com/engine/classes/RenderComponent.md#hide). This method sets the [MeshInstance#visible](https://api.playcanvas.com/engine/classes/MeshInstance.md#visible) property on all mesh instances to true. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RenderComponentSystem.md # RenderComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/render/system.js#L54 Allows an Entity to render a mesh or a primitive shape like a box, capsule, sphere, cylinder, cone etc. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RenderTarget.md # RenderTarget Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/render-target.js#L94 A render target is a rectangular rendering surface that can be rendered into, instead of the screen. It wraps one or more color buffer [Texture](https://api.playcanvas.com/engine/classes/Texture.md)s 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. ## Usage 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: ```javascript 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](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md), 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](https://playcanvas.github.io/#/graphics/render-to-texture) ## Multisampling (MSAA) 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. ```javascript const renderTarget = new RenderTarget({ colorBuffer: texture, depth: true, samples: 4 }); ``` ## Explicit multisampled color buffers and custom resolves (WebGPU) A multisampled texture (a [Texture](https://api.playcanvas.com/engine/classes/Texture.md) 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. ```javascript // 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](https://playcanvas.github.io/#/graphics-advanced/custom-msaa-resolve) ## Constructors ### constructor ```ts 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](https://api.playcanvas.com/engine/classes/RenderTarget.md#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`](https://api.playcanvas.com/engine/classes/Texture.md), 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`](https://api.playcanvas.com/engine/classes/Texture.md)`[]`, 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`](https://api.playcanvas.com/engine/classes/Texture.md), 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH.md), [PIXELFORMAT_DEPTH16](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH16.md) or [PIXELFORMAT_DEPTHSTENCIL](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTHSTENCIL.md) 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`](https://api.playcanvas.com/engine/classes/Texture.md), optional): A single-sampled [PIXELFORMAT_R32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) 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](https://api.playcanvas.com/engine/classes/RenderTarget.md#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](https://api.playcanvas.com/engine/classes/RenderTarget.md#copy), or the automatic resolve into a provided `depthBuffer`. Can be: - [DEPTHRESOLVE_MIN](https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_MIN.md): the minimum sample value - with a standard depth buffer this selects the nearest surface, a conservative and stable choice for depth-consuming effects. - [DEPTHRESOLVE_MAX](https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_MAX.md): the maximum sample value - the farthest surface. - [DEPTHRESOLVE_SAMPLE0](https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_SAMPLE0.md): the value of the sample at index 0. Defaults to [DEPTHRESOLVE_MIN](https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_MIN.md). 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](https://api.playcanvas.com/engine/classes/RenderTarget.md#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: - [CUBEFACE_POSX](https://api.playcanvas.com/engine/variables/CUBEFACE_POSX.md) - [CUBEFACE_NEGX](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGX.md) - [CUBEFACE_POSY](https://api.playcanvas.com/engine/variables/CUBEFACE_POSY.md) - [CUBEFACE_NEGY](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGY.md) - [CUBEFACE_POSZ](https://api.playcanvas.com/engine/variables/CUBEFACE_POSZ.md) - [CUBEFACE_NEGZ](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGZ.md) Defaults to [CUBEFACE_POSX](https://api.playcanvas.com/engine/variables/CUBEFACE_POSX.md). - `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: - [RENDERTARGET_ORIGIN_TOP](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md): row 0 of the stored image is the top row of the rendered image, on all graphics APIs - the same layout image textures use. Use for anything treated as a picture: sampling with mesh UVs, cube map faces, or pixel readback saved as an image. Recommended for all new content - write the sampling code as if the texture was a loaded image. Internally the image is rendered upside-down on WebGL2. - [RENDERTARGET_ORIGIN_BOTTOM](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_BOTTOM.md): row 0 of the stored image is the bottom row of the rendered image, on all graphics APIs - replicating WebGL2's native layout. Use to keep consuming code written against WebGL conventions working unchanged on all APIs: shaders deriving UVs from projected (NDC) coordinates or a projection scale-bias matrix, and texture atlases addressing cells by viewport rectangles (on WebGPU this also switches viewport / scissor rectangles to raw texel-row addressing). If a render target that worked on WebGL2 appears upside-down on WebGPU, this is the drop-in fix; migrating the sampling code to image orientation and [RENDERTARGET_ORIGIN_TOP](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md) is the better long-term choice. Internally the image is rendered upside-down on WebGPU. - [RENDERTARGET_ORIGIN_NATIVE](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_NATIVE.md): the image is stored in the native orientation of the graphics API and the row order differs between WebGL2 (bottom-up) and WebGPU (top-down). No flipping takes place. Only appropriate for orientation-agnostic consumers: UVs derived from gl_FragCoord, sampling via the same matrix the target was rendered with (shadow maps), or integer texel fetch. Takes precedence over the deprecated `flipY` option. Defaults to [RENDERTARGET_ORIGIN_NATIVE](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_NATIVE.md). - `options.resolveBuffer` ([`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `| 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) cannot be hardware-resolved. - `options.resolveBuffers` (`(`[`Texture`](https://api.playcanvas.com/engine/classes/Texture.md) `| 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** ```ts // 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; ``` ## Properties ### autoResolve ```ts autoResolve: boolean ``` ### name ```ts name: string ``` The name of the render target. ## Accessors ### colorBuffer ```ts get colorBuffer(): Texture ``` Color buffer set up on the render target. ### colorBufferCount ```ts get colorBufferCount(): number ``` The number of color buffers (attachments) set up on the render target. ### depth ```ts get depth(): boolean ``` True if the render target contains the depth attachment. ### depthBuffer ```ts 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. ### depthResolveBuffer ```ts 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. ### depthResolveMode ```ts get depthResolveMode(): string set depthResolveMode(value: string) ``` Gets how the samples of the multisampled depth buffer are resolved into a single depth value. ### face ```ts 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: - [CUBEFACE_POSX](https://api.playcanvas.com/engine/variables/CUBEFACE_POSX.md) - [CUBEFACE_NEGX](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGX.md) - [CUBEFACE_POSY](https://api.playcanvas.com/engine/variables/CUBEFACE_POSY.md) - [CUBEFACE_NEGY](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGY.md) - [CUBEFACE_POSZ](https://api.playcanvas.com/engine/variables/CUBEFACE_POSZ.md) - [CUBEFACE_NEGZ](https://api.playcanvas.com/engine/variables/CUBEFACE_NEGZ.md) ### height ```ts get height(): number ``` Height of the render target in pixels. ### mipLevel ```ts get mipLevel(): number ``` Mip level of the render target. ### mipmaps ```ts get mipmaps(): boolean ``` True if the mipmaps are automatically generated for the color buffer(s) if it contains a mip chain. ### origin ```ts 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](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md), [RENDERTARGET_ORIGIN_BOTTOM](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_BOTTOM.md) or [RENDERTARGET_ORIGIN_NATIVE](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_NATIVE.md). See the `origin` option of the constructor for details. ### resolveBuffer ```ts 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. ### samples ```ts get samples(): number ``` Number of antialiasing samples the render target uses. ### stencil ```ts get stencil(): boolean ``` True if the render target contains the stencil attachment. ### transientColor ```ts get transientColor(): boolean ``` True if the multi-sampled color attachment is allocated as a transient ("memoryless") attachment (WebGPU only). See the `transientColor` constructor option. ### transientDepth ```ts get transientDepth(): boolean ``` True if the depth attachment is allocated as a transient ("memoryless") attachment (WebGPU only). See the `transientDepth` constructor option. ### width ```ts get width(): number ``` Width of the render target in pixels. ## Methods ### copy ```ts 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: - On WebGL 2.0, between render targets with matching sample counts. - On WebGPU, between single-sampled render targets. - On WebGPU, from a multisampled source into a multisampled `depthBuffer` of this render target with an equal sample count and matching format - a full depth snapshot, including the individual samples. - On WebGPU, from a multisampled source into a single-sampled [PIXELFORMAT_R32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) color buffer of this render target - a shader-based resolve controlled by the source's [RenderTarget#depthResolveMode](https://api.playcanvas.com/engine/classes/RenderTarget.md#depthresolvemode). **Parameters** - `source` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md)): 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 ```ts destroy(): void ``` Frees resources associated with this render target. ### getColorBuffer ```ts getColorBuffer(index: number): Texture ``` Accessor for multiple render target color buffers. **Parameters** - `index` (`number`): Index of the color buffer to get. **Returns** [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md): - Color buffer at the specified index. ### getResolveBuffer ```ts 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`](https://api.playcanvas.com/engine/classes/Texture.md) `| null`: - The resolve texture at the specified index, or null when the attachment has none. ### resize ```ts 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 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RenderView.md # RenderView Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/render-view.js#L13 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](https://api.playcanvas.com/engine/classes/XrView.md). ## Accessors ### viewport ```ts 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. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Scene.md # Scene Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/scene.js#L56 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](https://api.playcanvas.com/engine/classes/AppBase.md#scene). The scene owns the rendering setup that is not tied to a single entity: the [layers](https://api.playcanvas.com/engine/classes/Scene.md#layers) composition that decides render order; the lighting environment through [ambientLight](https://api.playcanvas.com/engine/classes/Scene.md#ambientlight), [skybox](https://api.playcanvas.com/engine/classes/Scene.md#skybox), [envAtlas](https://api.playcanvas.com/engine/classes/Scene.md#envatlas) and the [sky](https://api.playcanvas.com/engine/classes/Scene.md#sky) and [lighting](https://api.playcanvas.com/engine/classes/Scene.md#lighting) parameter objects; [exposure](https://api.playcanvas.com/engine/classes/Scene.md#exposure), or [physicalUnits](https://api.playcanvas.com/engine/classes/Scene.md#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](https://api.playcanvas.com/engine/classes/Scene.md#fog) is a read-only [FogParams](https://api.playcanvas.com/engine/classes/FogParams.md) whose `type`, `color`, `start` and `end` you set, and [CameraComponent#fog](https://api.playcanvas.com/engine/classes/CameraComponent.md#fog) can override it for a single camera. **Example** ```ts // 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** ```ts // Run code for each camera just before it renders the scene app.scene.on('prerender', (camera) => { // camera is the CameraComponent about to render }); ``` ## Properties ### ambientBake ```ts ambientBake: boolean = false ``` If enabled, the ambient lighting will be baked into lightmaps. This will be either the [skybox](https://api.playcanvas.com/engine/classes/Scene.md#skybox) if set up, otherwise [ambientLight](https://api.playcanvas.com/engine/classes/Scene.md#ambientlight). Defaults to false. ### ambientBakeOcclusionBrightness ```ts ambientBakeOcclusionBrightness: number = 0 ``` If [ambientBake](https://api.playcanvas.com/engine/classes/Scene.md#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 ```ts ambientBakeOcclusionContrast: number = 0 ``` If [ambientBake](https://api.playcanvas.com/engine/classes/Scene.md#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 ```ts ambientLight: Color ``` The color of the scene's ambient light, specified in sRGB color space. Defaults to black (0, 0, 0). ### ambientLuminance ```ts 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 ```ts exposure: number = 1 ``` The exposure value tweaks the overall brightness of the scene. Ignored if physicalUnits is true. Defaults to 1. ### lightmapFilterEnabled ```ts 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 ```ts lightmapHDR: boolean = false ``` Enables HDR lightmaps. This can result in smoother lightmaps especially when many samples are used. Defaults to false. ### lightmapMaxResolution ```ts lightmapMaxResolution: number = 2048 ``` The maximum lightmap resolution. Defaults to 2048. ### lightmapMode ```ts lightmapMode: number = BAKE_COLORDIR ``` The lightmap baking mode. Can be: - [BAKE_COLOR](https://api.playcanvas.com/engine/variables/BAKE_COLOR.md): single color lightmap - [BAKE_COLORDIR](https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md): single color lightmap + dominant light direction (used for bump or specular). Only lights with bakeDir=true will be used for generating the dominant light direction. Defaults to [BAKE_COLORDIR](https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md). ### lightmapSizeMultiplier ```ts lightmapSizeMultiplier: number = 1 ``` The lightmap resolution multiplier. Defaults to 1. ### physicalUnits ```ts physicalUnits: boolean = false ``` Use physically based units for cameras and lights. When used, the exposure value is ignored. ### root ```ts root: Entity = null ``` The root entity of the scene, which is usually the only child to the [Application](https://api.playcanvas.com/engine/classes/Application.md) root entity. ## Accessors ### ambientBakeNumSamples ```ts get ambientBakeNumSamples(): number set ambientBakeNumSamples(value: number) ``` Gets the number of samples used to bake the ambient light into the lightmap. ### ambientBakeSpherePart ```ts get ambientBakeSpherePart(): number set ambientBakeSpherePart(value: number) ``` Gets the part of the sphere which represents the source of ambient light. ### clusteredLightingEnabled ```ts get clusteredLightingEnabled(): boolean set clusteredLightingEnabled(value: boolean) ``` Gets whether clustered lighting is enabled. ### envAtlas ```ts get envAtlas(): Texture | null set envAtlas(value: Texture | null) ``` Gets the environment lighting atlas. ### fog ```ts get fog(): FogParams ``` Gets the [FogParams](https://api.playcanvas.com/engine/classes/FogParams.md) that define fog parameters. ### gsplat ```ts get gsplat(): GSplatParams ``` Gets the GSplat parameters. ### layers ```ts get layers(): LayerComposition set layers(layers: LayerComposition) ``` Gets the [LayerComposition](https://api.playcanvas.com/engine/classes/LayerComposition.md) that defines rendering order of this scene. ### lighting ```ts get lighting(): LightingParams ``` Gets the [LightingParams](https://api.playcanvas.com/engine/classes/LightingParams.md) that define lighting parameters. ### lightmapFilterRange ```ts get lightmapFilterRange(): number set lightmapFilterRange(value: number) ``` Gets the range parameter of the bilateral filter. ### lightmapFilterSmoothness ```ts get lightmapFilterSmoothness(): number set lightmapFilterSmoothness(value: number) ``` Gets the spatial parameter of the bilateral filter. ### lightmapPixelFormat ```ts get lightmapPixelFormat(): number ``` Gets the lightmap pixel format. ### prefilteredCubemaps ```ts get prefilteredCubemaps(): Texture[] set prefilteredCubemaps(value: Texture[]) ``` Gets the 6 prefiltered cubemaps acting as the source of image-based lighting. ### sky ```ts get sky(): Sky ``` Gets the [Sky](https://api.playcanvas.com/engine/classes/Sky.md) that defines sky properties. ### skybox ```ts get skybox(): Texture | null set skybox(value: Texture | null) ``` Gets the base cubemap texture used as the scene's skybox when skyboxMip is 0. ### skyboxHighlightMultiplier ```ts get skyboxHighlightMultiplier(): number set skyboxHighlightMultiplier(value: number) ``` Gets the highlight multiplied for the skybox. ### skyboxIntensity ```ts get skyboxIntensity(): number set skyboxIntensity(value: number) ``` Gets the multiplier for skybox intensity. ### skyboxLuminance ```ts get skyboxLuminance(): number set skyboxLuminance(value: number) ``` Gets the luminance (in lm/m^2) of the skybox. ### skyboxMip ```ts get skyboxMip(): number set skyboxMip(value: number) ``` Gets the mip level of the skybox to be displayed. ### skyboxRotation ```ts get skyboxRotation(): Readonly set skyboxRotation(value: Readonly) ``` Gets the rotation of the skybox to be displayed. Use the setter to update skybox state. ## Methods ### setSkybox ```ts setSkybox(cubemaps?: Texture[]): void ``` Sets the cubemap for the scene skybox. **Parameters** - `cubemaps` ([`Texture`](https://api.playcanvas.com/engine/classes/Texture.md)`[]`, 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). ## Events ### EVENT_POSTCULL ```ts static EVENT_POSTCULL: string = 'postcull' ``` Fired after mesh instance visibility culling is performed for a camera; mesh instance visibility (such as [MeshInstance#visibleThisFrame](https://api.playcanvas.com/engine/classes/MeshInstance.md#visiblethisframe)) is up to date when this fires. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) that was culled, or null when the culling is internal (for example when culling shadow casters for a light's shadow map). **Example** ```ts app.scene.on('postcull', (camera) => { if (camera) { console.log(`Visibility culling was performed for camera ${camera.entity.name}`); } }); ``` ### EVENT_POSTRENDER ```ts static EVENT_POSTRENDER: string = 'postrender' ``` Fired when the camera renders the scene. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) that rendered the scene. **Example** ```ts app.scene.on('postrender', (camera) => { console.log(`Camera ${camera.entity.name} rendered the scene`); }); ``` ### EVENT_POSTRENDER_LAYER ```ts static EVENT_POSTRENDER_LAYER: string = 'postrender:layer' ``` Fired when the camera renders a layer. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md), the [Layer](https://api.playcanvas.com/engine/classes/Layer.md) 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](https://api.playcanvas.com/engine/classes/QuadRender.md#render). **Example** ```ts app.scene.on('postrender:layer', (camera, layer, transparent) => { console.log(`Camera ${camera.entity.name} rendered the layer ${layer.name} (transparent: ${transparent})`); }); ``` ### EVENT_PRECULL ```ts 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](https://api.playcanvas.com/engine/classes/CameraComponent.md) 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** ```ts app.scene.on('precull', (camera) => { if (camera) { console.log(`Visibility culling will be performed for camera ${camera.entity.name}`); } }); ``` ### EVENT_PRERENDER ```ts static EVENT_PRERENDER: string = 'prerender' ``` Fired before the camera renders the scene. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) that will render the scene. **Example** ```ts app.scene.on('prerender', (camera) => { console.log(`Camera ${camera.entity.name} will render the scene`); }); ``` ### EVENT_PRERENDER_LAYER ```ts static EVENT_PRERENDER_LAYER: string = 'prerender:layer' ``` Fired before the camera renders a layer. The handler is passed the [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md), the [Layer](https://api.playcanvas.com/engine/classes/Layer.md) 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](https://api.playcanvas.com/engine/classes/QuadRender.md#render). **Example** ```ts app.scene.on('prerender:layer', (camera, layer, transparent) => { console.log(`Camera ${camera.entity.name} will render the layer ${layer.name} (transparent: ${transparent})`); }); ``` ### EVENT_SETLAYERS ```ts 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](https://api.playcanvas.com/engine/classes/LayerComposition.md). **Example** ```ts 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; } } }); ``` ### EVENT_SETSKYBOX ```ts static EVENT_SETSKYBOX: string = 'set:skybox' ``` Fired when the skybox is set. The handler is passed the [Texture](https://api.playcanvas.com/engine/classes/Texture.md) that is the previously used skybox cubemap texture. The new skybox cubemap texture is in the [skybox](https://api.playcanvas.com/engine/classes/Scene.md#skybox) property. **Example** ```ts app.scene.on('set:skybox', (oldSkybox) => { console.log(`Skybox changed from ${oldSkybox.name} to ${app.scene.skybox.name}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SceneDepthReader.md # SceneDepthReader Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/graphics/scene-depth-reader.js#L59 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#requestscenedepthmap). ```javascript 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'); }); }); ``` ## Constructors ### constructor ```ts new SceneDepthReader(camera: CameraComponent) ``` **Parameters** - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The camera whose depth is read. ## Methods ### destroy ```ts 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 ```ts read(rect: Vec4, width: number, height: number, target?: Float32Array): Promise> | 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](https://api.playcanvas.com/engine/classes/GSplatParams.md#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`](https://api.playcanvas.com/engine/classes/Vec4.md)): The region of the view to sample, normalized, with its origin in the bottom left as [CameraComponent#rect](https://api.playcanvas.com/engine/classes/CameraComponent.md#rect). - `width` (`number`): The number of samples across the region. Not pixels. - `height` (`number`): The number of samples down the region. - `target` (`Float32Array`, 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> | null`: The samples, in world units, or null when the camera is disabled or is not rendering a scene depth, leaving nothing to read. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SceneRegistry.md # SceneRegistry Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L56 Container for storing and loading of scenes. An instance of the registry is created on the [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) object as [AppBase#scenes](https://api.playcanvas.com/engine/classes/AppBase.md#scenes). ## Constructors ### constructor ```ts new SceneRegistry(app: AppBase) ``` Create a new SceneRegistry instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. ## Methods ### add ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)): The scene item (which can be found with [find](https://api.playcanvas.com/engine/classes/SceneRegistry.md#find), URL of the scene file (e.g."scene_id.json") or name of the scene. - `callback` ([`ChangeSceneCallback`](https://api.playcanvas.com/engine/types/ChangeSceneCallback.md), optional): The function to call after loading, passed (err, entity) where err is null if no errors occurred. **Example** ```ts app.scenes.changeScene("Scene Name", (err, entity) => { if (!err) { // success } else { // error } }); ``` ### find ```ts find(name: string): SceneRegistryItem | null ``` Find a Scene by name and return the [SceneRegistryItem](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md). **Parameters** - `name` (`string`): The name of the scene. **Returns** [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md) `| null`: The stored data about a scene or null if no scene with that name exists. ### findByUrl ```ts findByUrl(url: string): SceneRegistryItem | null ``` Find a scene by the URL and return the [SceneRegistryItem](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md). **Parameters** - `url` (`string`): The URL to search by. **Returns** [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md) `| null`: The stored data about a scene or null if no scene with that URL exists. ### list ```ts list(): SceneRegistryItem[] ``` Return the list of scene. **Returns** [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)`[]`: All items in the registry. ### loadScene ```ts loadScene(url: string, callback: LoadSceneCallback): void ``` Load the scene hierarchy and scene settings. This is an internal method used by the [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). **Parameters** - `url` (`string`): The URL of the scene file. - `callback` ([`LoadSceneCallback`](https://api.playcanvas.com/engine/types/LoadSceneCallback.md)): The function called after the settings are applied. Passed (err, scene) where err is null if no error occurred and scene is the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ### loadSceneData ```ts 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](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenehierarchy) and [loadSceneSettings](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenesettings) to make scene loading quicker for the user. **Parameters** - `sceneItem` (`string |` [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)): The scene item (which can be found with [find](https://api.playcanvas.com/engine/classes/SceneRegistry.md#find), URL of the scene file (e.g."scene_id.json") or name of the scene. - `callback` ([`LoadSceneDataCallback`](https://api.playcanvas.com/engine/types/LoadSceneDataCallback.md)): The function to call after loading, passed (err, sceneItem) where err is null if no errors occurred. **Example** ```ts const sceneItem = app.scenes.find("Scene Name"); app.scenes.loadSceneData(sceneItem, (err, sceneItem) => { if (err) { // error } }); ``` ### loadSceneHierarchy ```ts 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`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)): The scene item (which can be found with [find](https://api.playcanvas.com/engine/classes/SceneRegistry.md#find), URL of the scene file (e.g."scene_id.json") or name of the scene. - `callback` ([`LoadHierarchyCallback`](https://api.playcanvas.com/engine/types/LoadHierarchyCallback.md)): The function to call after loading, passed (err, entity) where err is null if no errors occurred. **Example** ```ts 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 ```ts loadSceneSettings(sceneItem: string | SceneRegistryItem, callback: LoadSettingsCallback): void ``` Load a scene file and apply the scene settings to the current scene. **Parameters** - `sceneItem` (`string |` [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)): The scene item (which can be found with [find](https://api.playcanvas.com/engine/classes/SceneRegistry.md#find), URL of the scene file (e.g."scene_id.json") or name of the scene. - `callback` ([`LoadSettingsCallback`](https://api.playcanvas.com/engine/types/LoadSettingsCallback.md)): The function called after the settings are applied. Passed (err) where err is null if no error occurred. **Example** ```ts const sceneItem = app.scenes.find("Scene Name"); app.scenes.loadSceneSettings(sceneItem, (err) => { if (!err) { // success } else { // error } }); ``` ### remove ```ts remove(name: string): void ``` Remove an item from the scene registry. **Parameters** - `name` (`string`): The name of the scene. ### unloadSceneData ```ts unloadSceneData(sceneItem: string | SceneRegistryItem): void ``` Unloads scene data that has been loaded previously using [loadSceneData](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenedata). **Parameters** - `sceneItem` (`string |` [`SceneRegistryItem`](https://api.playcanvas.com/engine/classes/SceneRegistryItem.md)): The scene item (which can be found with [find](https://api.playcanvas.com/engine/classes/SceneRegistry.md#find) or URL of the scene file. Usually this will be "scene_id.json". **Example** ```ts const sceneItem = app.scenes.find("Scene Name"); app.scenes.unloadSceneData(sceneItem); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SceneRegistryItem.md # SceneRegistryItem Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry-item.js#L6 Item to be stored in the [SceneRegistry](https://api.playcanvas.com/engine/classes/SceneRegistry.md). ## Constructors ### constructor ```ts 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. ## Properties ### name ```ts name: string ``` The name of the scene. ### url ```ts url: string ``` The url of the scene file. ## Accessors ### loaded ```ts get loaded(): boolean ``` Returns true if the scene data has loaded. ### loading ```ts get loading(): boolean ``` Returns true if the scene data is still being loaded. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScopeId.md # ScopeId Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/scope-id.js#L8 The scope for a variable. ## Constructors ### constructor ```ts new ScopeId(name: string) ``` Create a new ScopeId instance. **Parameters** - `name` (`string`): The variable name. ## Properties ### name ```ts name: string ``` The variable name. ## Methods ### getValue ```ts getValue(): any ``` Get variable value. **Returns** `any`: The value. ### setValue ```ts setValue(value: any): void ``` Set variable value. **Parameters** - `value` (`any`): The value. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScopeSpace.md # ScopeSpace Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/scope-space.js#L8 The scope for variables. ## Constructors ### constructor ```ts new ScopeSpace(name: string) ``` Create a new ScopeSpace instance. **Parameters** - `name` (`string`): The scope name. ## Properties ### name ```ts name: string ``` The scope name. ## Methods ### resolve ```ts 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`](https://api.playcanvas.com/engine/classes/ScopeId.md): The variable instance. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Shader.md # Shader Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/shader.js#L29 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. ## Constructors ### constructor ```ts new Shader(graphicsDevice: GraphicsDevice, definition: object) ``` Creates a new Shader instance. Consider [ShaderUtils.createShader](https://api.playcanvas.com/engine/classes/ShaderUtils.md#createshader) as a simpler and more powerful way to create a shader. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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`, 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`, 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`](https://api.playcanvas.com/engine/classes/BindGroupFormat.md), 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](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_INTERLEAVED.md) to pack all captured varyings into a single buffer, or [TRANSFORM_FEEDBACK_SEPARATE](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_SEPARATE.md) to store each varying in its own buffer. This setting is only effective when useTransformFeedback property is enabled. Defaults to [TRANSFORM_FEEDBACK_INTERLEAVED](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_INTERLEAVED.md). - `definition.fincludes` (`Map`, 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](https://api.playcanvas.com/engine/variables/SHADERLANGUAGE_GLSL.md). - `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`, 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** ```ts // 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); ``` ## Methods ### destroy ```ts destroy(): void ``` Frees resources associated with this shader. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ShaderChunkMap.md # ShaderChunkMap Class · extends `Map` · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunk-map.js#L19 A collection of shader chunks, used by [ShaderChunks](https://api.playcanvas.com/engine/classes/ShaderChunks.md). 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. ## Methods ### add ```ts 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`](https://api.playcanvas.com/engine/classes/ShaderChunkMap.md): The ShaderChunkMap instance. ### clear ```ts clear(): void ``` Removes all shader chunks from the Map. ### delete ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/ShaderChunkMap.md): The ShaderChunkMap instance. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ShaderChunks.md # ShaderChunks Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunks.js#L18 A collection of GLSL and WGSL shader chunks, used to generate shaders. ## Properties ### version ```ts 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. ## Methods ### get ```ts static get(device: GraphicsDevice, shaderLanguage?: string): ShaderChunkMap ``` Returns a shader chunks map for the given device and shader language. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `shaderLanguage` (`string`, optional, default `SHADERLANGUAGE_GLSL`): The shader language to use (GLSL or WGSL). **Returns** [`ShaderChunkMap`](https://api.playcanvas.com/engine/classes/ShaderChunkMap.md): The shader chunks for the specified language. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ShaderMaterial.md # ShaderMaterial Class · extends [`Material`](https://api.playcanvas.com/engine/classes/Material.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/shader-material.js#L66 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](https://api.playcanvas.com/engine/classes/StandardMaterial.md) properties or shader chunk overrides. The shader is described by a [ShaderDesc](https://api.playcanvas.com/engine/interfaces/ShaderDesc.md): 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](https://api.playcanvas.com/engine/classes/Material.md#setparameter). Render state such as [Material#blendType](https://api.playcanvas.com/engine/classes/Material.md#blendtype), [Material#cull](https://api.playcanvas.com/engine/classes/Material.md#cull) and [Material#depthWrite](https://api.playcanvas.com/engine/classes/Material.md#depthwrite) comes from [Material](https://api.playcanvas.com/engine/classes/Material.md). 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: ```javascript 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); }` }); ``` ## Constructors ### constructor ```ts new ShaderMaterial(shaderDesc?: ShaderDesc) ``` Create a new ShaderMaterial instance. **Parameters** - `shaderDesc` ([`ShaderDesc`](https://api.playcanvas.com/engine/interfaces/ShaderDesc.md), optional): The description of the shader to be used by the material. ## Accessors ### shaderDesc ```ts get shaderDesc(): ShaderDesc | undefined set shaderDesc(value: ShaderDesc | undefined) ``` Gets the shader description. ## Methods ### copy ```ts copy(source: ShaderMaterial): ShaderMaterial ``` Copy a `ShaderMaterial`. **Parameters** - `source` ([`ShaderMaterial`](https://api.playcanvas.com/engine/classes/ShaderMaterial.md)): The material to copy from. **Returns** [`ShaderMaterial`](https://api.playcanvas.com/engine/classes/ShaderMaterial.md): The destination material. ## Inherited from [Material](https://api.playcanvas.com/engine/classes/Material.md) - `alphaToCoverage: boolean = false` - `cull: number = CULLFACE_BACK` - `frontFace: number = FRONTFACE_CCW` - `name: string = 'Untitled'` - `stencilBack: StencilParameters | null = null` - `stencilFront: StencilParameters | null = null` - `userId: string = ''` - `get alphaTest(): number` · `set alphaTest(value: number)` - `get alphaWrite(): boolean` · `set alphaWrite(value: boolean)` - `get blendState(): Readonly` · `set blendState(value: Readonly)` - `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(): void` - `protected _markPropertyModified(property: MaterialProperty): void` - `protected _markPropertyMutable(property: MaterialProperty, value: any): void` - `clone(): ShaderMaterial` - `deleteParameter(name: string): void` - `destroy(): void` - `getDefine(name: string): boolean` - `getParameter(name: string): any` - `getShaderChunks(shaderLanguage?: string): ShaderChunkMap` - `setDefine(name: string, value: string | boolean | undefined): void` - `setParameter(name: string, data: number | number[] | ArrayBufferView | Texture | StorageBuffer): void` - `update(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ShaderUtils.md # ShaderUtils Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-utils.js#L43 Utility class for creating shaders. Provides a higher-level API over the [Shader](https://api.playcanvas.com/engine/classes/Shader.md) 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. ## Methods ### createShader ```ts 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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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`, 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`, 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`, 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`, 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`](https://api.playcanvas.com/engine/classes/Shader.md): The newly created shader. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Skin.md # Skin Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skin.js#L13 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. ## Constructors ### constructor ```ts new Skin(graphicsDevice: GraphicsDevice, ibp: Mat4[], boneNames: string[]) ``` Create a new Skin instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to manage this skin. - `ibp` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)`[]`): The array of inverse bind matrices. - `boneNames` (`string[]`): The array of bone names for the bones referenced by this skin. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SkinInstance.md # SkinInstance Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skin-instance.js#L21 A skin instance is responsible for generating the matrix palette that is used to skin vertices from object space to world space. ## Constructors ### constructor ```ts new SkinInstance(skin: Skin) ``` Create a new SkinInstance instance. **Parameters** - `skin` ([`Skin`](https://api.playcanvas.com/engine/classes/Skin.md)): The skin that will provide the inverse bind pose matrices to generate the final matrix palette. ## Properties ### bones ```ts bones: GraphNode[] ``` An array of nodes representing each bone in this skin instance. ## Methods ### initSkin ```ts initSkin(skin: Skin): void ``` **Parameters** - `skin` ([`Skin`](https://api.playcanvas.com/engine/classes/Skin.md)): The skin. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Sky.md # Sky Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skybox/sky.js#L16 Implementation of the sky. ## Properties ### node ```ts 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](https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md). ## Accessors ### center ```ts get center(): Vec3 set center(value: Vec3) ``` Gets the center of the sky. ### depthWrite ```ts get depthWrite(): boolean set depthWrite(value: boolean) ``` Gets whether depth writing is enabled for the sky. ### fisheye ```ts get fisheye(): number set fisheye(value: number) ``` Gets the fisheye projection strength for the sky. ### type ```ts get type(): string set type(value: string) ``` Gets the type of the sky. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SphereGeometry.md # SphereGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/sphere-geometry.js#L33 A procedural sphere-shaped geometry. Typically, you would: 1. Create a SphereGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new SphereGeometry({ radius: 1, latitudeBands: 32, longitudeBands: 32 }); ``` ## Inherited from [TorusGeometry](https://api.playcanvas.com/engine/classes/TorusGeometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Sprite.md # Sprite Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/sprite.js#L33 A Sprite contains references to one or more frames of a [TextureAtlas](https://api.playcanvas.com/engine/classes/TextureAtlas.md). It can be used by the [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md) or the [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) to render a single frame or a sprite animation. ## Constructors ### constructor ```ts new Sprite(device: GraphicsDevice, options?: object) ``` Create a new Sprite instance. **Parameters** - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device of the application. - `options` (`object`, optional): Options for creating the Sprite. - `options.atlas` ([`TextureAtlas`](https://api.playcanvas.com/engine/classes/TextureAtlas.md), 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: - [SPRITE_RENDERMODE_SIMPLE](https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_SIMPLE.md) - [SPRITE_RENDERMODE_SLICED](https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_SLICED.md) - [SPRITE_RENDERMODE_TILED](https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_TILED.md) Defaults to [SPRITE_RENDERMODE_SIMPLE](https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_SIMPLE.md). ## Accessors ### atlas ```ts get atlas(): TextureAtlas set atlas(value: TextureAtlas) ``` Gets the texture atlas. ### frameKeys ```ts get frameKeys(): string[] set frameKeys(value: string[]) ``` Gets the keys of the frames in the sprite atlas that this sprite is using. ### meshes ```ts get meshes(): Mesh[] ``` An array that contains a mesh for each frame. ### pixelsPerUnit ```ts get pixelsPerUnit(): number set pixelsPerUnit(value: number) ``` Gets the number of pixels that map to one PlayCanvas unit. ### renderMode ```ts get renderMode(): number set renderMode(value: number) ``` Sets the rendering mode of the sprite. ## Methods ### destroy ```ts destroy(): void ``` Free up the meshes created by the sprite. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md # SpriteAnimationClip Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/sprite-animation-clip.js#L17 Handles playing of sprite animations and loading of relevant sprite assets. ## Constructors ### constructor ```ts new SpriteAnimationClip(component: SpriteComponent, data: object) ``` Create a new SpriteAnimationClip instance. **Parameters** - `component` ([`SpriteComponent`](https://api.playcanvas.com/engine/classes/SpriteComponent.md)): 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. ## Properties ### fps ```ts fps: number = 0 ``` Frames per second for this animation clip. A negative value plays the animation backwards. ### loop ```ts loop: boolean = false ``` Whether to loop the animation clip when it reaches the end. ### name ```ts name: string | undefined ``` The name of this animation clip. ## Accessors ### duration ```ts get duration(): number ``` Gets the total duration of the animation in seconds. ### frame ```ts get frame(): number set frame(value: number) ``` Gets the index of the frame of the [Sprite](https://api.playcanvas.com/engine/classes/Sprite.md) currently being rendered. ### isPaused ```ts get isPaused(): boolean ``` Sets whether the animation is currently paused. ### isPlaying ```ts get isPlaying(): boolean ``` Sets whether the animation is currently playing. ### sprite ```ts get sprite(): Sprite set sprite(value: Sprite) ``` Gets the current sprite used to play the animation. ### spriteAsset ```ts get spriteAsset(): number set spriteAsset(value: number) ``` Gets the id of the sprite asset used to play the animation. ### time ```ts get time(): number set time(value: number) ``` Gets the current time of the animation in seconds. ## Methods ### pause ```ts pause(): void ``` Pauses the animation. ### play ```ts play(): void ``` Plays the animation. If it's already playing then this does nothing. ### resume ```ts resume(): void ``` Resumes the paused animation. ### stop ```ts stop(): void ``` Stops the animation and resets the animation to the first frame. ## Events ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when the clip stops playing because it reached its end. **Example** ```ts clip.on('end', () => { console.log('Clip ended'); }); ``` ### EVENT_LOOP ```ts static EVENT_LOOP: string = 'loop' ``` Fired when the clip reached the end of its current loop. **Example** ```ts clip.on('loop', () => { console.log('Clip looped'); }); ``` ### EVENT_PAUSE ```ts static EVENT_PAUSE: string = 'pause' ``` Fired when the clip is paused. **Example** ```ts clip.on('pause', () => { console.log('Clip paused'); }); ``` ### EVENT_PLAY ```ts static EVENT_PLAY: string = 'play' ``` Fired when the clip starts playing. **Example** ```ts clip.on('play', () => { console.log('Clip started playing'); }); ``` ### EVENT_RESUME ```ts static EVENT_RESUME: string = 'resume' ``` Fired when the clip is resumed. **Example** ```ts clip.on('resume', () => { console.log('Clip resumed'); }); ``` ### EVENT_STOP ```ts static EVENT_STOP: string = 'stop' ``` Fired when the clip is stopped. **Example** ```ts clip.on('stop', () => { console.log('Clip stopped'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SpriteComponent.md # SpriteComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/component.js#L65 The SpriteComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to render a simple static sprite or sprite animations. The [type](https://api.playcanvas.com/engine/classes/SpriteComponent.md#type) property can be set to either [SPRITETYPE_SIMPLE](https://api.playcanvas.com/engine/variables/SPRITETYPE_SIMPLE.md) to render a single frame from a sprite asset, or [SPRITETYPE_ANIMATED](https://api.playcanvas.com/engine/variables/SPRITETYPE_ANIMATED.md) to play one or more [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md)s. You should never need to use the SpriteComponent constructor directly. To add a SpriteComponent to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#sprite) property: ```javascript 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: - [Animated sprite](https://playcanvas.github.io/#/misc/animated-sprite) ## Accessors ### autoPlayClip ```ts get autoPlayClip(): string set autoPlayClip(value: string) ``` Gets the name of the clip to play automatically when the component is enabled. ### batchGroupId ```ts get batchGroupId(): number set batchGroupId(value: number) ``` Gets the batch group for the sprite. ### clips ```ts get clips(): {} set clips(value: {}) ``` Gets the dictionary that contains [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md)s. ### color ```ts get color(): Readonly set color(value: Readonly) ``` Gets the color tint of the sprite in sRGB color space. Use the setter to update the tint. ### currentClip ```ts get currentClip(): SpriteAnimationClip ``` Gets the current clip being played. ### drawOrder ```ts get drawOrder(): number set drawOrder(value: number) ``` Gets the draw order of the component. ### flipX ```ts get flipX(): boolean set flipX(value: boolean) ``` Gets whether to flip the X axis when rendering a sprite. ### flipY ```ts get flipY(): boolean set flipY(value: boolean) ``` Gets whether to flip the Y axis when rendering a sprite. ### frame ```ts get frame(): number set frame(value: number) ``` Gets which frame from the current sprite asset to render. ### height ```ts get height(): number set height(value: number) ``` Gets the height of the sprite when rendering using 9-Slicing. ### layers ```ts get layers(): readonly number[] set layers(value: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this sprite belongs. ### opacity ```ts get opacity(): number set opacity(value: number) ``` Gets the opacity of the sprite. ### speed ```ts get speed(): number set speed(value: number) ``` Gets the global speed modifier used when playing sprite animation clips. ### sprite ```ts get sprite(): Sprite set sprite(value: Sprite) ``` Gets the current sprite. ### spriteAsset ```ts get spriteAsset(): number | Asset set spriteAsset(value: number | Asset) ``` Gets the asset id or the [Asset](https://api.playcanvas.com/engine/classes/Asset.md) of the sprite to render. ### type ```ts get type(): string set type(value: string) ``` Gets the type of the SpriteComponent. ### width ```ts get width(): number set width(value: number) ``` Gets the width of the sprite when rendering using 9-Slicing. ## Methods ### addClip ```ts addClip(data: object): SpriteAnimationClip ``` Creates and adds a new [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) 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`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): The asset id or the [Asset](https://api.playcanvas.com/engine/classes/Asset.md) of the sprite that this clip will play. **Returns** [`SpriteAnimationClip`](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md): The new clip that was added. ### clip ```ts clip(name: string): SpriteAnimationClip ``` Get an animation clip by name. **Parameters** - `name` (`string`): The name of the clip. **Returns** [`SpriteAnimationClip`](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md): The clip. ### pause ```ts pause(): void ``` Pauses the current animation clip. ### play ```ts 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`](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md): The clip that started playing. ### removeClip ```ts removeClip(name: string): void ``` Removes a clip by name. **Parameters** - `name` (`string`): The name of the animation clip to remove. ### resume ```ts resume(): void ``` Resumes the current paused animation clip. ### stop ```ts stop(): void ``` Stops the current animation clip and resets it to the first frame. ## Events ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when an animation clip stops playing because it reached its end. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that ended. **Example** ```ts entity.sprite.on('end', (clip) => { console.log(`Animation clip ${clip.name} ended.`); }); ``` ### EVENT_LOOP ```ts static EVENT_LOOP: string = 'loop' ``` Fired when an animation clip reached the end of its current loop. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that looped. **Example** ```ts entity.sprite.on('loop', (clip) => { console.log(`Animation clip ${clip.name} looped.`); }); ``` ### EVENT_PAUSE ```ts static EVENT_PAUSE: string = 'pause' ``` Fired when an animation clip is paused. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that was paused. **Example** ```ts entity.sprite.on('pause', (clip) => { console.log(`Animation clip ${clip.name} paused.`); }); ``` ### EVENT_PLAY ```ts static EVENT_PLAY: string = 'play' ``` Fired when an animation clip starts playing. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that started playing. **Example** ```ts entity.sprite.on('play', (clip) => { console.log(`Animation clip ${clip.name} started playing.`); }); ``` ### EVENT_RESUME ```ts static EVENT_RESUME: string = 'resume' ``` Fired when an animation clip is resumed. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that was resumed. **Example** ```ts entity.sprite.on('resume', (clip) => { console.log(`Animation clip ${clip.name} resumed.`); }); ``` ### EVENT_STOP ```ts static EVENT_STOP: string = 'stop' ``` Fired when an animation clip is stopped. The handler is passed the [SpriteAnimationClip](https://api.playcanvas.com/engine/classes/SpriteAnimationClip.md) that was stopped. **Example** ```ts entity.sprite.on('stop', (clip) => { console.log(`Animation clip ${clip.name} stopped.`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SpriteComponentSystem.md # SpriteComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/system.js#L41 Manages the [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md)s of an application. Reach it through `app.systems.sprite`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/StandardMaterial.md # StandardMaterial Class · extends [`Material`](https://api.playcanvas.com/engine/classes/Material.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material.js#L627 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](https://api.playcanvas.com/engine/classes/Color.md) or number), mesh vertex colors and a [Texture](https://api.playcanvas.com/engine/classes/Texture.md). 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](https://api.playcanvas.com/engine/classes/MeshInstance.md#setinstancing). A property assignment only reaches the GPU once [Material#update](https://api.playcanvas.com/engine/classes/Material.md#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](https://api.playcanvas.com/engine/classes/Material.md#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](https://api.playcanvas.com/engine/classes/Material.md#getshaderchunks). When the surface is not a lit material at all, use [ShaderMaterial](https://api.playcanvas.com/engine/classes/ShaderMaterial.md) instead. **Example** ```ts 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; ``` ## Constructors ### constructor ```ts new StandardMaterial() ``` Create a new StandardMaterial instance. **Example** ```ts // 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** ```ts // 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(); ``` ## Properties ### anisotropyMap ```ts anisotropyMap: Texture | null ``` The anisotropy map of the material (default is null). ### anisotropyMapOffset ```ts anisotropyMapOffset: Vec2 ``` Controls the 2D offset of the anisotropy map. Each component is between 0 and 1. ### anisotropyMapRotation ```ts anisotropyMapRotation: number ``` Controls the 2D rotation (in degrees) of the anisotropy map. ### anisotropyMapTiling ```ts anisotropyMapTiling: Vec2 ``` Controls the 2D tiling of the anisotropy map. ### anisotropyMapUv ```ts anisotropyMapUv: number ``` Anisotropy map UV channel. Valid values are 0 to 7. ### aoDetailMap ```ts 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 ```ts aoDetailMapChannel: string ``` Color channels of the detail (secondary) AO map to use. Can be "r", "g", "b" or "a" (default is "g"). ### aoDetailMapOffset ```ts aoDetailMapOffset: Vec2 ``` Controls the 2D offset of the detail (secondary) AO map. Each component is between 0 and 1. ### aoDetailMapRotation ```ts aoDetailMapRotation: number ``` Controls the 2D rotation (in degrees) of the detail (secondary) AO map. ### aoDetailMapTiling ```ts aoDetailMapTiling: Vec2 ``` Controls the 2D tiling of the detail (secondary) AO map. ### aoDetailMapUv ```ts aoDetailMapUv: number ``` Detail (secondary) AO map UV channel. Valid values are 0 to 7. ### aoDetailMode ```ts aoDetailMode: string ``` Determines how the main (primary) and detail (secondary) AO maps are blended together. Can be: - DETAILMODE_MUL: Multiply together the primary and secondary colors. - DETAILMODE_ADD: Add together the primary and secondary colors. - DETAILMODE_SCREEN: Softer version of DETAILMODE_ADD. - DETAILMODE_OVERLAY: Multiplies or screens the colors, depending on the primary color. - DETAILMODE_MIN: Select whichever of the primary and secondary colors is darker, component-wise. - DETAILMODE_MAX: Select whichever of the primary and secondary colors is lighter, component-wise. Defaults to DETAILMODE_MUL. ### aoMap ```ts aoMap: Texture | null ``` The main (primary) baked ambient occlusion (AO) map (default is null). Modulates ambient color. ### aoMapChannel ```ts aoMapChannel: string ``` Color channel of the main (primary) AO map to use. Can be "r", "g", "b" or "a". ### aoMapOffset ```ts aoMapOffset: Vec2 ``` Controls the 2D offset of the main (primary) AO map. Each component is between 0 and 1. ### aoMapRotation ```ts aoMapRotation: number ``` Controls the 2D rotation (in degrees) of the main (primary) AO map. ### aoMapTiling ```ts aoMapTiling: Vec2 ``` Controls the 2D tiling of the main (primary) AO map. ### aoMapUv ```ts aoMapUv: number ``` Main (primary) AO map UV channel. Valid values are 0 to 7. ### aoVertexColor ```ts aoVertexColor: boolean ``` Use mesh vertex colors for AO. If aoMap is set, it'll be multiplied by vertex colors. ### aoVertexColorChannel ```ts aoVertexColorChannel: string ``` Vertex color channels to use for AO. Can be "r", "g", "b" or "a". ### clearCoatGlossInvert ```ts 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 ```ts clearCoatGlossMap: Texture | null ``` Monochrome clearcoat glossiness map (default is null). If specified, will be multiplied by normalized 'clearCoatGloss' value and/or vertex colors. ### clearCoatGlossMapChannel ```ts clearCoatGlossMapChannel: string ``` Color channel of the clearcoat gloss map to use. Can be "r", "g", "b" or "a". ### clearCoatGlossMapOffset ```ts clearCoatGlossMapOffset: Vec2 ``` Controls the 2D offset of the clearcoat gloss map. Each component is between 0 and 1. ### clearCoatGlossMapRotation ```ts clearCoatGlossMapRotation: number ``` Controls the 2D rotation (in degrees) of the clear coat gloss map. ### clearCoatGlossMapTiling ```ts clearCoatGlossMapTiling: Vec2 ``` Controls the 2D tiling of the clearcoat gloss map. ### clearCoatGlossMapUv ```ts clearCoatGlossMapUv: number ``` Clearcoat gloss map UV channel. Valid values are 0 to 7. ### clearCoatGlossVertexColor ```ts clearCoatGlossVertexColor: boolean ``` Use mesh vertex colors for clearcoat glossiness. If clearCoatGlossMap is set, it'll be multiplied by vertex colors. ### clearCoatGlossVertexColorChannel ```ts clearCoatGlossVertexColorChannel: string ``` Vertex color channel to use for clearcoat glossiness. Can be "r", "g", "b" or "a". ### clearCoatMap ```ts clearCoatMap: Texture | null ``` Monochrome clearcoat intensity map (default is null). If specified, will be multiplied by normalized 'clearCoat' value and/or vertex colors. ### clearCoatMapChannel ```ts clearCoatMapChannel: string ``` Color channel of the clearcoat intensity map to use. Can be "r", "g", "b" or "a". ### clearCoatMapOffset ```ts clearCoatMapOffset: Vec2 ``` Controls the 2D offset of the clearcoat intensity map. Each component is between 0 and 1. ### clearCoatMapRotation ```ts clearCoatMapRotation: number ``` Controls the 2D rotation (in degrees) of the clearcoat intensity map. ### clearCoatMapTiling ```ts clearCoatMapTiling: Vec2 ``` Controls the 2D tiling of the clearcoat intensity map. ### clearCoatMapUv ```ts clearCoatMapUv: number ``` Clearcoat intensity map UV channel. Valid values are 0 to 7. ### clearCoatNormalMap ```ts clearCoatNormalMap: Texture | null ``` The clearcoat normal map of the material (default is null). The texture must contains normalized, tangent space normals. ### clearCoatNormalMapOffset ```ts clearCoatNormalMapOffset: Vec2 ``` Controls the 2D offset of the main clearcoat normal map. Each component is between 0 and 1. ### clearCoatNormalMapRotation ```ts clearCoatNormalMapRotation: number ``` Controls the 2D rotation (in degrees) of the main clearcoat map. ### clearCoatNormalMapTiling ```ts clearCoatNormalMapTiling: Vec2 ``` Controls the 2D tiling of the main clearcoat normal map. ### clearCoatNormalMapUv ```ts clearCoatNormalMapUv: number ``` Clearcoat normal map UV channel. Valid values are 0 to 7. ### clearCoatVertexColor ```ts clearCoatVertexColor: boolean ``` Use mesh vertex colors for clearcoat intensity. If clearCoatMap is set, it'll be multiplied by vertex colors. ### clearCoatVertexColorChannel ```ts clearCoatVertexColorChannel: string ``` Vertex color channel to use for clearcoat intensity. Can be "r", "g", "b" or "a". ### cubeMap ```ts 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 ```ts cubeMapProjection: number ``` The type of projection applied to the cubeMap property: - CUBEPROJ_NONE: The cube map is treated as if it is infinitely far away. - CUBEPROJ_BOX: Box-projection based on a world space axis-aligned bounding box. Defaults to CUBEPROJ_NONE. ### diffuseDetailMap ```ts 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 ```ts diffuseDetailMapChannel: string ``` Color channels of the detail (secondary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### diffuseDetailMapOffset ```ts diffuseDetailMapOffset: Vec2 ``` Controls the 2D offset of the detail (secondary) diffuse map. Each component is between 0 and 1. ### diffuseDetailMapRotation ```ts diffuseDetailMapRotation: number ``` Controls the 2D rotation (in degrees) of the detail (secondary) diffuse map. ### diffuseDetailMapTiling ```ts diffuseDetailMapTiling: Vec2 ``` Controls the 2D tiling of the detail (secondary) diffuse map. ### diffuseDetailMapUv ```ts diffuseDetailMapUv: number ``` Detail (secondary) diffuse map UV channel. Valid values are 0 to 7. ### diffuseDetailMode ```ts diffuseDetailMode: string ``` Determines how the main (primary) and detail (secondary) diffuse maps are blended together. Can be: - DETAILMODE_MUL: Multiply together the primary and secondary colors. - DETAILMODE_ADD: Add together the primary and secondary colors. - DETAILMODE_SCREEN: Softer version of DETAILMODE_ADD. - DETAILMODE_OVERLAY: Multiplies or screens the colors, depending on the primary color. - DETAILMODE_MIN: Select whichever of the primary and secondary colors is darker, component-wise. - DETAILMODE_MAX: Select whichever of the primary and secondary colors is lighter, component-wise. Defaults to DETAILMODE_MUL. ### diffuseMap ```ts diffuseMap: Texture | null ``` The main (primary) diffuse map of the material (default is null). ### diffuseMapChannel ```ts diffuseMapChannel: string ``` Color channels of the main (primary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### diffuseMapOffset ```ts diffuseMapOffset: Vec2 ``` Controls the 2D offset of the main (primary) diffuse map. Each component is between 0 and 1. ### diffuseMapRotation ```ts diffuseMapRotation: number ``` Controls the 2D rotation (in degrees) of the main (primary) diffuse map. ### diffuseMapTiling ```ts diffuseMapTiling: Vec2 ``` Controls the 2D tiling of the main (primary) diffuse map. ### diffuseMapUv ```ts diffuseMapUv: number ``` Main (primary) diffuse map UV channel. Valid values are 0 to 7. ### diffuseVertexColor ```ts diffuseVertexColor: boolean ``` Multiply diffuse by the mesh vertex colors. ### diffuseVertexColorChannel ```ts diffuseVertexColorChannel: string ``` Vertex color channels to use for diffuse. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### emissiveMap ```ts 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 ```ts emissiveMapChannel: string ``` Color channels of the emissive map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### emissiveMapOffset ```ts emissiveMapOffset: Vec2 ``` Controls the 2D offset of the emissive map. Each component is between 0 and 1. ### emissiveMapRotation ```ts emissiveMapRotation: number ``` Controls the 2D rotation (in degrees) of the emissive map. ### emissiveMapTiling ```ts emissiveMapTiling: Vec2 ``` Controls the 2D tiling of the emissive map. ### emissiveMapUv ```ts emissiveMapUv: number ``` Emissive map UV channel. Valid values are 0 to 7. ### emissiveVertexColor ```ts emissiveVertexColor: boolean ``` Use mesh vertex colors for emission. If emissiveMap or emissive are set, they'll be multiplied by vertex colors. ### emissiveVertexColorChannel ```ts emissiveVertexColorChannel: string ``` Vertex color channels to use for emission. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### enableGGXSpecular ```ts enableGGXSpecular: boolean ``` Enables GGX specular. Also enables anisotropyIntensity parameter to set material anisotropy. ### envAtlas ```ts 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 ```ts 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. - FRESNEL_NONE: No Fresnel. - FRESNEL_SCHLICK: Schlick's approximation of Fresnel (recommended). Parameterized by specular color. ### glossInvert ```ts glossInvert: boolean ``` Invert the gloss component (default is false). Enabling this flag results in material treating the gloss members as roughness. ### glossMap ```ts glossMap: Texture | null ``` Gloss map (default is null). If specified, will be multiplied by normalized gloss value and/or vertex colors. ### glossMapChannel ```ts glossMapChannel: string ``` Color channel of the gloss map to use. Can be "r", "g", "b" or "a". ### glossMapOffset ```ts glossMapOffset: Vec2 ``` Controls the 2D offset of the gloss map. Each component is between 0 and 1. ### glossMapRotation ```ts glossMapRotation: number ``` Controls the 2D rotation (in degrees) of the gloss map. ### glossMapTiling ```ts glossMapTiling: Vec2 ``` Controls the 2D tiling of the gloss map. ### glossMapUv ```ts glossMapUv: number ``` Gloss map UV channel. Valid values are 0 to 7. ### glossVertexColor ```ts glossVertexColor: boolean ``` Use mesh vertex colors for glossiness. If glossMap is set, it'll be multiplied by vertex colors. ### glossVertexColorChannel ```ts glossVertexColorChannel: string ``` Vertex color channel to use for glossiness. Can be "r", "g", "b" or "a". ### heightMap ```ts 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 ```ts heightMapChannel: string ``` Color channel of the height map to use. Can be "r", "g", "b" or "a". ### heightMapOffset ```ts heightMapOffset: Vec2 ``` Controls the 2D offset of the height map. Each component is between 0 and 1. ### heightMapRotation ```ts heightMapRotation: number ``` Controls the 2D rotation (in degrees) of the height map. ### heightMapTiling ```ts heightMapTiling: Vec2 ``` Controls the 2D tiling of the height map. ### heightMapUv ```ts heightMapUv: number ``` Height map UV channel. Valid values are 0 to 7. ### iridescenceMap ```ts iridescenceMap: Texture | null ``` The per-pixel iridescence intensity. Only used when useIridescence is enabled. ### iridescenceMapChannel ```ts iridescenceMapChannel: string ``` Color channels of the iridescence map to use. Can be "r", "g", "b" or "a". ### iridescenceMapOffset ```ts iridescenceMapOffset: Vec2 ``` Controls the 2D offset of the iridescence map. Each component is between 0 and 1. ### iridescenceMapRotation ```ts iridescenceMapRotation: number ``` Controls the 2D rotation (in degrees) of the iridescence map. ### iridescenceMapTiling ```ts iridescenceMapTiling: Vec2 ``` Controls the 2D tiling of the iridescence map. ### iridescenceMapUv ```ts iridescenceMapUv: number ``` Iridescence map UV channel. Valid values are 0 to 7. ### iridescenceThicknessMap ```ts iridescenceThicknessMap: Texture | null ``` The per-pixel iridescence thickness. Defines a gradient weight between iridescenceThicknessMin and iridescenceThicknessMax. Only used when useIridescence is enabled. ### iridescenceThicknessMapChannel ```ts iridescenceThicknessMapChannel: string ``` Color channels of the iridescence thickness map to use. Can be "r", "g", "b" or "a". ### iridescenceThicknessMapOffset ```ts iridescenceThicknessMapOffset: Vec2 ``` Controls the 2D offset of the iridescence thickness map. Each component is between 0 and 1. ### iridescenceThicknessMapRotation ```ts iridescenceThicknessMapRotation: number ``` Controls the 2D rotation (in degrees) of the iridescence thickness map. ### iridescenceThicknessMapTiling ```ts iridescenceThicknessMapTiling: Vec2 ``` Controls the 2D tiling of the iridescence thickness map. ### iridescenceThicknessMapUv ```ts iridescenceThicknessMapUv: number ``` Iridescence thickness map UV channel. Valid values are 0 to 7. ### lightMap ```ts 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 ```ts lightMapChannel: string ``` Color channels of the lightmap to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### lightMapOffset ```ts lightMapOffset: Vec2 ``` Controls the 2D offset of the lightmap. Each component is between 0 and 1. ### lightMapRotation ```ts lightMapRotation: number ``` Controls the 2D rotation (in degrees) of the lightmap. ### lightMapTiling ```ts lightMapTiling: Vec2 ``` Controls the 2D tiling of the lightmap. ### lightMapUv ```ts lightMapUv: number ``` Lightmap UV channel. Valid values are 0 to 7. ### lightVertexColor ```ts lightVertexColor: boolean ``` Use baked vertex lighting. If lightMap is set, it'll be multiplied by vertex colors. ### lightVertexColorChannel ```ts lightVertexColorChannel: string ``` Vertex color channels to use for baked lighting. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### metalnessMap ```ts metalnessMap: Texture | null ``` Monochrome metalness map (default is null). ### metalnessMapChannel ```ts metalnessMapChannel: string ``` Color channel of the metalness map to use. Can be "r", "g", "b" or "a". ### metalnessMapOffset ```ts metalnessMapOffset: Vec2 ``` Controls the 2D offset of the metalness map. Each component is between 0 and 1. ### metalnessMapRotation ```ts metalnessMapRotation: number ``` Controls the 2D rotation (in degrees) of the metalness map. ### metalnessMapTiling ```ts metalnessMapTiling: Vec2 ``` Controls the 2D tiling of the metalness map. ### metalnessMapUv ```ts metalnessMapUv: number ``` Metalness map UV channel. Valid values are 0 to 7. ### metalnessVertexColor ```ts metalnessVertexColor: boolean ``` Use mesh vertex colors for metalness. If metalnessMap is set, it'll be multiplied by vertex colors. ### metalnessVertexColorChannel ```ts metalnessVertexColorChannel: string ``` Vertex color channel to use for metalness. Can be "r", "g", "b" or "a". ### normalDetailMap ```ts 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 ```ts normalDetailMapOffset: Vec2 ``` Controls the 2D offset of the detail (secondary) normal map. Each component is between 0 and 1. ### normalDetailMapRotation ```ts normalDetailMapRotation: number ``` Controls the 2D rotation (in degrees) of the detail (secondary) normal map. ### normalDetailMapTiling ```ts normalDetailMapTiling: Vec2 ``` Controls the 2D tiling of the detail (secondary) normal map. ### normalDetailMapUv ```ts normalDetailMapUv: number ``` Detail (secondary) normal map UV channel. Valid values are 0 to 7. ### normalMap ```ts normalMap: Texture | null ``` The main (primary) normal map of the material (default is null). The texture must contains normalized, tangent space normals. ### normalMapOffset ```ts normalMapOffset: Vec2 ``` Controls the 2D offset of the main (primary) normal map. Each component is between 0 and 1. ### normalMapRotation ```ts normalMapRotation: number ``` Controls the 2D rotation (in degrees) of the main (primary) normal map. ### normalMapTiling ```ts normalMapTiling: Vec2 ``` Controls the 2D tiling of the main (primary) normal map. ### normalMapUv ```ts normalMapUv: number ``` Main (primary) normal map UV channel. Valid values are 0 to 7. ### occludeDirect ```ts occludeDirect: boolean ``` Tells if AO should darken directional lighting. Defaults to false. ### occludeSpecular ```ts 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. - SPECOCC_NONE: No specular occlusion - SPECOCC_AO: Use AO directly to occlude specular. - SPECOCC_GLOSSDEPENDENT: Modify AO based on material glossiness/view angle to occlude specular. ### onUpdateShader ```ts 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](https://api.playcanvas.com/engine/classes/StandardMaterialOptions.md) and the options for the lit options are [LitShaderOptions](https://api.playcanvas.com/engine/classes/LitShaderOptions.md). ### opacityDither ```ts opacityDither: string ``` Used to specify whether opacity is dithered, which allows transparency without alpha blending. Can be: - DITHER_NONE: Opacity dithering is disabled. - DITHER_BAYER2: Opacity is dithered using a Bayer 2 matrix. - DITHER_BAYER4: Opacity is dithered using a Bayer 4 matrix. - DITHER_BAYER8: Opacity is dithered using a Bayer 8 matrix. - DITHER_BAYER16: Opacity is dithered using a Bayer 16 matrix. - DITHER_BLUENOISE: Opacity is dithered using a blue noise. - DITHER_IGNNOISE: Opacity is dithered using an interleaved gradient noise. Defaults to DITHER_NONE. ### opacityFadesSpecular ```ts 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 ```ts opacityMap: Texture | null ``` The opacity map of the material (default is null). ### opacityMapChannel ```ts opacityMapChannel: string ``` Color channel of the opacity map to use. Can be "r", "g", "b" or "a". ### opacityMapOffset ```ts opacityMapOffset: Vec2 ``` Controls the 2D offset of the opacity map. Each component is between 0 and 1. ### opacityMapRotation ```ts opacityMapRotation: number ``` Controls the 2D rotation (in degrees) of the opacity map. ### opacityMapTiling ```ts opacityMapTiling: Vec2 ``` Controls the 2D tiling of the opacity map. ### opacityMapUv ```ts opacityMapUv: number ``` Opacity map UV channel. Valid values are 0 to 7. ### opacityShadowDither ```ts opacityShadowDither: string ``` Used to specify whether shadow opacity is dithered, which allows shadow transparency without alpha blending. Can be: - DITHER_NONE: Opacity dithering is disabled. - DITHER_BAYER2: Opacity is dithered using a Bayer 2 matrix. - DITHER_BAYER4: Opacity is dithered using a Bayer 4 matrix. - DITHER_BAYER8: Opacity is dithered using a Bayer 8 matrix. - DITHER_BAYER16: Opacity is dithered using a Bayer 16 matrix. - DITHER_BLUENOISE: Opacity is dithered using a blue noise. - DITHER_IGNNOISE: Opacity is dithered using an interleaved gradient noise. Defaults to DITHER_NONE. ### opacityVertexColor ```ts opacityVertexColor: boolean ``` Use mesh vertex colors for opacity. If opacityMap is set, it'll be multiplied by vertex colors. ### opacityVertexColorChannel ```ts opacityVertexColorChannel: string ``` Vertex color channels to use for opacity. Can be "r", "g", "b" or "a". ### parallaxMode ```ts parallaxMode: string ``` Selects how the height map is used to offset the UV of the other maps of the material. Can be: - PARALLAX_OFFSET: A single tap of the height map, which pivots the surface around the heightMapBase level of the map. - PARALLAX_OCCLUSION: The view ray is marched through the height field, which spans heightMapFactor of depth with the geometry sitting at the heightMapBase level. This represents deeper displacement without smearing, at the cost of multiple taps per pixel. Note that the silhouette of the mesh is not affected, and the depth buffer still sees the flat surface. Defaults to PARALLAX_OFFSET. ### pixelSnap ```ts pixelSnap: boolean ``` Align vertices to pixel coordinates when rendering. Useful for pixel perfect 2D graphics. ### refractionMap ```ts refractionMap: Texture | null ``` The map of the refraction visibility. ### refractionMapChannel ```ts refractionMapChannel: string ``` Color channels of the refraction map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### refractionMapOffset ```ts refractionMapOffset: Vec2 ``` Controls the 2D offset of the refraction map. Each component is between 0 and 1. ### refractionMapRotation ```ts refractionMapRotation: number ``` Controls the 2D rotation (in degrees) of the refraction map. ### refractionMapTiling ```ts refractionMapTiling: Vec2 ``` Controls the 2D tiling of the refraction map. ### refractionMapUv ```ts refractionMapUv: number ``` Refraction map UV channel. Valid values are 0 to 7. ### refractionVertexColor ```ts refractionVertexColor: boolean ``` Use mesh vertex colors for refraction. If refraction map is set, it will be multiplied by vertex colors. ### refractionVertexColorChannel ```ts refractionVertexColorChannel: string ``` Vertex color channel to use for refraction. Can be "r", "g", "b" or "a". ### shadowCatcher ```ts shadowCatcher: boolean ``` When enabled, the material will output accumulated directional shadow value in linear space as the color. ### sheenGlossInvert ```ts sheenGlossInvert: boolean ``` Invert the sheen gloss component (default is false). Enabling this flag results in material treating the sheen gloss members as roughness. ### sheenGlossMap ```ts sheenGlossMap: Texture | null ``` The sheen glossiness microstructure color map of the material (default is null). ### sheenGlossMapChannel ```ts sheenGlossMapChannel: string ``` Color channels of the sheen glossiness map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### sheenGlossMapOffset ```ts sheenGlossMapOffset: Vec2 ``` Controls the 2D offset of the sheen glossiness map. Each component is between 0 and 1. ### sheenGlossMapRotation ```ts sheenGlossMapRotation: number ``` Controls the 2D rotation (in degrees) of the sheen glossiness map. ### sheenGlossMapTiling ```ts sheenGlossMapTiling: Vec2 ``` Controls the 2D tiling of the sheen glossiness map. ### sheenGlossMapUv ```ts sheenGlossMapUv: number ``` Sheen glossiness map UV channel. Valid values are 0 to 7. ### sheenGlossVertexColor ```ts 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 ```ts sheenGlossVertexColorChannel: string ``` Vertex color channels to use for sheen glossiness. Can be "r", "g", "b" or "a". ### sheenMap ```ts sheenMap: Texture | null ``` The sheen microstructure color map of the material (default is null). ### sheenMapChannel ```ts sheenMapChannel: string ``` Color channels of the sheen map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### sheenMapOffset ```ts sheenMapOffset: Vec2 ``` Controls the 2D offset of the sheen map. Each component is between 0 and 1. ### sheenMapRotation ```ts sheenMapRotation: number ``` Controls the 2D rotation (in degrees) of the sheen map. ### sheenMapTiling ```ts sheenMapTiling: Vec2 ``` Controls the 2D tiling of the sheen map. ### sheenMapUv ```ts sheenMapUv: number ``` Sheen map UV channel. Valid values are 0 to 7. ### sheenVertexColor ```ts sheenVertexColor: boolean ``` Use mesh vertex colors for sheen. If sheen map or sheen tint are set, they'll be multiplied by vertex colors. ### sheenVertexColorChannel ```ts sheenVertexColorChannel: string ``` Vertex color channels to use for sheen. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### specularityFactorMap ```ts specularityFactorMap: Texture | null ``` The factor of specularity as a texture (default is null). ### specularityFactorMapChannel ```ts specularityFactorMapChannel: string ``` The channel used by the specularity factor texture to sample from (default is 'a'). ### specularityFactorMapOffset ```ts specularityFactorMapOffset: Vec2 ``` Controls the 2D offset of the specularity factor map. Each component is between 0 and 1. ### specularityFactorMapRotation ```ts specularityFactorMapRotation: number ``` Controls the 2D rotation (in degrees) of the specularity factor map. ### specularityFactorMapTiling ```ts specularityFactorMapTiling: Vec2 ``` Controls the 2D tiling of the specularity factor map. ### specularityFactorMapUv ```ts specularityFactorMapUv: number ``` Specularity factor map UV channel. Valid values are 0 to 7. ### specularityFactorTint ```ts 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 ```ts specularityFactorVertexColor: boolean ``` Use mesh vertex colors for specularity factor. If specularityFactorMap or are specularityFactorTint are set, they'll be multiplied by vertex colors. ### specularityFactorVertexColorChannel ```ts specularityFactorVertexColorChannel: string ``` Vertex color channels to use for specularity factor. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### specularMap ```ts specularMap: Texture | null ``` The specular map of the material (default is null). ### specularMapChannel ```ts specularMapChannel: string ``` Color channels of the specular map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### specularMapOffset ```ts specularMapOffset: Vec2 ``` Controls the 2D offset of the specular map. Each component is between 0 and 1. ### specularMapRotation ```ts specularMapRotation: number ``` Controls the 2D rotation (in degrees) of the specular map. ### specularMapTiling ```ts specularMapTiling: Vec2 ``` Controls the 2D tiling of the specular map. ### specularMapUv ```ts specularMapUv: number ``` Specular map UV channel. Valid values are 0 to 7. ### specularVertexColor ```ts specularVertexColor: boolean ``` Multiply specular by the mesh vertex colors. ### specularVertexColorChannel ```ts specularVertexColorChannel: string ``` Vertex color channels to use for specular. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. ### sphereMap ```ts sphereMap: Texture | null ``` The spherical environment map of the material (default is null). This will replace the scene lighting environment. ### thicknessMap ```ts thicknessMap: Texture | null ``` The per-pixel thickness of the medium, only used when useDynamicRefraction is enabled. ### thicknessMapChannel ```ts thicknessMapChannel: string ``` Color channels of the thickness map to use. Can be "r", "g", "b" or "a". ### thicknessMapOffset ```ts thicknessMapOffset: Vec2 ``` Controls the 2D offset of the thickness map. Each component is between 0 and 1. ### thicknessMapRotation ```ts thicknessMapRotation: number ``` Controls the 2D rotation (in degrees) of the thickness map. ### thicknessMapTiling ```ts thicknessMapTiling: Vec2 ``` Controls the 2D tiling of the thickness map. ### thicknessMapUv ```ts thicknessMapUv: number ``` Thickness map UV channel. Valid values are 0 to 7. ### thicknessVertexColor ```ts thicknessVertexColor: boolean ``` Use mesh vertex colors for thickness. If thickness map is set, it will be multiplied by vertex colors. ### thicknessVertexColorChannel ```ts thicknessVertexColorChannel: string ``` Vertex color channel to use for thickness. Can be "r", "g", "b" or "a". ### twoSidedLighting ```ts twoSidedLighting: boolean ``` Calculate proper normals (and therefore lighting) on backfaces. ### useDynamicRefraction ```ts useDynamicRefraction: boolean ``` Enables higher quality refractions using the grab pass instead of pre-computed cube maps for refractions. ### useFog ```ts useFog: boolean ``` Apply fogging (as configured in scene settings) ### useIridescence ```ts useIridescence: boolean ``` Enable thin-film iridescence. ### useLighting ```ts useLighting: boolean ``` Apply lighting ### useMetalness ```ts 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 ```ts useMetalnessSpecularColor: boolean ``` When metalness is enabled, use the specular map to apply color tint to specular reflections. ### useSheen ```ts useSheen: boolean ``` Toggle sheen specular effect on/off. ### useSkybox ```ts useSkybox: boolean ``` Apply scene skybox as prefiltered environment map ### useTonemap ```ts useTonemap: boolean ``` Apply tonemapping (as configured via CameraComponent#toneMapping). Defaults to true. ### vertexColorGamma ```ts 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. ## Accessors ### alphaDither ```ts get alphaDither(): number set alphaDither(value: number) ``` Gets the dither alpha of the material. ### alphaFade ```ts get alphaFade(): number set alphaFade(value: number) ``` Gets the alpha fade of the material. ### alphaTest ```ts get alphaTest(): number set alphaTest(value: number) ``` Gets the alpha test reference value. ### ambient ```ts get ambient(): Color set ambient(value: Color) ``` Gets the ambient color of the material. ### anisotropyIntensity ```ts get anisotropyIntensity(): number set anisotropyIntensity(value: number) ``` Gets the anisotropy intensity of the material. ### anisotropyRotation ```ts get anisotropyRotation(): number set anisotropyRotation(value: number) ``` Gets the anisotropy rotation of the material. ### aoIntensity ```ts get aoIntensity(): number set aoIntensity(value: number) ``` Gets the ambient occlusion intensity of the material. ### attenuation ```ts get attenuation(): Color set attenuation(value: Color) ``` Gets the attenuation color of the material. ### attenuationDistance ```ts get attenuationDistance(): number set attenuationDistance(value: number) ``` Gets the attenuation distance of the material. ### bumpiness ```ts get bumpiness(): number set bumpiness(value: number) ``` Gets the bumpiness of the material. ### clearCoat ```ts get clearCoat(): number set clearCoat(value: number) ``` Gets the clearcoat intensity of the material. ### clearCoatBumpiness ```ts get clearCoatBumpiness(): number set clearCoatBumpiness(value: number) ``` Gets the clearcoat bumpiness of the material. ### clearCoatGloss ```ts get clearCoatGloss(): number set clearCoatGloss(value: number) ``` Gets the clearcoat glossiness of the material. ### cubeMapProjectionBox ```ts 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](https://api.playcanvas.com/engine/classes/StandardMaterial.md#update). ### diffuse ```ts get diffuse(): Color set diffuse(value: Color) ``` Gets the diffuse color of the material. ### dispersion ```ts get dispersion(): number set dispersion(value: number) ``` Gets the dispersion of the material. ### emissive ```ts get emissive(): Color set emissive(value: Color) ``` Gets the emissive color of the material. ### emissiveIntensity ```ts get emissiveIntensity(): number set emissiveIntensity(value: number) ``` Gets the emissive color multiplier. ### gloss ```ts get gloss(): number set gloss(value: number) ``` Gets the glossiness of the material. ### heightMapBase ```ts get heightMapBase(): number set heightMapBase(value: number) ``` Gets the height map base level of the material. ### heightMapFactor ```ts get heightMapFactor(): number set heightMapFactor(value: number) ``` Gets the height map factor of the material. ### iridescence ```ts get iridescence(): number set iridescence(value: number) ``` Gets the iridescence intensity of the material. ### iridescenceRefractionIndex ```ts get iridescenceRefractionIndex(): number set iridescenceRefractionIndex(value: number) ``` Gets the index of refraction of the iridescent thin-film of the material. ### iridescenceThicknessMax ```ts get iridescenceThicknessMax(): number set iridescenceThicknessMax(value: number) ``` Gets the maximum iridescence thickness of the material. ### iridescenceThicknessMin ```ts get iridescenceThicknessMin(): number set iridescenceThicknessMin(value: number) ``` Gets the minimum iridescence thickness of the material. ### metalness ```ts get metalness(): number set metalness(value: number) ``` Gets the metalness of the material. ### normalDetailMapBumpiness ```ts get normalDetailMapBumpiness(): number set normalDetailMapBumpiness(value: number) ``` Gets the detail normal map bumpiness of the material. ### occludeSpecularIntensity ```ts get occludeSpecularIntensity(): number set occludeSpecularIntensity(value: number) ``` Gets the specular occlusion intensity of the material. ### opacity ```ts get opacity(): number set opacity(value: number) ``` Gets the opacity of the material. ### parallaxSamples ```ts get parallaxSamples(): number set parallaxSamples(value: number) ``` Gets the maximum number of height map taps of parallax occlusion mapping of the material. ### parallaxShadowSamples ```ts get parallaxShadowSamples(): number set parallaxShadowSamples(value: number) ``` Gets the maximum number of height map taps of the parallax self shadowing of the material. ### reflectivity ```ts get reflectivity(): number set reflectivity(value: number) ``` Gets the environment map intensity of the material. ### refraction ```ts get refraction(): number set refraction(value: number) ``` Gets the refraction of the material. ### refractionIndex ```ts get refractionIndex(): number set refractionIndex(value: number) ``` Gets the index of refraction of the material. ### sheen ```ts get sheen(): Color set sheen(value: Color) ``` Gets the sheen color of the material. ### sheenGloss ```ts get sheenGloss(): number set sheenGloss(value: number) ``` Gets the sheen glossiness of the material. ### specular ```ts get specular(): Color set specular(value: Color) ``` Gets the specular color of the material. ### specularityFactor ```ts get specularityFactor(): number set specularityFactor(value: number) ``` Gets the specularity factor of the material. ### thickness ```ts get thickness(): number set thickness(value: number) ``` Gets the thickness of the medium of the material. ## Methods ### copy ```ts copy(source: StandardMaterial): StandardMaterial ``` Copy a `StandardMaterial`. **Parameters** - `source` ([`StandardMaterial`](https://api.playcanvas.com/engine/classes/StandardMaterial.md)): The material to copy from. **Returns** [`StandardMaterial`](https://api.playcanvas.com/engine/classes/StandardMaterial.md): The destination material. ### destroy ```ts 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 ```ts 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** ```ts mesh.setVertexStream(SEMANTIC_ATTR15, offset, 3); material.setAttribute('offset', SEMANTIC_ATTR15); ``` ### update ```ts update(): void ``` ## Inherited from [Material](https://api.playcanvas.com/engine/classes/Material.md) - `alphaToCoverage: boolean = false` - `cull: number = CULLFACE_BACK` - `frontFace: number = FRONTFACE_CCW` - `name: string = 'Untitled'` - `stencilBack: StencilParameters | null = null` - `stencilFront: StencilParameters | null = null` - `userId: string = ''` - `get alphaWrite(): boolean` · `set alphaWrite(value: boolean)` - `get blendState(): Readonly` · `set blendState(value: Readonly)` - `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(): void` - `protected _markPropertyModified(property: MaterialProperty): void` - `protected _markPropertyMutable(property: MaterialProperty, value: any): void` - `clone(): StandardMaterial` - `deleteParameter(name: string): void` - `getDefine(name: string): boolean` - `getParameter(name: string): any` - `getShaderChunks(shaderLanguage?: string): ShaderChunkMap` - `setDefine(name: string, value: string | boolean | undefined): void` - `setParameter(name: string, data: number | number[] | ArrayBufferView | Texture | StorageBuffer): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/StandardMaterialOptions.md # StandardMaterialOptions Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material-options.js#L10 The standard material options define a set of options used to control the shader frontend shader generation, such as textures, tints and multipliers. ## Properties ### clearCoatGlossInvert ```ts clearCoatGlossInvert: boolean = false ``` Invert the clearcoat gloss channel. ### clearCoatPackedNormal ```ts clearCoatPackedNormal: boolean = false ``` If normal clear coat map contains X in RGB, Y in Alpha, and Z must be reconstructed. ### defines ```ts defines: Map ``` The set of defines used to generate the shader. ### forceUv1 ```ts 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 ```ts glossInvert: boolean = false ``` Invert the gloss channel. ### glossTint ```ts glossTint: boolean = false ``` Defines if [StandardMaterial#gloss](https://api.playcanvas.com/engine/classes/StandardMaterial.md#gloss) constant should affect glossiness value. ### litOptions ```ts litOptions: LitShaderOptions ``` Storage for the options for lit the shader and material. ### metalnessTint ```ts metalnessTint: boolean = false ``` Defines if [StandardMaterial#metalness](https://api.playcanvas.com/engine/classes/StandardMaterial.md#metalness) constant should affect metalness value. ### normalDetailPackedNormal ```ts normalDetailPackedNormal: boolean = false ``` If normal detail map contains X in RGB, Y in Alpha, and Z must be reconstructed. ### packedNormal ```ts packedNormal: boolean = false ``` If normal map contains X in RGB, Y in Alpha, and Z must be reconstructed. ### sheenGlossInvert ```ts sheenGlossInvert: boolean = false ``` Invert the sheen gloss channel. ### useAO ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/Lightmapper.md). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/StencilParameters.md # StencilParameters Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/stencil-parameters.js#L11 Holds stencil test settings. ## Constructors ### constructor ```ts new StencilParameters(options?: any) ``` Create a new StencilParameters instance. **Parameters** - `options` (`any`, optional, default `{}`): Options object to configure the stencil parameters. ## Properties ### DEFAULT ```ts static readonly DEFAULT: StencilParameters ``` A default stencil state. ## Accessors ### fail ```ts get fail(): number set fail(value: number) ``` Gets the operation to perform if stencil test is failed. ### func ```ts get func(): number set func(value: number) ``` Sets the comparison function that decides if the pixel should be written. ### readMask ```ts get readMask(): number set readMask(value: number) ``` Gets the mask applied to stencil buffer value and reference value before comparison. ### ref ```ts get ref(): number set ref(value: number) ``` Gets the stencil test reference value used in comparisons. ### writeMask ```ts get writeMask(): number set writeMask(value: number) ``` Gets the bit mask applied to the stencil value when written. ### zfail ```ts get zfail(): number set zfail(value: number) ``` Gets the operation to perform if depth test is failed. ### zpass ```ts get zpass(): number set zpass(value: number) ``` Gets the operation to perform if both stencil and depth test are passed. ## Methods ### clone ```ts clone(): StencilParameters ``` Clone the stencil parameters. **Returns** [`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md): A cloned StencilParameters object. ### copy ```ts copy(rhs: StencilParameters): StencilParameters ``` Copies the contents of a source stencil parameters to this stencil parameters. **Parameters** - `rhs` ([`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md)): A stencil parameters to copy from. **Returns** [`StencilParameters`](https://api.playcanvas.com/engine/classes/StencilParameters.md): Self for chaining. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/StorageBuffer.md # StorageBuffer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/storage-buffer.js#L26 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](https://api.playcanvas.com/engine/variables/TRACEID_BUFFERS.md) trace channel is enabled), call sites may assign the instance's `name` property to a descriptive string. ## Constructors ### constructor ```ts new StorageBuffer(graphicsDevice: GraphicsDevice, byteSize: number, bufferUsage?: number, addStorageUsage?: boolean) ``` Create a new StorageBuffer instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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](https://api.playcanvas.com/engine/variables/BUFFERUSAGE_READ.md), [BUFFERUSAGE_WRITE](https://api.playcanvas.com/engine/variables/BUFFERUSAGE_WRITE.md), [BUFFERUSAGE_COPY_SRC](https://api.playcanvas.com/engine/variables/BUFFERUSAGE_COPY_SRC.md) and [BUFFERUSAGE_COPY_DST](https://api.playcanvas.com/engine/variables/BUFFERUSAGE_COPY_DST.md) 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. ## Methods ### clear ```ts 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 ```ts copy(srcBuffer: StorageBuffer, srcOffset?: number, dstOffset?: number, size?: number): void ``` Copy data from another storage buffer into this storage buffer. **Parameters** - `srcBuffer` ([`StorageBuffer`](https://api.playcanvas.com/engine/classes/StorageBuffer.md)): 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 ```ts destroy(): void ``` Frees resources associated with this storage buffer. ### read ```ts read(offset?: number, size?: number, data?: ArrayBufferView | null, immediate?: boolean): Promise> ``` 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 | 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>`: 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 ```ts write(bufferOffset?: number, data: ArrayBuffer | ArrayBufferView, 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`): 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Texture.md # Texture Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/texture.js#L70 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 [Material](https://api.playcanvas.com/engine/classes/Material.md)s and sampled in [Shader](https://api.playcanvas.com/engine/classes/Shader.md)s (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: 1. **As textures**: - float (i.e. [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md)), half-float (i.e. [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md)) and small-float ([PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md)) formats are always supported on both WebGL2 and WebGPU with point sampling. - half-float and small-float formats are always supported on WebGL2 and WebGPU with linear sampling. - float formats are supported on WebGL2 and WebGPU with linear sampling only if [GraphicsDevice#textureFloatFilterable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatfilterable) is true. - [PIXELFORMAT_RGB9E5](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB9E5.md) is a compact HDR format with shared exponent, supported for sampling on both WebGL2 and WebGPU, but cannot be used as a render target. 2. **As renderable textures** that can be used as color buffers in a [RenderTarget](https://api.playcanvas.com/engine/classes/RenderTarget.md): - on WebGPU, rendering to float and half-float formats is always supported. - on WebGPU, rendering to small-float format is supported only if [GraphicsDevice#textureRG11B10Renderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturerg11b10renderable) is true. - on WebGL2, rendering to these 3 formats is supported only if [GraphicsDevice#textureFloatRenderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatrenderable) is true. - on WebGL2, if [GraphicsDevice#textureFloatRenderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatrenderable) is false, but [GraphicsDevice#textureHalfFloatRenderable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturehalffloatrenderable) is true, rendering to half-float formats only is supported. This is the case of many mobile iOS devices. - you can determine available renderable HDR format using [GraphicsDevice#getRenderableHdrFormat](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#getrenderablehdrformat). - [PIXELFORMAT_RGB10A2](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB10A2.md) provides 10 bits per RGB channel with 2-bit alpha, offering higher precision than [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md) at the same memory cost. It is renderable on both WebGL2 and WebGPU. [PIXELFORMAT_RGB10A2U](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB10A2U.md) is the unsigned integer variant. ## Constructors ### constructor ```ts new Texture(graphicsDevice: GraphicsDevice, options?: object) ``` Create a new Texture instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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](https://api.playcanvas.com/engine/variables/ADDRESS_REPEAT.md). - `options.addressV` (`number`, optional): The repeat mode to use in the V direction. Defaults to [ADDRESS_REPEAT](https://api.playcanvas.com/engine/variables/ADDRESS_REPEAT.md). - `options.addressW` (`number`, optional): The repeat mode to use in the W direction. Defaults to [ADDRESS_REPEAT](https://api.playcanvas.com/engine/variables/ADDRESS_REPEAT.md). - `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: - [FUNC_LESS](https://api.playcanvas.com/engine/variables/FUNC_LESS.md) - [FUNC_LESSEQUAL](https://api.playcanvas.com/engine/variables/FUNC_LESSEQUAL.md) - [FUNC_GREATER](https://api.playcanvas.com/engine/variables/FUNC_GREATER.md) - [FUNC_GREATEREQUAL](https://api.playcanvas.com/engine/variables/FUNC_GREATEREQUAL.md) - [FUNC_EQUAL](https://api.playcanvas.com/engine/variables/FUNC_EQUAL.md) - [FUNC_NOTEQUAL](https://api.playcanvas.com/engine/variables/FUNC_NOTEQUAL.md) Defaults to [FUNC_LESS](https://api.playcanvas.com/engine/variables/FUNC_LESS.md). - `options.compareOnRead` (`boolean`, optional): When enabled, and if texture format is [PIXELFORMAT_DEPTH](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH.md) or [PIXELFORMAT_DEPTHSTENCIL](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTHSTENCIL.md), 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: - [PIXELFORMAT_R8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8.md) - [PIXELFORMAT_RG8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8.md) - [PIXELFORMAT_RGB565](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB565.md) - [PIXELFORMAT_RGBA5551](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA5551.md) - [PIXELFORMAT_RGBA4](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA4.md) - [PIXELFORMAT_RGB8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB8.md) - [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md) - [PIXELFORMAT_DXT1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT1.md) - [PIXELFORMAT_DXT3](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT3.md) - [PIXELFORMAT_DXT5](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT5.md) - [PIXELFORMAT_RGB16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB16F.md) - [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md) - [PIXELFORMAT_RGB32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB32F.md) - [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md) - [PIXELFORMAT_ETC1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC1.md) - [PIXELFORMAT_PVRTC_2BPP_RGB_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGB_1.md) - [PIXELFORMAT_PVRTC_2BPP_RGBA_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGBA_1.md) - [PIXELFORMAT_PVRTC_4BPP_RGB_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGB_1.md) - [PIXELFORMAT_PVRTC_4BPP_RGBA_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGBA_1.md) - [PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md) - [PIXELFORMAT_ASTC_4x4](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ASTC_4x4.md) - [PIXELFORMAT_ATC_RGB](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGB.md) - [PIXELFORMAT_ATC_RGBA](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGBA.md) Defaults to [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md). - `options.height` (`number`, optional): The height of the texture in pixels. Defaults to 4. - `options.levels` (`Uint8Array[] | Uint8ClampedArray[] | Uint16Array[] | Uint32Array[] | Float32Array[] | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | Uint8Array[][]`, 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](https://api.playcanvas.com/engine/variables/FILTER_LINEAR.md). - `options.minFilter` (`number`, optional): The minification filter type to use. Defaults to [FILTER_LINEAR_MIPMAP_LINEAR](https://api.playcanvas.com/engine/variables/FILTER_LINEAR_MIPMAP_LINEAR.md). - `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: - [TEXTUREPROJECTION_NONE](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_NONE.md) - [TEXTUREPROJECTION_CUBE](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_CUBE.md) - [TEXTUREPROJECTION_EQUIRECT](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_EQUIRECT.md) - [TEXTUREPROJECTION_OCTAHEDRAL](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_OCTAHEDRAL.md) Defaults to [TEXTUREPROJECTION_CUBE](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_CUBE.md) if options.cubemap is true, otherwise [TEXTUREPROJECTION_NONE](https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_NONE.md). - `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: - [TEXTURETYPE_DEFAULT](https://api.playcanvas.com/engine/variables/TEXTURETYPE_DEFAULT.md) - [TEXTURETYPE_RGBM](https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBM.md) - [TEXTURETYPE_RGBE](https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBE.md) - [TEXTURETYPE_RGBP](https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBP.md) - [TEXTURETYPE_SWIZZLEGGGR](https://api.playcanvas.com/engine/variables/TEXTURETYPE_SWIZZLEGGGR.md) Defaults to [TEXTURETYPE_DEFAULT](https://api.playcanvas.com/engine/variables/TEXTURETYPE_DEFAULT.md). - `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** ```ts // 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(); ``` ## Properties ### _invalid ```ts protected _invalid: boolean = false ``` ### _lockedLevel ```ts protected _lockedLevel: number = -1 ``` ### _lockedMode ```ts protected _lockedMode: number = TEXTURELOCK_NONE ``` ### _numLevels ```ts protected _numLevels: number = 0 ``` ### _numLevelsRequested ```ts protected _numLevelsRequested: number | undefined ``` ### _samples ```ts protected _samples: number = 1 ``` The number of MSAA samples of the texture, 1 if not multisampled. ### _storage ```ts protected _storage: boolean = false ``` ### id ```ts protected id: number ``` ### name ```ts name: string ``` The name of the texture. ## Accessors ### addressU ```ts get addressU(): number set addressU(v: number) ``` Gets the addressing mode to be applied to the texture horizontally. ### addressV ```ts get addressV(): number set addressV(v: number) ``` Gets the addressing mode to be applied to the texture vertically. ### addressW ```ts get addressW(): number set addressW(addressW: number) ``` Gets the addressing mode to be applied to the 3D texture depth. ### anisotropy ```ts get anisotropy(): number set anisotropy(v: number) ``` Gets the integer value specifying the level of anisotropy to apply to the texture. ### array ```ts get array(): boolean ``` Returns true if this texture is a 2D texture array and false otherwise. ### arrayLength ```ts get arrayLength(): number ``` Returns the number of textures inside this texture if this is a 2D array texture or 0 otherwise. ### compareFunc ```ts get compareFunc(): number set compareFunc(v: number) ``` Gets the comparison function when [compareOnRead](https://api.playcanvas.com/engine/classes/Texture.md#compareonread) is enabled. ### compareOnRead ```ts get compareOnRead(): boolean set compareOnRead(v: boolean) ``` Gets whether you can get filtered results of comparison using texture() in your shader. ### cubemap ```ts get cubemap(): boolean ``` Returns true if this texture is a cube map and false otherwise. ### depth ```ts get depth(): number ``` The number of depth slices in a 3D texture. ### flipY ```ts get flipY(): boolean set flipY(flipY: boolean) ``` Gets whether the texture should be flipped in the Y-direction. ### format ```ts get format(): number ``` The pixel format of the texture. Can be: - [PIXELFORMAT_R8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8.md) - [PIXELFORMAT_RG8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8.md) - [PIXELFORMAT_RGB565](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB565.md) - [PIXELFORMAT_RGBA5551](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA5551.md) - [PIXELFORMAT_RGBA4](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA4.md) - [PIXELFORMAT_RGB8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB8.md) - [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md) - [PIXELFORMAT_DXT1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT1.md) - [PIXELFORMAT_DXT3](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT3.md) - [PIXELFORMAT_DXT5](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT5.md) - [PIXELFORMAT_RGB16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB16F.md) - [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md) - [PIXELFORMAT_RGB32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB32F.md) - [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md) - [PIXELFORMAT_ETC1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC1.md) - [PIXELFORMAT_PVRTC_2BPP_RGB_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGB_1.md) - [PIXELFORMAT_PVRTC_2BPP_RGBA_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGBA_1.md) - [PIXELFORMAT_PVRTC_4BPP_RGB_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGB_1.md) - [PIXELFORMAT_PVRTC_4BPP_RGBA_1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGBA_1.md) - [PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md) - [PIXELFORMAT_ASTC_4x4](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ASTC_4x4.md) - [PIXELFORMAT_ATC_RGB](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGB.md) - [PIXELFORMAT_ATC_RGBA](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGBA.md) ### height ```ts get height(): number ``` The height of the texture in pixels. ### magFilter ```ts get magFilter(): number set magFilter(v: number) ``` Gets the magnification filter to be applied to the texture. ### minFilter ```ts get minFilter(): number set minFilter(v: number) ``` Gets the minification filter to be applied to the texture. ### mipmaps ```ts get mipmaps(): boolean set mipmaps(v: boolean) ``` Gets whether the texture should generate/upload mipmaps. ### numLevels ```ts get numLevels(): number ``` Gets the number of mip levels. ### pot ```ts get pot(): boolean ``` Returns true if all dimensions of the texture are power of two, and false otherwise. ### samples ```ts 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`. ### srgb ```ts 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. ### storage ```ts get storage(): boolean ``` Defines if texture can be used as a storage texture by a compute shader. ### volume ```ts get volume(): boolean ``` Returns true if this texture is a 3D volume and false otherwise. ### width ```ts get width(): number ``` The width of the texture in pixels. ## Methods ### copy ```ts 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`](https://api.playcanvas.com/engine/classes/Texture.md)): 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`](https://api.playcanvas.com/engine/classes/RenderTarget.md), 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 ```ts destroy(): void ``` Frees resources associated with this texture. ### getSource ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/TextureView.md): A new TextureView for this texture. **Example** ```ts // Create a view for mip level 1 const mip1View = texture.getView(1); // Use with compute shader compute.setParameter('outputTexture', mip1View); ``` ### lock ```ts lock(options?: object): Uint8Array | Uint16Array | Uint32Array | Float32Array ``` 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: - [TEXTURELOCK_READ](https://api.playcanvas.com/engine/variables/TEXTURELOCK_READ.md) - [TEXTURELOCK_WRITE](https://api.playcanvas.com/engine/variables/TEXTURELOCK_WRITE.md) Defaults to [TEXTURELOCK_WRITE](https://api.playcanvas.com/engine/variables/TEXTURELOCK_WRITE.md). **Returns** `Uint8Array | Uint16Array | Uint32Array | Float32Array`: A typed array containing the pixel data of the locked mip level. ### read ```ts read(x: number, y: number, width: number, height: number, options?: object): Promise | Uint16Array | Uint32Array | Float32Array> ``` 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 | Uint16Array | Uint32Array | Float32Array`, 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`](https://api.playcanvas.com/engine/classes/RenderTarget.md), 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 | Uint16Array | Uint32Array | Float32Array>`: A promise that resolves with the pixel data of the texture. ### setSource ```ts 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. `
`) as a source requires [GraphicsDevice#supportsHtmlTextures](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#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 ```ts unlock(): void ``` Unlocks the currently locked mip level and uploads it to VRAM. ### upload ```ts upload(): void ``` Forces a reupload of the texture's pixel data to graphics memory. Ordinarily, this function is called internally by [setSource](https://api.playcanvas.com/engine/classes/Texture.md#setsource) and [unlock](https://api.playcanvas.com/engine/classes/Texture.md#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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureAtlas.md # TextureAtlas Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/texture-atlas.js#L15 A TextureAtlas contains a number of frames from a texture. Each frame defines a region in a texture. The TextureAtlas is referenced by [Sprite](https://api.playcanvas.com/engine/classes/Sprite.md)s. ## Constructors ### constructor ```ts new TextureAtlas() ``` Create a new TextureAtlas instance. **Example** ```ts 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) } }; ``` ## Accessors ### frames ```ts get frames(): any set frames(value: any) ``` Gets the frames which define portions of the texture atlas. ### texture ```ts get texture(): Texture set texture(value: Texture) ``` Gets the texture used by the atlas. ## Methods ### destroy ```ts destroy(): void ``` Free up the underlying texture owned by the atlas. ### removeFrame ```ts removeFrame(key: string): void ``` Removes a frame from the texture atlas. **Parameters** - `key` (`string`): The key of the frame. **Example** ```ts atlas.removeFrame('1'); ``` ### setFrame ```ts 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. - `data.border` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The border of the frame for 9-slicing. Values are ordered as follows: left, bottom, right, top border in pixels. - `data.pivot` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The pivot of the frame - values are between 0-1. - `data.rect` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The u, v, width, height properties of the frame in pixels. **Example** ```ts atlas.setFrame('1', { rect: new Vec4(0, 0, 128, 128), pivot: new Vec2(0.5, 0.5), border: new Vec4(5, 5, 5, 5) }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureParser.md # TextureParser Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/texture/texture.js#L14 Interface to a texture parser. Implementations of this interface handle the loading and opening of texture assets. ## Methods ### load ```ts load(url: object, callback: ResourceHandlerCallback, asset?: Asset): 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`](https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md)): The callback used when the resource is loaded or an error occurs. - `asset` ([`Asset`](https://api.playcanvas.com/engine/classes/Asset.md)``, optional): Optional asset that is passed by ResourceLoader. ### open ```ts open(url: string, data: any, device: GraphicsDevice): Texture ``` Convert raw resource data into a [Texture](https://api.playcanvas.com/engine/classes/Texture.md). **Parameters** - `url` (`string`): The URL of the resource to open. - `data` (`any`): The raw resource data passed by callback from [ResourceHandler#load](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load). - `device` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. **Returns** [`Texture`](https://api.playcanvas.com/engine/classes/Texture.md): The parsed resource data. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureRenderer.md # TextureRenderer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/texture-renderer.js#L113 Displays textures for a single frame, for debugging. Call [draw](https://api.playcanvas.com/engine/classes/TextureRenderer.md#draw) or [sceneDepth](https://api.playcanvas.com/engine/classes/TextureRenderer.md#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](https://api.playcanvas.com/engine/classes/TextureRenderer.md#channels) selection, and single-channel formats such as [PIXELFORMAT_R8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8.md) display their channel as grayscale. Other selections display stored channel values, including alpha, as opaque previews. Depth textures using [PIXELFORMAT_DEPTH](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH.md), [PIXELFORMAT_DEPTH16](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH16.md) or [PIXELFORMAT_DEPTHSTENCIL](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTHSTENCIL.md) are displayed as raw grayscale values. Use [sceneDepth](https://api.playcanvas.com/engine/classes/TextureRenderer.md#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](https://api.playcanvas.com/engine/classes/TextureRenderer.md#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](https://api.playcanvas.com/engine/classes/TextureRenderer.md#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** ```ts const textures = new TextureRenderer(app); app.on('update', () => { textures.draw(texture, 0.7, 0.7, 0.25, 0.25); }); ``` **Example** ```ts // 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); }); ``` ## Constructors ### constructor ```ts new TextureRenderer(app: AppBase) ``` Creates a debug texture renderer. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application to render into and bind resource lifetime to. ## Properties ### camera ```ts 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 ```ts 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. ## Accessors ### channels ```ts set channels(value: string) ``` Channels displayed by subsequent [draw](https://api.playcanvas.com/engine/classes/TextureRenderer.md#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](https://api.playcanvas.com/engine/classes/TextureRenderer.md#scenedepth). Invalid values leave the previous selection unchanged. **Example** ```ts textures.channels = 'aaa'; textures.draw(texture, 0, 0, 0.25, 0.25); ``` ## Methods ### destroy ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/TextureRenderer.md#channels) is 'rgb'. Other selections display stored channel values. Raw depth is shown as grayscale without projection-dependent linearization; use [sceneDepth](https://api.playcanvas.com/engine/classes/TextureRenderer.md#scenedepth) for camera depth. Texture row 0 is displayed at the top. For rendered textures, use [RENDERTARGET_ORIGIN_TOP](https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md) 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`](https://api.playcanvas.com/engine/classes/Texture.md)): 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 ```ts 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TextureView.md # TextureView Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/texture-view.js#L19 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](https://api.playcanvas.com/engine/classes/Texture.md#getview). Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound and this class has no effect. ## Properties ### arrayLayerCount ```ts readonly arrayLayerCount: number ``` The number of array layers accessible to the view. ### baseArrayLayer ```ts readonly baseArrayLayer: number ``` The first array layer accessible to the view. ### baseMipLevel ```ts readonly baseMipLevel: number ``` The first mip level accessible to the view. ### mipLevelCount ```ts readonly mipLevelCount: number ``` The number of mip levels accessible to the view. ### texture ```ts readonly texture: Texture ``` The texture this view references. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TorusGeometry.md # TorusGeometry Class · extends [`Geometry`](https://api.playcanvas.com/engine/classes/Geometry.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/torus-geometry.js#L34 A procedural torus-shaped geometry. Typically, you would: 1. Create a TorusGeometry instance. 2. Generate a [Mesh](https://api.playcanvas.com/engine/classes/Mesh.md) from the geometry. 3. Create a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) referencing the mesh. 4. Create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) with a [RenderComponent](https://api.playcanvas.com/engine/classes/RenderComponent.md) and assign the [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md) to it. 5. Add the entity to the [Scene](https://api.playcanvas.com/engine/classes/Scene.md). ```javascript // 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); ``` ## Constructors ### constructor ```ts 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** ```ts const geometry = new TorusGeometry({ tubeRadius: 1, ringRadius: 2, sectorAngle: 360, segments: 30, sides: 20 }); ``` ## Inherited from [Geometry](https://api.playcanvas.com/engine/classes/Geometry.md) - `blendIndices: ArrayLike | undefined` - `blendWeights: ArrayLike | undefined` - `colors: ArrayLike | undefined` - `tangents: ArrayLike | undefined` - `calculateNormals(): void` - `calculateTangents(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TransformFeedback.md # TransformFeedback Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/transform-feedback.js#L89 This object allows you to configure and use the transform feedback feature (WebGL2 only). How to use: 1. First, check that you're on WebGL2, by looking at the `app.graphicsDevice.isWebGL2`` value. 2. Define the outputs in your vertex shader. The syntax is `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. 3. Create the shader using `TransformFeedback.createShader(device, vsCode, yourShaderName)`. 4. Create/acquire the input vertex buffer. Can be any VertexBuffer, either manually created, or from a Mesh. 5. Create the TransformFeedback object: `const tf = new TransformFeedback(inputBuffer)`. This object will internally create an output buffer. 6. Run the shader: `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. ```javascript // *** 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; } ``` ```javascript // *** 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); }; ``` ## Constructors ### constructor ```ts new TransformFeedback(inputBuffer: VertexBuffer | TransformFeedbackStream[], outputBuffer?: VertexBuffer, usage?: number) ``` Create a new TransformFeedback instance. **Parameters** - `inputBuffer` ([`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md) `|` [`TransformFeedbackStream`](https://api.playcanvas.com/engine/interfaces/TransformFeedbackStream.md)`[]`): 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`](https://api.playcanvas.com/engine/classes/VertexBuffer.md), 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: - [BUFFER_STATIC](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md) - [BUFFER_DYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md) - [BUFFER_STREAM](https://api.playcanvas.com/engine/variables/BUFFER_STREAM.md) - [BUFFER_GPUDYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_GPUDYNAMIC.md) Defaults to [BUFFER_GPUDYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_GPUDYNAMIC.md) (which is recommended for continuous update). **Example** ```ts // 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 ]); ``` ## Accessors ### inputBuffer ```ts get inputBuffer(): VertexBuffer ``` The current input buffer. When multiple input buffers are used, this is the first one - see [TransformFeedback#inputBuffers](https://api.playcanvas.com/engine/classes/TransformFeedback.md#inputbuffers). ### inputBuffers ```ts get inputBuffers(): VertexBuffer[] ``` The buffers read by the shader, in the order they were supplied. ### outputBuffer ```ts get outputBuffer(): VertexBuffer ``` The current output buffer. When multiple output buffers are used, this is the first one - see [TransformFeedback#outputBuffers](https://api.playcanvas.com/engine/classes/TransformFeedback.md#outputbuffers). ### outputBuffers ```ts get outputBuffers(): VertexBuffer[] ``` The buffers written by transform feedback, in the order of the captured varyings. ## Methods ### destroy ```ts destroy(): void ``` Destroys the transform feedback helper object. ### process ```ts 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`](https://api.playcanvas.com/engine/classes/Shader.md)): A vertex shader to run. Should be created with [TransformFeedback.createShader](https://api.playcanvas.com/engine/classes/TransformFeedback.md#createshader). - `swap` (`boolean`, optional, default `true`): Swap input/output buffer data. Useful for continuous buffer processing. Default is true. ### createShader ```ts 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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): 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](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_INTERLEAVED.md) to pack all captured varyings into a single buffer, or [TRANSFORM_FEEDBACK_SEPARATE](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_SEPARATE.md) to store each varying in its own buffer. This setting is only effective when useTransformFeedback property is enabled. Defaults to [TRANSFORM_FEEDBACK_INTERLEAVED](https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_INTERLEAVED.md). **Returns** [`Shader`](https://api.playcanvas.com/engine/classes/Shader.md): A shader to use in the process() function. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/UniformBufferFormat.md # UniformBufferFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/uniform-buffer-format.js#L256 A descriptor that defines the layout of data inside the uniform buffer. ## Constructors ### constructor ```ts new UniformBufferFormat(graphicsDevice: GraphicsDevice, uniforms: UniformFormat[], options?: object) ``` Create a new UniformBufferFormat instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device. - `uniforms` ([`UniformFormat`](https://api.playcanvas.com/engine/classes/UniformFormat.md)`[]`): 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. ## Properties ### uniforms ```ts uniforms: UniformFormat[] ``` ## Methods ### get ```ts 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`](https://api.playcanvas.com/engine/classes/UniformFormat.md) `| undefined`: - The format of the uniform. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/UniformFormat.md # UniformFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/uniform-buffer-format.js#L48 A class storing description of an individual uniform, stored inside a uniform buffer. ## Constructors ### constructor ```ts 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). ## Accessors ### isArrayType ```ts get isArrayType(): boolean ``` True if this is an array of elements (i.e. count > 0) -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/VertexBuffer.md # VertexBuffer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-buffer.js#L18 A vertex buffer is the mechanism via which the application specifies vertex data to the graphics hardware. ## Constructors ### constructor ```ts new VertexBuffer(graphicsDevice: GraphicsDevice, format: VertexFormat, numVertices: number, options?: object, ...args: any[]) ``` Create a new VertexBuffer instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to manage this vertex buffer. - `format` ([`VertexFormat`](https://api.playcanvas.com/engine/classes/VertexFormat.md)): 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`, 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[]`) ## Methods ### destroy ```ts destroy(): void ``` Frees resources associated with this vertex buffer. ### getFormat ```ts getFormat(): VertexFormat ``` Returns the data format of the specified vertex buffer. **Returns** [`VertexFormat`](https://api.playcanvas.com/engine/classes/VertexFormat.md): The data format of the specified vertex buffer. ### getNumVertices ```ts 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 ```ts 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](https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md), modified repeatedly and used many times [BUFFER_DYNAMIC](https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md) or modified once and used at most a few times [BUFFER_STREAM](https://api.playcanvas.com/engine/variables/BUFFER_STREAM.md). **Returns** `number`: The usage type of the vertex buffer (see BUFFER_*). ### lock ```ts lock(): ArrayBuffer | ArrayBufferView ``` Returns a mapped memory block representing the content of the vertex buffer. **Returns** `ArrayBuffer | ArrayBufferView`: The memory that stores the buffer's vertices. This matches whatever was supplied as the initial data: an [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) when none was provided, otherwise the [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or typed array that was passed in. Use [ArrayBufferConstructor.isView](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView) to distinguish the two before accessing it. ### setData ```ts setData(data?: ArrayBuffer | ArrayBufferView): boolean ``` Sets the data of the vertex buffer and uploads it to the GPU. **Parameters** - `data` (`ArrayBuffer | ArrayBufferView`, optional): Source data. Can be an [ArrayBuffer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or a typed array. Stored by reference, not copied. **Returns** `boolean`: True if function finished successfully, false otherwise. ### unlock ```ts 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** ```ts // After modifying bytes 16 through 31 of the CPU storage: vertexBuffer.unlock(16, 16); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/VertexFormat.md # VertexFormat Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-format.js#L69 A vertex format is a descriptor that defines the layout of vertex data inside a [VertexBuffer](https://api.playcanvas.com/engine/classes/VertexBuffer.md). ## Constructors ### constructor ```ts new VertexFormat(graphicsDevice: GraphicsDevice, description: AttributeDescription[], vertexCount?: number) ``` Create a new VertexFormat instance. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to manage this vertex format. - `description` ([`AttributeDescription`](https://api.playcanvas.com/engine/interfaces/AttributeDescription.md)`[]`): 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** ```ts // Specify 3-component positions (x, y, z) const vertexFormat = new VertexFormat(graphicsDevice, [ { semantic: SEMANTIC_POSITION, components: 3, type: TYPE_FLOAT32 } ]); ``` **Example** ```ts // 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 } ]); ``` ## Methods ### hasUv ```ts 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](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD0.md) to 7 for [SEMANTIC_TEXCOORD7](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD7.md). **Returns** `boolean`: True if the format contains the texture coordinate set. ### getDefaultInstancingFormat ```ts static getDefaultInstancingFormat(graphicsDevice: GraphicsDevice): VertexFormat ``` The [VertexFormat](https://api.playcanvas.com/engine/classes/VertexFormat.md) used to store matrices of type [Mat4](https://api.playcanvas.com/engine/classes/Mat4.md) for hardware instancing. The matrix rows use [SEMANTIC_ATTR11](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR11.md), [SEMANTIC_ATTR12](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR12.md), [SEMANTIC_ATTR14](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR14.md) and [SEMANTIC_ATTR15](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR15.md). The first two share their attribute locations with [SEMANTIC_TEXCOORD6](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD6.md) and [SEMANTIC_TEXCOORD7](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD7.md), so a shader reading those texture coordinate sets needs a custom instancing format on other attributes. **Parameters** - `graphicsDevice` ([`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to create this vertex format. **Returns** [`VertexFormat`](https://api.playcanvas.com/engine/classes/VertexFormat.md): The default instancing vertex format. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/VertexIterator.md # VertexIterator Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-iterator.js#L240 A vertex iterator simplifies the process of writing vertex data to a vertex buffer. ## Constructors ### constructor ```ts new VertexIterator(vertexBuffer: VertexBuffer) ``` Create a new VertexIterator instance. **Parameters** - `vertexBuffer` ([`VertexBuffer`](https://api.playcanvas.com/engine/classes/VertexBuffer.md)): The vertex buffer to be iterated. ## Properties ### element ```ts element: {} ``` The vertex buffer elements. ## Methods ### end ```ts 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** ```ts 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 ```ts 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** ```ts 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(); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/WebglGraphicsDevice.md # WebglGraphicsDevice Class · extends [`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/webgl/webgl-graphics-device.js#L144 WebglGraphicsDevice extends the base [GraphicsDevice](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) to provide rendering capabilities utilizing the WebGL 2.0 specification. ## Constructors ### constructor ```ts 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: - 'default': Let the user agent decide which GPU configuration is most suitable. This is the default value. - 'high-performance': Prioritizes rendering performance over power consumption. - 'low-power': Prioritizes power saving over rendering performance. 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. ## Properties ### transformFeedbackBuffers ```ts transformFeedbackBuffers: VertexBuffer[] | null | undefined ``` ## Accessors ### fullscreen ```ts get fullscreen(): boolean set fullscreen(fullscreen: boolean) ``` Gets whether the device is currently in fullscreen mode. ## Methods ### clear ```ts 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: - [CLEARFLAG_COLOR](https://api.playcanvas.com/engine/variables/CLEARFLAG_COLOR.md) - [CLEARFLAG_DEPTH](https://api.playcanvas.com/engine/variables/CLEARFLAG_DEPTH.md) - [CLEARFLAG_STENCIL](https://api.playcanvas.com/engine/variables/CLEARFLAG_STENCIL.md) - `options.stencil` (`number`, optional): The stencil value to clear the stencil buffer to. Defaults to 0. **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/RenderTarget.md), optional): The source render target. Defaults to frame buffer. - `dest` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md), 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 ```ts destroy(): void ``` Destroy the graphics device. ### postInit ```ts postInit(): void ``` Function that executes after the device has been created. ### setBindGroup ```ts setBindGroup(index: number, bindGroup: BindGroup, offsets?: Uint32Array): void ``` **Parameters** - `index` (`number`): Index of the bind group slot - `bindGroup` (`BindGroup`): Bind group to attach - `offsets` (`Uint32Array`, 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 ```ts setBlendState(blendState: any): void ``` Sets the specified blend state. **Parameters** - `blendState` (`any`): New blend state. ### setCullMode ```ts setCullMode(cullMode: any): void ``` Controls how triangles are culled based on their face direction. The default cull mode is [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md). **Parameters** - `cullMode` (`any`): The cull mode to set. Can be: - [CULLFACE_NONE](https://api.playcanvas.com/engine/variables/CULLFACE_NONE.md) - [CULLFACE_BACK](https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md) - [CULLFACE_FRONT](https://api.playcanvas.com/engine/variables/CULLFACE_FRONT.md) ### setDepthState ```ts setDepthState(depthState: any): void ``` Sets the specified depth state. **Parameters** - `depthState` (`any`): New depth state. ### setFrontFace ```ts setFrontFace(frontFace: any): void ``` Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md). **Parameters** - `frontFace` (`any`): The front face to set. Can be: - [FRONTFACE_CW](https://api.playcanvas.com/engine/variables/FRONTFACE_CW.md) - [FRONTFACE_CCW](https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md) ### setScissor ```ts 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 ```ts setShader(shader: Shader, asyncCompile?: boolean): void ``` Sets the active shader to be used during subsequent draw calls. **Parameters** - `shader` ([`Shader`](https://api.playcanvas.com/engine/classes/Shader.md)): 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 ```ts 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](https://api.playcanvas.com/engine/classes/StencilParameters.md#default) if not specified. - `stencilBack` (`any`): The back stencil parameters. Defaults to [StencilParameters.DEFAULT](https://api.playcanvas.com/engine/classes/StencilParameters.md#default) if not specified. ### setViewport ```ts 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. ## Inherited from [GraphicsDevice](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) - `readonly canvas: HTMLCanvasElement` - `gpuProfiler: GpuProfiler` - `insideRenderPass: boolean = false` - `isHdr: boolean = false` - `readonly isNull: boolean = false` - `readonly isWebGPU: boolean = false` - `readonly maxAnisotropy: number` - `readonly maxColorAttachments: number = 1` - `readonly maxCubeMapSize: number` - `maxIndirectDispatchCount: number = 256` - `maxIndirectDrawCount: number = 1024` - `readonly maxSamples: number = 1` - `readonly maxSubgroupSize: number = 0` - `readonly maxTextureSize: number` - `readonly maxVolumeSize: number` - `readonly minSubgroupSize: number = 0` - `readonly precision: string` - `readonly samples: number` - `readonly scope: ScopeSpace` - `supportsClipDistances: boolean = false` - `readonly supportsCompute: boolean = false` - `readonly supportsDualSourceBlending: boolean = false` - `readonly supportsHtmlTextures: boolean = false` - `readonly supportsIndependentBlending: boolean = false` - `readonly supportsIndirectDraw: boolean = false` - `readonly supportsLinearIndexing: boolean = false` - `supportsMultiDraw: boolean = true` - `readonly supportsPacked4x8IntegerDotProduct: boolean = false` - `readonly supportsPointerCompositeAccess: boolean = false` - `readonly supportsPrimitiveIndex: boolean = false` - `readonly supportsShaderF16: boolean = false` - `readonly supportsStorageTextureRead: boolean = false` - `readonly supportsSubgroupId: boolean = false` - `readonly supportsSubgroups: boolean = false` - `readonly supportsSubgroupSizeControl: boolean = false` - `readonly supportsSubgroupUniformity: boolean = false` - `readonly supportsTextureAndSamplerLet: boolean = false` - `readonly supportsTextureFormatsTier1: boolean = false` - `readonly supportsTextureFormatsTier2: boolean = false` - `readonly supportsTransientAttachments: boolean = false` - `readonly supportsUnrestrictedPointerParameters: boolean = false` - `readonly textureFloatBlendable: boolean = false` - `readonly textureFloatFilterable: boolean = false` - `readonly textureFloatRenderable: boolean` - `readonly textureHalfFloatRenderable: boolean` - `readonly textureRG11B10Renderable: boolean = false` - `get deviceType(): "webgl2" | "webgpu"` - `get height(): number` - `get indirectDispatchBuffer(): StorageBuffer | null` - `get indirectDrawBuffer(): StorageBuffer | null` - `get maxPixelRatio(): number` · `set maxPixelRatio(ratio: number)` - `get width(): number` - `computeDispatch(computes: Compute[], name?: string): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `getIndirectDispatchSlot(count?: number): number` - `getIndirectDrawSlot(count?: number): number` - `getRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefined` - `getRenderTarget(): RenderTarget` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `setDrawStates(blendState?: BlendState, depthState?: DepthState, cullMode?: number, frontFace?: number, stencilFront?: StencilParameters, stencilBack?: StencilParameters): void` - `setRenderTarget(renderTarget: RenderTarget | null): void` - `protected validateAttributes(shader: Shader, vertexBuffers: (VertexBuffer | null | undefined)[]): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/WideLine.md # WideLine Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L46 A connected, variable-width line rendered by a [WideLineRenderer](https://api.playcanvas.com/engine/classes/WideLineRenderer.md). 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. ## Accessors ### cap ```ts get cap(): number set cap(value: number) ``` Gets the cap style. ### closed ```ts get closed(): boolean set closed(value: boolean) ``` Gets whether the last point connects back to the first point. ### dashLength ```ts get dashLength(): number set dashLength(value: number) ``` Gets the length of each visible dash in world units. ### dashOffset ```ts get dashOffset(): number set dashOffset(value: number) ``` Gets the offset of the dash pattern in world units. ### gapLength ```ts get gapLength(): number set gapLength(value: number) ``` Gets the length of each gap in world units. ### join ```ts get join(): number set join(value: number) ``` Gets the join style. ### pointCount ```ts get pointCount(): number ``` The number of points in the line. This is zero until [WideLine#set](https://api.playcanvas.com/engine/classes/WideLine.md#set) is called. ### renderer ```ts get renderer(): WideLineRenderer | null ``` The renderer that owns this line, or null when the line is not being rendered. ## Methods ### set ```ts set(positions: ArrayLike, colors?: ArrayLike | Color, widths?: number | ArrayLike): 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`): Packed xyz coordinates. The length must be a multiple of three and contain at least two points. - `colors` (`ArrayLike |` [`Color`](https://api.playcanvas.com/engine/classes/Color.md), 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](https://api.playcanvas.com/engine/classes/Color.md) is ignored. - `widths` (`number | ArrayLike`, optional, default `1`): One width per point, or a single width used by every point. Width units are selected by the owning [WideLineRenderer](https://api.playcanvas.com/engine/classes/WideLineRenderer.md) and values must be non-negative. **Returns** [`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md): This line. ### setColors ```ts setColors(colors: ArrayLike | Color): WideLine ``` Replaces colors without changing the number of points. **Parameters** - `colors` (`ArrayLike |` [`Color`](https://api.playcanvas.com/engine/classes/Color.md)): Packed rgb values containing exactly `pointCount * 3` values, or a single color used by every point. The alpha component of a [Color](https://api.playcanvas.com/engine/classes/Color.md) is ignored. **Returns** [`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md): This line. ### setPositions ```ts setPositions(positions: ArrayLike): WideLine ``` Replaces positions without changing the number of points. **Parameters** - `positions` (`ArrayLike`): Packed xyz coordinates containing exactly `pointCount * 3` values. **Returns** [`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md): This line. ### setWidths ```ts setWidths(widths: number | ArrayLike): WideLine ``` Replaces widths without changing the number of points. **Parameters** - `widths` (`number | ArrayLike`): An array containing exactly `pointCount` values, or a single width used by every point. Width units are selected by the owning [WideLineRenderer](https://api.playcanvas.com/engine/classes/WideLineRenderer.md) and values must be non-negative. **Returns** [`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md): This line. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/WideLineRenderer.md # WideLineRenderer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L550 Renders a collection of [WideLine](https://api.playcanvas.com/engine/classes/WideLine.md) 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](https://api.playcanvas.com/engine/classes/WideLine.md) 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](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#widthunits). A line can belong to only one WideLineRenderer at a time. Use [WideLineRenderer#add](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#add) and [WideLineRenderer#remove](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#remove) to transfer ownership without changing the line data. ## Basic usage The following example creates a three-point line with a color gradient, variable width and rounded ends and joins: ```javascript 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](https://api.playcanvas.com/engine/classes/WideLine.md#setpositions), [WideLine#setColors](https://api.playcanvas.com/engine/classes/WideLine.md#setcolors) and [WideLine#setWidths](https://api.playcanvas.com/engine/classes/WideLine.md#setwidths). These methods preserve the point count and reuse the line's existing storage. Use [WideLine#set](https://api.playcanvas.com/engine/classes/WideLine.md#set) when the point count needs to change. ## Performance 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: ```javascript 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](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#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](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#clear) removes the lines but retains this capacity for reuse. ## Rendering behavior and limitations - Rendering is opaque. Packed colors contain rgb values, the alpha component of a [Color](https://api.playcanvas.com/engine/classes/Color.md) is ignored and transparent lines are not supported. - Widths use screen pixels by default. Set [WideLineRenderer#widthUnits](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#widthunits) to [LINEWIDTH_WORLD](https://api.playcanvas.com/engine/variables/LINEWIDTH_WORLD.md) for camera-facing ribbons measured in world units. - [WideLineRenderer#depthTest](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#depthtest) and [WideLineRenderer#depthWrite](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#depthwrite) control interaction with the depth buffer. Both default to true. - The renderer is added to the Immediate layer by default. Assign [WideLineRenderer#layer](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#layer) to render it in another layer. - The batch is not frustum culled. Disable the renderer using [WideLineRenderer#enabled](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#enabled) when none of its lines need to be rendered. - Call [WideLineRenderer#destroy](https://api.playcanvas.com/engine/classes/WideLineRenderer.md#destroy) to release the internal mesh, material and instance buffer. Detached lines remain usable and can be added to another renderer. See the following examples for interactive styling and update demonstrations: - [https://playcanvas.github.io/#/graphics/wide-line](https://playcanvas.github.io/#/graphics/wide-line) - [https://playcanvas.github.io/#/graphics/wide-lines-styles](https://playcanvas.github.io/#/graphics/wide-lines-styles) - [https://playcanvas.github.io/#/graphics/wide-lines-dynamic](https://playcanvas.github.io/#/graphics/wide-lines-dynamic) ## Constructors ### constructor ```ts new WideLineRenderer(app: AppBase) ``` Creates a new wide line renderer. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. ## Accessors ### capacity ```ts get capacity(): number set capacity(value: number) ``` Gets the allocated instance capacity, measured in generated line segments. ### depthTest ```ts get depthTest(): boolean set depthTest(value: boolean) ``` Gets whether lines are tested against the depth buffer. ### depthWrite ```ts get depthWrite(): boolean set depthWrite(value: boolean) ``` Gets whether lines write to the depth buffer. ### enabled ```ts get enabled(): boolean set enabled(value: boolean) ``` Gets whether this renderer is visible. ### layer ```ts get layer(): Layer set layer(value: Layer) ``` Gets the layer containing the renderer's mesh instance. ### widthUnits ```ts get widthUnits(): number set widthUnits(value: number) ``` Gets the units used to interpret line widths. ## Methods ### add ```ts add(line: WideLine): void ``` Adds a line to this renderer. A line can belong to only one renderer at a time. **Parameters** - `line` ([`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md)): The line to add. ### clear ```ts clear(): void ``` Removes all lines. Allocated instance capacity is retained for reuse. ### destroy ```ts destroy(): void ``` Releases all renderer-owned resources. Lines previously owned by this renderer remain usable and can be added to another renderer. ### remove ```ts remove(line: WideLine): boolean ``` Removes a line from this renderer without modifying its point data or style. **Parameters** - `line` ([`WideLine`](https://api.playcanvas.com/engine/classes/WideLine.md)): The line to remove. **Returns** `boolean`: True if the line was owned by this renderer and was removed. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/WireRenderer.md # WireRenderer Class · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wire-renderer.js#L109 Renders wireframe shapes for a single frame, for debugging and visualization. Shapes are submitted as line segments to the layer given by [WireRenderer#layer](https://api.playcanvas.com/engine/classes/WireRenderer.md#layer), which defaults to the [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md) 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](https://api.playcanvas.com/engine/classes/WireRenderer.md#color), [WireRenderer#layer](https://api.playcanvas.com/engine/classes/WireRenderer.md#layer), [WireRenderer#depthTest](https://api.playcanvas.com/engine/classes/WireRenderer.md#depthtest), [WireRenderer#segments](https://api.playcanvas.com/engine/classes/WireRenderer.md#segments) and [WireRenderer#transform](https://api.playcanvas.com/engine/classes/WireRenderer.md#transform). Fields can be assigned between calls, and drawing many shapes with the same state allocates nothing: ```javascript 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: ```javascript 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](https://api.playcanvas.com/engine/classes/WideLineRenderer.md) instead. ## Constructors ### constructor ```ts new WireRenderer(app: AppBase) ``` Creates a new WireRenderer instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The application. **Example** ```ts const wire = new WireRenderer(app); ``` ## Properties ### color ```ts color: Color ``` The color used by shapes, specified in sRGB color space. The alpha component is respected. Defaults to white. ### depthTest ```ts depthTest: boolean = true ``` Whether shapes are depth tested against the depth buffer. Defaults to true. ### layer ```ts layer: Layer | null = null ``` The layer shapes are rendered into, or null to use the [LAYERID_IMMEDIATE](https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md) layer. Defaults to null. ### segments ```ts segments: number = 20 ``` The number of line segments used to approximate a full circle. Defaults to 20. ### transform ```ts 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. ## Methods ### arrow ```ts arrow(from: Vec3, to: Vec3): void ``` Renders an arrow, as a shaft with four barbs at its tip. **Parameters** - `from` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The tail of the arrow. - `to` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The tip of the arrow. **Example** ```ts wire.arrow(position, position.clone().add(velocity)); ``` ### axes ```ts 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](https://api.playcanvas.com/engine/classes/WireRenderer.md#color). **Parameters** - `matrix` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The transform whose axes are rendered. - `size` (`number`): The length of each axis. **Example** ```ts wire.axes(entity.getWorldTransform(), 1); ``` ### box ```ts box(box: BoundingBox | OrientedBox): void ``` Renders the edges of a bounding box. An [OrientedBox](https://api.playcanvas.com/engine/classes/OrientedBox.md) is rendered in its own orientation, composed with [WireRenderer#transform](https://api.playcanvas.com/engine/classes/WireRenderer.md#transform). **Parameters** - `box` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md) `|` [`OrientedBox`](https://api.playcanvas.com/engine/classes/OrientedBox.md)): The box to render. **Example** ```ts wire.box(meshInstance.aabb); ``` ### boxMinMax ```ts boxMinMax(min: Vec3, max: Vec3): void ``` Renders the edges of a box specified by its min and max corners. **Parameters** - `min` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The min corner of the box. - `max` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The max corner of the box. **Example** ```ts wire.boxMinMax(new Vec3(-1, -1, -1), new Vec3(1, 1, 1)); ``` ### capsule ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the start cap sphere. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the end cap sphere. - `radius` (`number`): The radius of the capsule. **Example** ```ts wire.capsule(feet, head, 0.4); ``` ### circle ```ts circle(center: Vec3, normal: Vec3, radius: number): void ``` Renders a circle lying in the plane described by a normal. **Parameters** - `center` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the circle. - `normal` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The normal of the plane containing the circle. Need not be normalized. - `radius` (`number`): The radius of the circle. **Example** ```ts wire.circle(Vec3.ZERO, Vec3.UP, 5); ``` ### cone ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The tip of the cone. - `direction` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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** ```ts wire.cone(position, direction, 30, 10); ``` ### cylinder ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the start cap. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the end cap. - `radius` (`number`): The radius of the cylinder. **Example** ```ts wire.cylinder(base, tip, 0.5); ``` ### frustum ```ts 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`](https://api.playcanvas.com/engine/classes/CameraComponent.md) `|` [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): A camera, or a view-projection matrix. **Example** ```ts wire.frustum(otherCamera.camera); ``` ### light ```ts 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`](https://api.playcanvas.com/engine/classes/LightComponent.md)): 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** ```ts wire.light(entity.light); ``` ### line ```ts line(start: Vec3, end: Vec3): void ``` Renders a single line segment. **Parameters** - `start` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The start of the line, in world space. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The end of the line, in world space. **Example** ```ts wire.line(new Vec3(0, 0, 0), new Vec3(0, 1, 0)); ``` ### lines ```ts lines(positions: Vec3[], colors?: Color[]): void ``` Renders discrete line segments, formed by consecutive pairs of points. **Parameters** - `positions` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`[]`): The points to draw lines between. The length must be a multiple of two. - `colors` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)`[]`, optional): One color per point, or undefined to use [WireRenderer#color](https://api.playcanvas.com/engine/classes/WireRenderer.md#color). The color of each segment is interpolated between its ends. **Example** ```ts wire.lines([start, end], [Color.RED, Color.WHITE]); ``` ### linesPacked ```ts linesPacked(positions: number[] | Float32Array, colors?: number[] | Float32Array): void ``` Renders discrete line segments from packed arrays of numbers. This is the fastest of the line functions, as it avoids reading individual [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) and [Color](https://api.playcanvas.com/engine/classes/Color.md) instances. **Parameters** - `positions` (`number[] | Float32Array`): Packed xyz coordinates, forming pairs of points. - `colors` (`number[] | Float32Array`, optional): Packed rgba values, one color per point, or undefined to use [WireRenderer#color](https://api.playcanvas.com/engine/classes/WireRenderer.md#color). **Example** ```ts wire.linesPacked([0, 0, 0, 0, 1, 0]); ``` ### loop ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)`[]`): The points of the loop, in order. - `colors` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)`[]`, optional): One color per point, or undefined to use [WireRenderer#color](https://api.playcanvas.com/engine/classes/WireRenderer.md#color). **Example** ```ts wire.loop(outline); ``` ### plane ```ts 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](https://api.playcanvas.com/engine/classes/WireRenderer.md#transform) instead. **Parameters** - `center` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the square. - `normal` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The normal of the plane. Need not be normalized. - `size` (`number`): The side length of the square. **Example** ```ts wire.plane(Vec3.ZERO, Vec3.UP, 10); ``` ### point ```ts point(position: Vec3, size: number): void ``` Renders a small axis-aligned cross marking a position. **Parameters** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The position to mark. - `size` (`number`): The overall length of each arm of the cross. **Example** ```ts wire.point(hit.point, 0.2); ``` ### polyline ```ts polyline(positions: Vec3[], colors?: Color[]): void ``` Renders an open strip of connected line segments. **Parameters** - `positions` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)`[]`): The points of the strip, in order. - `colors` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)`[]`, optional): One color per point, or undefined to use [WireRenderer#color](https://api.playcanvas.com/engine/classes/WireRenderer.md#color). **Example** ```ts wire.polyline(trajectory); ``` ### sphere ```ts sphere(center: Vec3, radius: number): void ``` Renders a sphere as three great circles, one in each of the primary planes. **Parameters** - `center` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The center of the sphere. - `radius` (`number`): The radius of the sphere. **Example** ```ts wire.sphere(new Vec3(0, 1, 0), 0.5); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/calculateNormals.md # calculateNormals Function · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry-utils.js#L14 ```ts calculateNormals(positions: ArrayLike, indices: ArrayLike): number[] ``` Generates normal information from the specified positions and triangle indices. **Parameters** - `positions` (`ArrayLike`): An array of 3-dimensional vertex positions. - `indices` (`ArrayLike`): An array of triangle indices. **Returns** `number[]`: An array of 3-dimensional vertex normals. **Example** ```ts const normals = calculateNormals(positions, indices); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/calculateTangents.md # calculateTangents Function · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry-utils.js#L87 ```ts calculateTangents(positions: ArrayLike, normals: ArrayLike, uvs: ArrayLike, indices: ArrayLike): number[] ``` Generates tangent information from the specified positions, normals, texture coordinates and triangle indices. **Parameters** - `positions` (`ArrayLike`): An array of 3-dimensional vertex positions. - `normals` (`ArrayLike`): An array of 3-dimensional vertex normals. - `uvs` (`ArrayLike`): An array of 2-dimensional vertex texture coordinates. - `indices` (`ArrayLike`): An array of triangle indices. **Returns** `number[]`: An array of 3-dimensional vertex tangents. **Example** ```ts const tangents = calculateTangents(positions, normals, uvs, indices); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/createGraphicsDevice.md # createGraphicsDevice Function · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/graphics-device-create.js#L92 ```ts createGraphicsDevice(canvas: HTMLCanvasElement, options?: object): Promise ``` 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: - [DEVICETYPE_WEBGL2](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md): forwarded as the WebGL `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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB8.md) rather than [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md), which also changes the format of the scene color grab pass. - [DEVICETYPE_WEBGPU](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md): selects the canvas alpha mode ('premultiplied' when true, 'opaque' when false). The backbuffer always has an alpha channel, so `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](https://api.playcanvas.com/engine/classes/CameraComponent.md#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](https://api.playcanvas.com/engine/classes/Application.md) 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](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md), it is internally added to its end. A [DEVICETYPE_NULL](https://api.playcanvas.com/engine/variables/DEVICETYPE_NULL.md) device, which renders nothing, is only created if it is specified. Typically, you'd only specify [DEVICETYPE_WEBGPU](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md), or leave it empty. Use [DEVICETYPE_WEBGPU_BARE](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU_BARE.md) or [DEVICETYPE_WEBGL2_BARE](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2_BARE.md) 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](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR.md). Can be: - [DISPLAYFORMAT_LDR](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR.md) - [DISPLAYFORMAT_LDR_SRGB](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR_SRGB.md) - [DISPLAYFORMAT_HDR](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_HDR.md) - `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](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md) 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](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md) device type creation. - `options.powerPreference` (`"default" | "high-performance" | "low-power"`, optional): A hint indicating what configuration of GPU would be selected. Possible values are: - 'default': Let the user agent decide which GPU configuration is most suitable. This is the default value. - 'high-performance': Prioritizes rendering performance over power consumption. - 'low-power': Prioritizes power saving over rendering performance. 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md) constructor). **Returns** `Promise<`[`GraphicsDevice`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)`>`: - 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/drawQuadWithShader.md # drawQuadWithShader Function · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/quad-render-utils.js#L30 ```ts 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`](https://api.playcanvas.com/engine/classes/GraphicsDevice.md)): The graphics device used to draw the quad. - `target` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md) `| null`): The destination render target. If undefined, target is the frame buffer. - `shader` ([`Shader`](https://api.playcanvas.com/engine/classes/Shader.md)): The shader used for rendering the quad. Vertex shader should contain `attribute vec2 vertex_position`. - `rect` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The viewport rectangle of the quad, in pixels. Defaults to fullscreen: `[0, 0, target.width, target.height]`. - `scissorRect` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), 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'. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/reprojectTexture.md # reprojectTexture Function · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/reproject-texture.js#L391 ```ts 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`](https://api.playcanvas.com/engine/classes/Texture.md)): The source texture. - `target` ([`Texture`](https://api.playcanvas.com/engine/classes/Texture.md)): 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`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): Optional viewport rectangle. - `options.seamPixels` (`number`, optional): Optional number of seam pixels to render - `options.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) -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ASTC_4x4.md # PIXELFORMAT_ASTC_4x4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L779 ATC compressed format with alpha channel in blocks of 4x4. ```ts const PIXELFORMAT_ASTC_4x4: 28 = 28 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ASTC_4x4_SRGB.md # PIXELFORMAT_ASTC_4x4_SRGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L998 Format equivalent to [PIXELFORMAT_ASTC_4x4](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ASTC_4x4.md) but sampled in linear color space. ```ts const PIXELFORMAT_ASTC_4x4_SRGB: 63 = 63 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/DualGestureSource.md # DualGestureSource Class · extends [`InputSource`](https://api.playcanvas.com/engine/classes/InputSource.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/dual-gesture-source.js#L36 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](https://api.playcanvas.com/engine/classes/DualGestureSource.md#layout) chooses a joystick or a plain touch area for each side, for example `joystick-touch`, and the joysticks are exposed as [leftJoystick](https://api.playcanvas.com/engine/classes/DualGestureSource.md#leftjoystick) and [rightJoystick](https://api.playcanvas.com/engine/classes/DualGestureSource.md#rightjoystick). ## Constructors ### constructor ```ts 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. ## Accessors ### layout ```ts get layout(): "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch" set layout(value: "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch") ``` ### leftJoystick ```ts get leftJoystick(): VirtualJoystick ``` ### rightJoystick ```ts get rightJoystick(): VirtualJoystick ``` ## Methods ### attach ```ts attach(element: HTMLElement): void ``` **Parameters** - `element` (`HTMLElement`): The element. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### read ```ts read(): { doubleTap: number[]; leftInput: number[]; rightInput: number[] } ``` **Returns** `{ doubleTap: number[]; leftInput: number[]; rightInput: number[] }` ## Inherited from [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md) - `protected _element: HTMLElement | null = null` - `deltas: { doubleTap: InputDelta; leftInput: InputDelta; rightInput: InputDelta }` - `fire(event: string, ...args: any[]): void` - `off(event: string, callback: HandleEventCallback): void` - `on(event: string, callback: HandleEventCallback): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/FlyController.md # FlyController Class · extends [`InputController`](https://api.playcanvas.com/engine/classes/InputController.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/fly-controller.js#L27 The fly controller. Free flight: `rotate` deltas turn the pose about yaw and pitch, limited by [yawRange](https://api.playcanvas.com/engine/classes/FlyController.md#yawrange) and [pitchRange](https://api.playcanvas.com/engine/classes/FlyController.md#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](https://api.playcanvas.com/engine/classes/FlyController.md#rotatedamping) and [moveDamping](https://api.playcanvas.com/engine/classes/FlyController.md#movedamping). ## Properties ### moveDamping ```ts 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 ```ts 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. ## Accessors ### pitchRange ```ts get pitchRange(): Vec2 set pitchRange(value: Vec2) ``` ### yawRange ```ts get yawRange(): Vec2 set yawRange(value: Vec2) ``` ## Methods ### attach ```ts attach(pose: Pose, smooth?: boolean): void ``` **Parameters** - `pose` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): The initial pose of the controller. - `smooth` (`boolean`, optional, default `true`): Whether to smooth the transition. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### update ```ts update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose ``` **Parameters** - `frame` ([`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md)`<{ move: number[]; rotate: number[] }>`): The input frame. - `dt` (`number`): The delta time. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): - The controller pose. ## Inherited from [InputController](https://api.playcanvas.com/engine/classes/InputController.md) - `new FlyController()` - `protected _pose: Pose` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/FocusController.md # FocusController Class · extends [`InputController`](https://api.playcanvas.com/engine/classes/InputController.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/focus-controller.js#L25 The focus controller. It ignores the input frame and instead eases the pose from where it was towards the pose given to [attach](https://api.playcanvas.com/engine/classes/FocusController.md#attach), smoothed by [focusDamping](https://api.playcanvas.com/engine/classes/FocusController.md#focusdamping). Use it to animate a camera onto a new target and then hand over to another controller; [complete](https://api.playcanvas.com/engine/classes/FocusController.md#complete) reports when the target has been reached. ## Properties ### focusDamping ```ts 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. ## Methods ### attach ```ts attach(pose: Pose, smooth?: boolean): void ``` **Parameters** - `pose` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): The initial pose of the controller. - `smooth` (`boolean`, optional, default `true`): Whether to smooth the transition. ### complete ```ts complete(): boolean ``` **Returns** `boolean` ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### update ```ts update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose ``` **Parameters** - `frame` ([`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md)`<{ move: number[]; rotate: number[] }>`): The input frame. - `dt` (`number`): The delta time. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): - The controller pose. ## Inherited from [InputController](https://api.playcanvas.com/engine/classes/InputController.md) - `new FocusController()` - `protected _pose: Pose` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GamepadSource.md # GamepadSource Class · extends [`InputSource`](https://api.playcanvas.com/engine/classes/InputSource.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/gamepad-source.js#L33 Game pad input source class. Each [read](https://api.playcanvas.com/engine/classes/GamepadSource.md#read) polls the connected gamepads and yields `buttons` deltas for the buttons listed in [buttonCode](https://api.playcanvas.com/engine/classes/GamepadSource.md#buttoncode), and `leftStick` and `rightStick` deltas as `[x, y]`. ## Constructors ### constructor ```ts new GamepadSource() ``` ## Properties ### buttonCode ```ts 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`) ## Methods ### read ```ts read(): { buttons: number[]; leftStick: number[]; rightStick: number[] } ``` **Returns** `{ buttons: number[]; leftStick: number[]; rightStick: number[] }` ## Inherited from [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md) - `protected _element: HTMLElement | null = null` - `deltas: { buttons: InputDelta; leftStick: InputDelta; rightStick: InputDelta }` - `attach(element: HTMLElement): void` - `destroy(): void` - `detach(): void` - `fire(event: string, ...args: any[]): void` - `off(event: string, callback: HandleEventCallback): void` - `on(event: string, callback: HandleEventCallback): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/InputConsumer.md # InputConsumer Class · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L230 The base class for all input consumers, which are used to process input frames. A consumer implements [update](https://api.playcanvas.com/engine/classes/InputConsumer.md#update), receiving an [InputFrame](https://api.playcanvas.com/engine/classes/InputFrame.md) and the frame time, and does whatever that input means for it. [InputController](https://api.playcanvas.com/engine/classes/InputController.md) is the consumer that turns input into a [Pose](https://api.playcanvas.com/engine/classes/Pose.md). ## Constructors ### constructor ```ts new InputConsumer() ``` ## Methods ### update ```ts update(frame: InputFrame, dt: number): void ``` **Parameters** - `frame` ([`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md)``): The input frame. - `dt` (`number`): The delta time. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/InputController.md # InputController Class · extends [`InputConsumer`](https://api.playcanvas.com/engine/classes/InputConsumer.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L258 The base class for all input controllers. A controller consumes an [InputFrame](https://api.playcanvas.com/engine/classes/InputFrame.md) carrying `move` and `rotate` deltas and produces a [Pose](https://api.playcanvas.com/engine/classes/Pose.md): [attach](https://api.playcanvas.com/engine/classes/InputController.md#attach) sets the pose it starts from, [update](https://api.playcanvas.com/engine/classes/InputController.md#update) applies a frame and returns the current pose, and [detach](https://api.playcanvas.com/engine/classes/InputController.md#detach) releases it. The application applies the returned pose to an entity. [FlyController](https://api.playcanvas.com/engine/classes/FlyController.md), [OrbitController](https://api.playcanvas.com/engine/classes/OrbitController.md) and [FocusController](https://api.playcanvas.com/engine/classes/FocusController.md) implement three ways of doing this. **Example** ```ts 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); ``` ## Properties ### _pose ```ts protected _pose: Pose ``` ## Methods ### attach ```ts attach(pose: Pose, smooth?: boolean): void ``` **Parameters** - `pose` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): The initial pose of the controller. - `smooth` (`boolean`, optional, default `true`): Whether to smooth the transition. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### update ```ts update(frame: InputFrame, dt: number): Pose ``` **Parameters** - `frame` ([`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md)``): The input frame. - `dt` (`number`): The delta time. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): - The controller pose. ## Inherited from [InputConsumer](https://api.playcanvas.com/engine/classes/InputConsumer.md) - `new InputController()` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/InputDelta.md # InputDelta Class · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L15 Represents an input delta: a fixed-length array of numbers that accumulates input between reads. Sources [append](https://api.playcanvas.com/engine/classes/InputDelta.md#append) raw values to it as events arrive, and [read](https://api.playcanvas.com/engine/classes/InputDelta.md#read) returns the total and resets it to zero, so each read yields the change since the previous one. An [InputFrame](https://api.playcanvas.com/engine/classes/InputFrame.md) groups named deltas together. ## Constructors ### constructor ```ts new InputDelta(arg: number | number[]) ``` **Parameters** - `arg` (`number | number[]`): The size of the delta or an array of initial values. ## Methods ### add ```ts add(other: InputDelta): InputDelta ``` Adds another InputDelta instance to this one. **Parameters** - `other` ([`InputDelta`](https://api.playcanvas.com/engine/classes/InputDelta.md)): The other InputDelta instance to add. **Returns** [`InputDelta`](https://api.playcanvas.com/engine/classes/InputDelta.md): Self for chaining. ### append ```ts append(offsets: number[]): InputDelta ``` Appends offsets to the current delta values. **Parameters** - `offsets` (`number[]`): The offsets. **Returns** [`InputDelta`](https://api.playcanvas.com/engine/classes/InputDelta.md): Self for chaining. ### copy ```ts copy(other: InputDelta): InputDelta ``` Copies the values from another InputDelta instance to this one. **Parameters** - `other` ([`InputDelta`](https://api.playcanvas.com/engine/classes/InputDelta.md)): The other InputDelta instance to copy from. **Returns** [`InputDelta`](https://api.playcanvas.com/engine/classes/InputDelta.md): Self for chaining. ### length ```ts 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 ```ts read(): number[] ``` Returns the current value of the delta and resets it to zero. **Returns** `number[]`: - The current value of the delta. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/InputFrame.md # InputFrame Class · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L110 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](https://api.playcanvas.com/engine/classes/InputFrame.md#read) flushes every delta at once. A frame is the unit of exchange in this input system: [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md)s are frames that fill themselves from a device, and an application combines their values into a frame with the shape an [InputController](https://api.playcanvas.com/engine/classes/InputController.md) expects. **template** The shape of the input frame. ## Constructors ### constructor ```ts new InputFrame>(data: T) ``` **Parameters** - `data` ([`T`](https://api.playcanvas.com/engine/classes/InputFrame.md#t)): The input frame data, where each key corresponds to an input delta. ## Properties ### deltas ```ts deltas: { [K in string | number | symbol]: InputDelta } ``` ## Methods ### read ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/InputSource.md # InputSource Class · extends [`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L153 The base class for all input devices. An input source is an [InputFrame](https://api.playcanvas.com/engine/classes/InputFrame.md) that fills its own deltas from DOM events or device polling once [attach](https://api.playcanvas.com/engine/classes/InputSource.md#attach) is given an element, and stops on [detach](https://api.playcanvas.com/engine/classes/InputSource.md#detach). Call [InputFrame#read](https://api.playcanvas.com/engine/classes/InputFrame.md#read) once per frame to take the accumulated deltas. The built-in sources are [KeyboardMouseSource](https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md), [GamepadSource](https://api.playcanvas.com/engine/classes/GamepadSource.md), [MultiTouchSource](https://api.playcanvas.com/engine/classes/MultiTouchSource.md), [SingleGestureSource](https://api.playcanvas.com/engine/classes/SingleGestureSource.md) and [DualGestureSource](https://api.playcanvas.com/engine/classes/DualGestureSource.md); subclass this to add another device. **template** The shape of the input source. ## Properties ### _element ```ts protected _element: HTMLElement | null = null ``` ## Methods ### attach ```ts attach(element: HTMLElement): void ``` **Parameters** - `element` (`HTMLElement`): The element. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### fire ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/types/HandleEventCallback.md)): The callback function to remove. ### on ```ts 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`](https://api.playcanvas.com/engine/types/HandleEventCallback.md)): The callback function to execute when the event is triggered. ## Inherited from [InputFrame](https://api.playcanvas.com/engine/classes/InputFrame.md) - `new InputSource>(data: T)` - `deltas: { [K in string | number | symbol]: InputDelta }` - `read(): { [K in string | number | symbol]: number[] }` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md # KeyboardMouseSource Class · extends [`InputSource`](https://api.playcanvas.com/engine/classes/InputSource.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/keyboard-mouse-source.js#L70 Keyboard and mouse input source class. Attached to an element, it accumulates `key` deltas for the keys listed in [keyCode](https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md#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. ## Constructors ### constructor ```ts new KeyboardMouseSource(options?: object) ``` **Parameters** - `options` (`object`, optional, default `{}`): The options. - `options.pointerLock` (`boolean`, optional, default `false`): Whether to enable pointer lock. ## Properties ### _button ```ts _button: number[] ``` ### keyCode ```ts 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`) ## Methods ### attach ```ts attach(element: HTMLElement): void ``` **Parameters** - `element` (`HTMLElement`): The element. ### detach ```ts detach(): void ``` ### read ```ts read(): { button: number[]; key: number[]; mouse: number[]; wheel: number[] } ``` **Returns** `{ button: number[]; key: number[]; mouse: number[]; wheel: number[] }` ## Inherited from [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md) - `protected _element: HTMLElement | null = null` - `deltas: { button: InputDelta; key: InputDelta; mouse: InputDelta; wheel: InputDelta }` - `destroy(): void` - `fire(event: string, ...args: any[]): void` - `off(event: string, callback: HandleEventCallback): void` - `on(event: string, callback: HandleEventCallback): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MultiTouchSource.md # MultiTouchSource Class · extends [`InputSource`](https://api.playcanvas.com/engine/classes/InputSource.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/multi-touch-source.js#L22 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. ## Constructors ### constructor ```ts new MultiTouchSource() ``` ## Methods ### attach ```ts attach(element: HTMLElement): void ``` **Parameters** - `element` (`HTMLElement`): The element. ### detach ```ts detach(): void ``` ## Inherited from [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md) - `protected _element: HTMLElement | null = null` - `deltas: { count: InputDelta; pinch: InputDelta; touch: InputDelta }` - `destroy(): void` - `fire(event: string, ...args: any[]): void` - `off(event: string, callback: HandleEventCallback): void` - `on(event: string, callback: HandleEventCallback): void` - `read(): { count: number[]; pinch: number[]; touch: number[] }` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/OrbitController.md # OrbitController Class · extends [`InputController`](https://api.playcanvas.com/engine/classes/InputController.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/orbit-controller.js#L24 The orbit controller. The pose orbits a focus point at a distance: `rotate` deltas turn the view around the focus within [yawRange](https://api.playcanvas.com/engine/classes/OrbitController.md#yawrange) and [pitchRange](https://api.playcanvas.com/engine/classes/OrbitController.md#pitchrange), the first two `move` components pan the focus point, and the third scales the distance within [zoomRange](https://api.playcanvas.com/engine/classes/OrbitController.md#zoomrange). Motion is smoothed with [rotateDamping](https://api.playcanvas.com/engine/classes/OrbitController.md#rotatedamping), [moveDamping](https://api.playcanvas.com/engine/classes/OrbitController.md#movedamping) and [zoomDamping](https://api.playcanvas.com/engine/classes/OrbitController.md#zoomdamping). ## Properties ### moveDamping ```ts 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 ```ts 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 ```ts zoomDamping: number = 0.98 ``` The zoom damping. A higher value means more damping. A value of 0 means no damping. ## Accessors ### pitchRange ```ts get pitchRange(): Vec2 set pitchRange(range: Vec2) ``` ### yawRange ```ts get yawRange(): Vec2 set yawRange(range: Vec2) ``` ### zoomRange ```ts get zoomRange(): Vec2 set zoomRange(range: Vec2) ``` ## Methods ### attach ```ts attach(pose: Pose, smooth?: boolean): void ``` **Parameters** - `pose` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): The initial pose of the controller. - `smooth` (`boolean`, optional, default `true`): Whether to smooth the transition. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### update ```ts update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose ``` **Parameters** - `frame` ([`InputFrame`](https://api.playcanvas.com/engine/classes/InputFrame.md)`<{ move: number[]; rotate: number[] }>`): The input frame. - `dt` (`number`): The delta time. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): - The controller pose. ## Inherited from [InputController](https://api.playcanvas.com/engine/classes/InputController.md) - `new OrbitController()` - `protected _pose: Pose` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Pose.md # Pose Class · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/pose.js#L18 Represents a pose in 3D space, including position and rotation. It is what an [InputController](https://api.playcanvas.com/engine/classes/InputController.md) produces: a [position](https://api.playcanvas.com/engine/classes/Pose.md#position), Euler [angles](https://api.playcanvas.com/engine/classes/Pose.md#angles) in degrees and, for controllers that orbit, the [distance](https://api.playcanvas.com/engine/classes/Pose.md#distance) to the focus point. Optional ranges such as [pitchRange](https://api.playcanvas.com/engine/classes/Pose.md#pitchrange) and [yRange](https://api.playcanvas.com/engine/classes/Pose.md#yrange) clamp the result of [rotate](https://api.playcanvas.com/engine/classes/Pose.md#rotate) and [move](https://api.playcanvas.com/engine/classes/Pose.md#move). ## Constructors ### constructor ```ts new Pose(position?: Vec3, angles?: Vec3, distance?: number) ``` Creates a new Pose instance. **Parameters** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional, default `Vec3.ZERO`): The position of the pose. - `angles` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), 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. ## Properties ### angles ```ts angles: Vec3 ``` The angles of the pose in degrees calculated from the forward vector. ### distance ```ts distance: number = 0 ``` The focus distance from the position to the pose. ### pitchRange ```ts pitchRange: Vec2 ``` The allowed range of pitch angles in degrees, stored as (min, max). Applied when the pose is rotated via [rotate](https://api.playcanvas.com/engine/classes/Pose.md#rotate). ### position ```ts position: Vec3 ``` The position of the pose. ### xRange ```ts xRange: Vec2 ``` The allowed range of positions along the x axis, stored as (min, max). Applied when the pose is translated via [move](https://api.playcanvas.com/engine/classes/Pose.md#move). ### yawRange ```ts yawRange: Vec2 ``` The allowed range of yaw angles in degrees, stored as (min, max). Applied when the pose is rotated via [rotate](https://api.playcanvas.com/engine/classes/Pose.md#rotate). ### yRange ```ts yRange: Vec2 ``` The allowed range of positions along the y axis, stored as (min, max). Applied when the pose is translated via [move](https://api.playcanvas.com/engine/classes/Pose.md#move). ### zRange ```ts zRange: Vec2 ``` The allowed range of positions along the z axis, stored as (min, max). Applied when the pose is translated via [move](https://api.playcanvas.com/engine/classes/Pose.md#move). ## Methods ### clone ```ts clone(): Pose ``` Creates a clone of this pose. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): A new Pose instance with the same position, angles, and distance. ### copy ```ts copy(other: Pose): Pose ``` Copies the position and rotation from another pose. **Parameters** - `other` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): The pose to copy from. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. ### equalsApprox ```ts equalsApprox(other: Pose, epsilon?: number): boolean ``` Checks if this pose is approximately equal to another pose within a given epsilon. **Parameters** - `other` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The output vector to store the focus point. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The focus point of the pose. ### lerp ```ts 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`](https://api.playcanvas.com/engine/classes/Pose.md)): The left-hand side pose. - `rhs` ([`Pose`](https://api.playcanvas.com/engine/classes/Pose.md)): 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`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. ### look ```ts look(from: Vec3, to: Vec3): Pose ``` Sets the pose to look in the direction of the given vector. **Parameters** - `from` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point from which to look. - `to` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point to look at. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. ### move ```ts move(offset: Vec3): Pose ``` Moves the pose by the given vector. **Parameters** - `offset` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to move by. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. ### rotate ```ts rotate(euler: Vec3): Pose ``` Rotates the pose by the given angles in degrees. **Parameters** - `euler` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The angles to rotate by. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. ### set ```ts set(position: Vec3, angles: Vec3, distance: number): Pose ``` Sets the position and rotation of the pose. **Parameters** - `position` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The new position. - `angles` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The new angles in degrees. - `distance` (`number`): The new focus distance. **Returns** [`Pose`](https://api.playcanvas.com/engine/classes/Pose.md): The updated Pose instance. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SingleGestureSource.md # SingleGestureSource Class · extends [`InputSource`](https://api.playcanvas.com/engine/classes/InputSource.md) · category: Input Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/single-gesture-source.js#L19 Single gesture input source. One virtual control for a touch screen, either an on-screen [joystick](https://api.playcanvas.com/engine/classes/SingleGestureSource.md#joystick) or a drag anywhere on the element depending on [layout](https://api.playcanvas.com/engine/classes/SingleGestureSource.md#layout), producing an `input` delta as `[x, y]` and a `doubleTap` delta. ## Constructors ### constructor ```ts new SingleGestureSource() ``` ## Accessors ### joystick ```ts get joystick(): VirtualJoystick ``` ### layout ```ts get layout(): "joystick" | "touch" set layout(value: "joystick" | "touch") ``` ## Methods ### attach ```ts attach(element: HTMLElement): void ``` **Parameters** - `element` (`HTMLElement`): The element. ### destroy ```ts destroy(): void ``` ### detach ```ts detach(): void ``` ### read ```ts read(): { doubleTap: number[]; input: number[] } ``` **Returns** `{ doubleTap: number[]; input: number[] }` ## Inherited from [InputSource](https://api.playcanvas.com/engine/classes/InputSource.md) - `protected _element: HTMLElement | null = null` - `deltas: { doubleTap: InputDelta; input: InputDelta }` - `fire(event: string, ...args: any[]): void` - `off(event: string, callback: HandleEventCallback): void` - `on(event: string, callback: HandleEventCallback): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GamePad.md # GamePad Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L358 A GamePad stores information about a gamepad from the Gamepad API. ## Properties ### hand ```ts hand: string ``` The hand this gamepad is usually handled on. Only relevant for XR pads. Value is either "left", "right" or "none". ### id ```ts id: string ``` The identifier for the gamepad. Its structure depends on device. ### index ```ts index: number ``` The index for this controller. A gamepad that is disconnected and reconnected will retain the same index. ### map ```ts map: any ``` The buttons and axes map. ### mapping ```ts 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. ## Accessors ### axes ```ts get axes(): number[] ``` Gets the values from analog axes present on the GamePad. Values are between -1 and 1. ### buttons ```ts get buttons(): GamePadButton[] ``` Gets the buttons present on the GamePad. ### connected ```ts get connected(): boolean ``` Gets whether the gamepad is connected. ## Methods ### getAxis ```ts 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](https://api.playcanvas.com/engine/variables/PAD_L_STICK_X.md), etc. **Returns** `number`: The value of the axis between -1 and 1. ### getButton ```ts getButton(index: number): GamePadButton ``` Retrieve a button from its index. **Parameters** - `index` (`number`): The index to return the button for. **Returns** [`GamePadButton`](https://api.playcanvas.com/engine/classes/GamePadButton.md): The button for the searched index. May be a placeholder if none found. ### getValue ```ts 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](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `number`: The value of the button between 0 and 1. ### isPressed ```ts isPressed(button: number): boolean ``` Returns true if the button is pressed. **Parameters** - `button` (`number`): The button to test, use constants [PAD_FACE_1](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: True if the button is pressed. ### isTouched ```ts isTouched(button: number): boolean ``` Returns true if the button is touched. **Parameters** - `button` (`number`): The button to test, use constants [PAD_FACE_1](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: True if the button is touched. ### pulse ```ts pulse(intensity: number, duration: number, options?: object): Promise ``` 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`: Return a Promise resulting in true if the pulse was successfully completed. ### resetMap ```ts resetMap(): void ``` Reset gamepad mapping to default. ### updateMap ```ts 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** ```ts 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 ```ts 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](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: Return true if the button was pressed, false if not. ### wasReleased ```ts 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](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: Return true if the button was released, false if not. ### wasTouched ```ts 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](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: Return true if the button was touched, false if not. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GamePadButton.md # GamePadButton Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L268 A GamePadButton stores information about a button from the Gamepad API. ## Properties ### pressed ```ts pressed: boolean = false ``` Whether the button is currently down. ### touched ```ts touched: boolean = false ``` Whether the button is currently touched. ### value ```ts 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 ```ts wasPressed: boolean = false ``` Whether the button was pressed. ### wasReleased ```ts wasReleased: boolean = false ``` Whether the button was released since the last update. ### wasTouched ```ts wasTouched: boolean = false ``` Whether the button was touched since the last update. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/GamePads.md # GamePads Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L784 Input handler for accessing GamePad input. For frame-accumulated input deltas rather than raw pad state, see [GamepadSource](https://api.playcanvas.com/engine/classes/GamepadSource.md), [KeyboardMouseSource](https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md) and [MultiTouchSource](https://api.playcanvas.com/engine/classes/MultiTouchSource.md), which feed [InputController](https://api.playcanvas.com/engine/classes/InputController.md)s such as [OrbitController](https://api.playcanvas.com/engine/classes/OrbitController.md), [FlyController](https://api.playcanvas.com/engine/classes/FlyController.md) and [FocusController](https://api.playcanvas.com/engine/classes/FocusController.md). ## Constructors ### constructor ```ts new GamePads() ``` Create a new GamePads instance. ## Properties ### current ```ts current: GamePad[] = [] ``` The list of current gamepads. ### gamepadsSupported ```ts gamepadsSupported: boolean ``` Whether gamepads are supported by this device. ## Methods ### findById ```ts findById(id: string): GamePad | null ``` Find a connected [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) from its identifier. **Parameters** - `id` (`string`): The identifier to search for. **Returns** [`GamePad`](https://api.playcanvas.com/engine/classes/GamePad.md) `| null`: The [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) with the matching identifier or null if no gamepad is found or the gamepad is not connected. ### findByIndex ```ts findByIndex(index: number): GamePad | null ``` Find a connected [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) from its device index. **Parameters** - `index` (`number`): The device index to search for. **Returns** [`GamePad`](https://api.playcanvas.com/engine/classes/GamePad.md) `| null`: The [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) with the matching device index or null if no gamepad is found or the gamepad is not connected. ### getAxis ```ts 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](https://api.playcanvas.com/engine/variables/PAD_1.md), [PAD_2](https://api.playcanvas.com/engine/variables/PAD_2.md), 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](https://api.playcanvas.com/engine/variables/PAD_L_STICK_X.md), etc. **Returns** `number`: The value of the axis between -1 and 1. ### getMap ```ts 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 ```ts 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](https://api.playcanvas.com/engine/variables/PAD_1.md), [PAD_2](https://api.playcanvas.com/engine/variables/PAD_2.md), etc. For gamepad index call the function from the pad. - `button` (`number`): The button to test, use constants [PAD_FACE_1](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: True if the button is pressed. ### poll ```ts poll(pads?: GamePad[]): GamePad[] ``` Poll for the latest data from the gamepad API. **Parameters** - `pads` ([`GamePad`](https://api.playcanvas.com/engine/classes/GamePad.md)`[]`, optional, default `[]`): An optional array used to receive the gamepads mapping. This array will be returned by this function. **Returns** [`GamePad`](https://api.playcanvas.com/engine/classes/GamePad.md)`[]`: An array of gamepads and mappings for the model of gamepad that is attached. **Example** ```ts const gamepads = new GamePads(); const pads = gamepads.poll(); ``` ### pulse ```ts pulse(orderIndex: number, intensity: number, duration: number, options?: object): Promise ``` Make the gamepad vibrate. **Parameters** - `orderIndex` (`number`): The index of the pad to check, use constants [PAD_1](https://api.playcanvas.com/engine/variables/PAD_1.md), [PAD_2](https://api.playcanvas.com/engine/variables/PAD_2.md), 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`: Return a Promise resulting in true if the pulse was successfully completed. ### pulseAll ```ts pulseAll(intensity: number, duration: number, options?: object): Promise ``` 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`: Return a Promise resulting in an array of booleans defining if the pulse was successfully completed for every gamepads. ### wasPressed ```ts 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](https://api.playcanvas.com/engine/variables/PAD_1.md), [PAD_2](https://api.playcanvas.com/engine/variables/PAD_2.md), etc. For gamepad index call the function from the pad. - `button` (`number`): The button to test, use constants [PAD_FACE_1](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: True if the button was pressed since the last frame. ### wasReleased ```ts 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](https://api.playcanvas.com/engine/variables/PAD_1.md), [PAD_2](https://api.playcanvas.com/engine/variables/PAD_2.md), etc. For gamepad index call the function from the pad. - `button` (`number`): The button to test, use constants [PAD_FACE_1](https://api.playcanvas.com/engine/variables/PAD_FACE_1.md), etc. **Returns** `boolean`: True if the button was released since the last frame. ## Events ### EVENT_GAMEPADCONNECTED ```ts static EVENT_GAMEPADCONNECTED: string = 'gamepadconnected' ``` Fired when a gamepad is connected. The handler is passed the [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) object that was connected. **Example** ```ts 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); ``` ### EVENT_GAMEPADDISCONNECTED ```ts static EVENT_GAMEPADDISCONNECTED: string = 'gamepaddisconnected' ``` Fired when a gamepad is disconnected. The handler is passed the [GamePad](https://api.playcanvas.com/engine/classes/GamePad.md) object that was disconnected. **Example** ```ts const onPadDisconnected = (pad) => { // Pause the game. }; app.keyboard.on("gamepaddisconnected", onPadDisconnected, this); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Keyboard.md # Keyboard Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/keyboard.js#L79 Manages keyboard input by tracking key states and dispatching events. Extends [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) in order to fire `keydown` and `keyup` events (see [KeyboardEvent](https://api.playcanvas.com/engine/classes/KeyboardEvent.md)). 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](https://api.playcanvas.com/engine/classes/Keyboard.md#waspressed) and [Keyboard#wasReleased](https://api.playcanvas.com/engine/classes/Keyboard.md#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](https://api.playcanvas.com/engine/classes/AppBase.md#keyboard). For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see [KeyboardMouseSource](https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md), [GamepadSource](https://api.playcanvas.com/engine/classes/GamepadSource.md) and [MultiTouchSource](https://api.playcanvas.com/engine/classes/MultiTouchSource.md), which feed [InputController](https://api.playcanvas.com/engine/classes/InputController.md)s such as [OrbitController](https://api.playcanvas.com/engine/classes/OrbitController.md), [FlyController](https://api.playcanvas.com/engine/classes/FlyController.md) and [FocusController](https://api.playcanvas.com/engine/classes/FocusController.md). ## Constructors ### constructor ```ts 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](https://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html) 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** ```ts // attach keyboard listeners to the window const keyboard = new Keyboard(window); ``` ## Properties ### preventDefault ```ts preventDefault: boolean ``` Call preventDefault() in key event handlers. ### stopPropagation ```ts stopPropagation: boolean ``` Call stopPropagation() in key event handlers. ## Methods ### attach ```ts 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](https://api.playcanvas.com/engine/classes/Mouse.md#attach), held input states are not preserved. **Parameters** - `element` (`Element | Window`): The element to listen for keyboard events on. ### detach ```ts 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 ```ts 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 ```ts 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 ```ts 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. ## Events ### EVENT_KEYDOWN ```ts static EVENT_KEYDOWN: string = 'keydown' ``` Fired when a key is pressed. The handler is passed a [KeyboardEvent](https://api.playcanvas.com/engine/classes/KeyboardEvent.md). **Example** ```ts 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); ``` ### EVENT_KEYUP ```ts static EVENT_KEYUP: string = 'keyup' ``` Fired when a key is released. The handler is passed a [KeyboardEvent](https://api.playcanvas.com/engine/classes/KeyboardEvent.md). **Example** ```ts 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); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/KeyboardEvent.md # KeyboardEvent Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/keyboard-event.js#L14 The KeyboardEvent is passed into all event handlers registered on the [Keyboard](https://api.playcanvas.com/engine/classes/Keyboard.md). The events are: - [Keyboard.EVENT_KEYDOWN](https://api.playcanvas.com/engine/classes/Keyboard.md#event_keydown) - [Keyboard.EVENT_KEYUP](https://api.playcanvas.com/engine/classes/Keyboard.md#event_keyup) ## Constructors ### constructor ```ts new KeyboardEvent(keyboard?: Keyboard, event?: KeyboardEvent) ``` Create a new KeyboardEvent. **Parameters** - `keyboard` ([`Keyboard`](https://api.playcanvas.com/engine/classes/Keyboard.md), optional): The keyboard object which is firing the event. - `event` (`KeyboardEvent`, optional): The original browser event that was fired. **Example** ```ts 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); ``` ## Properties ### element ```ts element: Element | null = null ``` The element that fired the keyboard event. ### event ```ts event: KeyboardEvent | null = null ``` The original browser event which was fired. ### key ```ts key: number | null = null ``` The keyCode of the key that has changed. See the KEY_* constants. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Mouse.md # Mouse Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse.js#L36 Manages mouse input by tracking button states and dispatching events. Extends [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) to fire `mousedown`, `mouseup`, `mousemove` and `mousewheel` events (see [MouseEvent](https://api.playcanvas.com/engine/classes/MouseEvent.md)). 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](https://api.playcanvas.com/engine/classes/AppBase.md#mouse). For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see [KeyboardMouseSource](https://api.playcanvas.com/engine/classes/KeyboardMouseSource.md), [GamepadSource](https://api.playcanvas.com/engine/classes/GamepadSource.md) and [MultiTouchSource](https://api.playcanvas.com/engine/classes/MultiTouchSource.md), which feed [InputController](https://api.playcanvas.com/engine/classes/InputController.md)s such as [OrbitController](https://api.playcanvas.com/engine/classes/OrbitController.md), [FlyController](https://api.playcanvas.com/engine/classes/FlyController.md) and [FocusController](https://api.playcanvas.com/engine/classes/FocusController.md). ## Constructors ### constructor ```ts new Mouse(element?: Element) ``` Create a new Mouse instance. **Parameters** - `element` (`Element`, optional): The Element that the mouse events are attached to. ## Methods ### attach ```ts 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](https://api.playcanvas.com/engine/classes/Keyboard.md#attach). **Parameters** - `element` (`Element`): The DOM element to attach the mouse to. ### detach ```ts 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 ```ts disableContextMenu(): void ``` Disable the context menu usually activated with right-click. ### disablePointerLock ```ts disablePointerLock(success?: LockMouseCallback): void ``` Return control of the mouse cursor to the user. **Parameters** - `success` ([`LockMouseCallback`](https://api.playcanvas.com/engine/types/LockMouseCallback.md), optional): Function called when the mouse lock is disabled. ### enableContextMenu ```ts enableContextMenu(): void ``` Enable the context menu usually activated with right-click. This option is active by default. ### enablePointerLock ```ts 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: - In some browsers this will only work when the browser is running in fullscreen mode. See [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) for more details. - Enabling pointer lock can only be initiated by a user action e.g. in the event handler for a mouse or keyboard input. **Parameters** - `success` ([`LockMouseCallback`](https://api.playcanvas.com/engine/types/LockMouseCallback.md), optional): Function called if the request for mouse lock is successful. - `error` ([`LockMouseCallback`](https://api.playcanvas.com/engine/types/LockMouseCallback.md), optional): Function called if the request for mouse lock is unsuccessful. ### isPressed ```ts isPressed(button: number): boolean ``` Returns true if the mouse button is currently pressed. **Parameters** - `button` (`number`): The mouse button to test. Can be: - [MOUSEBUTTON_LEFT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_LEFT.md) - [MOUSEBUTTON_MIDDLE](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_MIDDLE.md) - [MOUSEBUTTON_RIGHT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_RIGHT.md) **Returns** `boolean`: True if the mouse button is current pressed. ### update ```ts update(): void ``` Update method, should be called once per frame. ### wasPressed ```ts 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: - [MOUSEBUTTON_LEFT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_LEFT.md) - [MOUSEBUTTON_MIDDLE](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_MIDDLE.md) - [MOUSEBUTTON_RIGHT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_RIGHT.md) **Returns** `boolean`: True if the mouse button was pressed since the last update. ### wasReleased ```ts 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: - [MOUSEBUTTON_LEFT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_LEFT.md) - [MOUSEBUTTON_MIDDLE](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_MIDDLE.md) - [MOUSEBUTTON_RIGHT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_RIGHT.md) **Returns** `boolean`: True if the mouse button was released since the last update. ### isPointerLocked ```ts static isPointerLocked(): boolean ``` Check if the mouse pointer has been locked, using [enablePointerLock](https://api.playcanvas.com/engine/classes/Mouse.md#enablepointerlock). **Returns** `boolean`: True if locked. ## Events ### EVENT_MOUSEDOWN ```ts static EVENT_MOUSEDOWN: string = 'mousedown' ``` Fired when a mouse button is pressed. The handler is passed a [MouseEvent](https://api.playcanvas.com/engine/classes/MouseEvent.md). **Example** ```ts app.mouse.on('mousedown', (e) => { console.log(`The ${e.button} button was pressed at position: ${e.x}, ${e.y}`); }); ``` ### EVENT_MOUSEMOVE ```ts static EVENT_MOUSEMOVE: string = 'mousemove' ``` Fired when the mouse is moved. The handler is passed a [MouseEvent](https://api.playcanvas.com/engine/classes/MouseEvent.md). **Example** ```ts app.mouse.on('mousemove', (e) => { console.log(`Current mouse position is: ${e.x}, ${e.y}`); }); ``` ### EVENT_MOUSEUP ```ts static EVENT_MOUSEUP: string = 'mouseup' ``` Fired when a mouse button is released. The handler is passed a [MouseEvent](https://api.playcanvas.com/engine/classes/MouseEvent.md). **Example** ```ts app.mouse.on('mouseup', (e) => { console.log(`The ${e.button} button was released at position: ${e.x}, ${e.y}`); }); ``` ### EVENT_MOUSEWHEEL ```ts static EVENT_MOUSEWHEEL: string = 'mousewheel' ``` Fired when a mouse wheel is moved. The handler is passed a [MouseEvent](https://api.playcanvas.com/engine/classes/MouseEvent.md). **Example** ```ts app.mouse.on('mousewheel', (e) => { console.log(`The mouse wheel was moved by ${e.wheelDelta}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/MouseEvent.md # MouseEvent Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse-event.js#L27 The MouseEvent object is passed into all event handlers registered on the [Mouse](https://api.playcanvas.com/engine/classes/Mouse.md). The events are: - [Mouse.EVENT_MOUSEDOWN](https://api.playcanvas.com/engine/classes/Mouse.md#event_mousedown) - [Mouse.EVENT_MOUSEUP](https://api.playcanvas.com/engine/classes/Mouse.md#event_mouseup) - [Mouse.EVENT_MOUSEMOVE](https://api.playcanvas.com/engine/classes/Mouse.md#event_mousemove) - [Mouse.EVENT_MOUSEWHEEL](https://api.playcanvas.com/engine/classes/Mouse.md#event_mousewheel) ## Constructors ### constructor ```ts new MouseEvent(mouse: Mouse, event: MouseEvent | WheelEvent) ``` Create a new MouseEvent instance. **Parameters** - `mouse` ([`Mouse`](https://api.playcanvas.com/engine/classes/Mouse.md)): The Mouse device that is firing this event. - `event` (`MouseEvent | WheelEvent`): The original browser event that fired. ## Properties ### altKey ```ts altKey: boolean = false ``` True if the alt key was pressed when this event was fired. ### button ```ts button: number = MOUSEBUTTON_NONE ``` The mouse button associated with this event. Can be: - [MOUSEBUTTON_LEFT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_LEFT.md) - [MOUSEBUTTON_MIDDLE](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_MIDDLE.md) - [MOUSEBUTTON_RIGHT](https://api.playcanvas.com/engine/variables/MOUSEBUTTON_RIGHT.md) ### buttons ```ts 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 ```ts ctrlKey: boolean = false ``` True if the ctrl key was pressed when this event was fired. ### dx ```ts 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 ```ts 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 ```ts element: Element ``` The element that the mouse was fired from. ### event ```ts event: MouseEvent | WheelEvent ``` The original browser event. ### metaKey ```ts metaKey: boolean = false ``` True if the meta key was pressed when this event was fired. ### shiftKey ```ts shiftKey: boolean = false ``` True if the shift key was pressed when this event was fired. ### wheelDelta ```ts wheelDelta: number = 0 ``` A value representing the amount the mouse wheel has moved, only valid for [Mouse.EVENT_MOUSEWHEEL](https://api.playcanvas.com/engine/classes/Mouse.md#event_mousewheel) events. ### x ```ts x: number = 0 ``` The x coordinate of the mouse pointer relative to the element [Mouse](https://api.playcanvas.com/engine/classes/Mouse.md) is attached to. ### y ```ts y: number = 0 ``` The y coordinate of the mouse pointer relative to the element [Mouse](https://api.playcanvas.com/engine/classes/Mouse.md) is attached to. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Touch.md # Touch Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L40 A instance of a single point touch on a [TouchDevice](https://api.playcanvas.com/engine/classes/TouchDevice.md). ## Constructors ### constructor ```ts new Touch(touch: Touch) ``` Create a new Touch object from the browser Touch. **Parameters** - `touch` (`Touch`): The browser Touch object. ## Properties ### id ```ts id: number ``` The identifier of the touch. ### target ```ts target: Element ``` The target DOM element of the touch event. ### touch ```ts touch: Touch ``` The original browser Touch object. ### x ```ts x: number ``` The x coordinate relative to the element that the TouchDevice is attached to. ### y ```ts y: number ``` The y coordinate relative to the element that the TouchDevice is attached to. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TouchDevice.md # TouchDevice Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-device.js#L17 Manages touch input by handling and dispatching touch events. Extends [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) to fire `touchstart`, `touchend`, `touchmove`, and `touchcancel` events (see [TouchEvent](https://api.playcanvas.com/engine/classes/TouchEvent.md)). 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](https://api.playcanvas.com/engine/classes/AppBase.md#touch). ## Constructors ### constructor ```ts 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. ## Methods ### attach ```ts 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 ```ts detach(): void ``` Detach a device from the element it is attached to. ## Events ### EVENT_TOUCHCANCEL ```ts 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](https://api.playcanvas.com/engine/classes/TouchEvent.md). **Example** ```ts app.touch.on('touchcancel', (e) => { console.log(`Touch canceled at position: ${e.x}, ${e.y}`); }); ``` ### EVENT_TOUCHEND ```ts static EVENT_TOUCHEND: string = 'touchend' ``` Fired when a touch ends. The handler is passed a [TouchEvent](https://api.playcanvas.com/engine/classes/TouchEvent.md). **Example** ```ts app.touch.on('touchend', (e) => { console.log(`Touch ended at position: ${e.x}, ${e.y}`); }); ``` ### EVENT_TOUCHMOVE ```ts static EVENT_TOUCHMOVE: string = 'touchmove' ``` Fired when a touch moves. The handler is passed a [TouchEvent](https://api.playcanvas.com/engine/classes/TouchEvent.md). **Example** ```ts app.touch.on('touchmove', (e) => { console.log(`Touch moved to position: ${e.x}, ${e.y}`); }); ``` ### EVENT_TOUCHSTART ```ts static EVENT_TOUCHSTART: string = 'touchstart' ``` Fired when a touch starts. The handler is passed a [TouchEvent](https://api.playcanvas.com/engine/classes/TouchEvent.md). **Example** ```ts app.touch.on('touchstart', (e) => { console.log(`Touch started at position: ${e.x}, ${e.y}`); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/TouchEvent.md # TouchEvent Class · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L103 The TouchEvent object is passed into all event handlers registered on the [TouchDevice](https://api.playcanvas.com/engine/classes/TouchDevice.md). The events are: - [TouchDevice.EVENT_TOUCHSTART](https://api.playcanvas.com/engine/classes/TouchDevice.md#event_touchstart) - [TouchDevice.EVENT_TOUCHEND](https://api.playcanvas.com/engine/classes/TouchDevice.md#event_touchend) - [TouchDevice.EVENT_TOUCHMOVE](https://api.playcanvas.com/engine/classes/TouchDevice.md#event_touchmove) - [TouchDevice.EVENT_TOUCHCANCEL](https://api.playcanvas.com/engine/classes/TouchDevice.md#event_touchcancel) ## Constructors ### constructor ```ts new TouchEvent(device: TouchDevice, event: TouchEvent) ``` Create a new TouchEvent instance. It is created from an existing browser event. **Parameters** - `device` ([`TouchDevice`](https://api.playcanvas.com/engine/classes/TouchDevice.md)): The source device of the touch events. - `event` (`TouchEvent`): The original browser TouchEvent. ## Properties ### changedTouches ```ts changedTouches: Touch[] = [] ``` A list of touches that have changed since the last event. ### element ```ts element: Element ``` The target DOM element that the event was fired from. ### event ```ts event: TouchEvent ``` The original browser TouchEvent. ### touches ```ts touches: Touch[] = [] ``` A list of all touches currently in contact with the device. ## Methods ### getTouchById ```ts 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`](https://api.playcanvas.com/engine/classes/Touch.md)`[]`): An array of touches to search. **Returns** [`Touch`](https://api.playcanvas.com/engine/classes/Touch.md) `| null`: The [Touch](https://api.playcanvas.com/engine/classes/Touch.md) object or null. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/getTouchTargetCoords.md # getTouchTargetCoords Function · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L14 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BoundingBox.md # BoundingBox Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/bounding-box.js#L48 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](https://api.playcanvas.com/engine/classes/BoundingBox.md#center) and [halfExtents](https://api.playcanvas.com/engine/classes/BoundingBox.md#halfextents). Set it from its extreme corners with [setMinMax](https://api.playcanvas.com/engine/classes/BoundingBox.md#setminmax) and read them back with [getMin](https://api.playcanvas.com/engine/classes/BoundingBox.md#getmin) and [getMax](https://api.playcanvas.com/engine/classes/BoundingBox.md#getmax). Fit a box to vertex data with [compute](https://api.playcanvas.com/engine/classes/BoundingBox.md#compute), grow it to enclose another box with [add](https://api.playcanvas.com/engine/classes/BoundingBox.md#add), and move a local box into world space with [setFromTransformedAabb](https://api.playcanvas.com/engine/classes/BoundingBox.md#setfromtransformedaabb), which is how the engine derives a mesh instance's world bounds from its mesh's local bounds. Tests such as [intersects](https://api.playcanvas.com/engine/classes/BoundingBox.md#intersects), [containsPoint](https://api.playcanvas.com/engine/classes/BoundingBox.md#containspoint) and [intersectsRay](https://api.playcanvas.com/engine/classes/BoundingBox.md#intersectsray) return a boolean and allocate nothing. [closestPoint](https://api.playcanvas.com/engine/classes/BoundingBox.md#closestpoint) writes into an optional result vector, while [getMin](https://api.playcanvas.com/engine/classes/BoundingBox.md#getmin) and [getMax](https://api.playcanvas.com/engine/classes/BoundingBox.md#getmax) return the box's own cached vectors, which should be treated as read-only. The constructor copies the vectors it is given. **Example** ```ts // 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** ```ts // 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}`); } ``` ## Constructors ### constructor ```ts new BoundingBox(center?: Vec3, halfExtents?: Vec3) ``` Create a new BoundingBox instance. The bounding box is axis-aligned. **Parameters** - `center` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Center of box. The constructor copies this parameter. Defaults to (0, 0, 0). - `halfExtents` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Half the distance across the box in each axis. The constructor copies this parameter. Defaults to (0.5, 0.5, 0.5). ## Properties ### center ```ts readonly center: Vec3 ``` Center of box. ### halfExtents ```ts readonly halfExtents: Vec3 ``` Half the distance across the box in each axis. ## Methods ### add ```ts add(other: BoundingBox): void ``` Combines two bounding boxes into one, enclosing both. **Parameters** - `other` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): Bounding box to add. ### clone ```ts clone(): BoundingBox ``` Returns a clone of the AABB. **Returns** [`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md): A duplicate AABB. ### closestPoint ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Point to find the closest point to. - `result` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to store the result in. If not provided, a new Vec3 is created and returned. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The closest point on the AABB. **Example** ```ts 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** ```ts // Reuse a result vector to avoid allocations in hot paths const result = new Vec3(); box.closestPoint(point, result); ``` ### compute ```ts compute(vertices: ArrayLike, numVerts?: number): void ``` Compute the size of the AABB to encapsulate all specified vertices. **Parameters** - `vertices` (`ArrayLike`): 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 ```ts containsPoint(point: Vec3): boolean ``` Test if a point is inside an AABB. **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Point to test. **Returns** `boolean`: True if the point is inside the AABB and false otherwise. ### copy ```ts copy(src: BoundingBox): void ``` Copies the contents of a source AABB. **Parameters** - `src` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): The AABB to copy from. ### equals ```ts equals(other: BoundingBox): boolean ``` Reports whether two axis-aligned bounding boxes are equal. **Parameters** - `other` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): The AABB to compare to. **Returns** `boolean`: True if the AABBs have the same center and half extents, false otherwise. ### getMax ```ts getMax(): Vec3 ``` Return the maximum corner of the AABB. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Maximum corner. ### getMin ```ts getMin(): Vec3 ``` Return the minimum corner of the AABB. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Minimum corner. ### intersects ```ts intersects(other: BoundingBox): boolean ``` Test whether two axis-aligned bounding boxes intersect. **Parameters** - `other` ([`BoundingBox`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): Bounding box to test against. **Returns** `boolean`: True if there is an intersection. ### intersectsBoundingSphere ```ts intersectsBoundingSphere(sphere: BoundingSphere): boolean ``` Test if a Bounding Sphere is overlapping, enveloping, or inside this AABB. **Parameters** - `sphere` ([`BoundingSphere`](https://api.playcanvas.com/engine/classes/BoundingSphere.md)): Bounding Sphere to test. **Returns** `boolean`: True if the Bounding Sphere is overlapping, enveloping, or inside the AABB and false otherwise. ### intersectsRay ```ts intersectsRay(ray: Ray, point?: Vec3): boolean ``` Test if a ray intersects with the AABB. **Parameters** - `ray` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): Ray to test against (direction must be normalized). - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. ### setFromTransformedAabb ```ts 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`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): Box to transform and enclose. - `m` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): 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 ```ts 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** - `min` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The minimum corner of the AABB. - `max` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The maximum corner of the AABB. ### computeMinMax ```ts static computeMinMax(vertices: ArrayLike, min: Vec3, max: Vec3, numVerts?: number): void ``` Compute the min and max bounding values to encapsulate all specified vertices. **Parameters** - `vertices` (`ArrayLike`): The vertices used to compute the new size for the AABB. - `min` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Stored computed min value. - `max` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Stored computed max value. - `numVerts` (`number`, optional): Number of vertices to use from the beginning of vertices array. All vertices are used if not specified. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/BoundingSphere.md # BoundingSphere Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/bounding-sphere.js#L28 A bounding sphere is a volume for facilitating fast intersection testing. A sphere is a [center](https://api.playcanvas.com/engine/classes/BoundingSphere.md#center) and a [radius](https://api.playcanvas.com/engine/classes/BoundingSphere.md#radius). It is the cheapest bounding volume to test, so it suits broad-phase checks made before a finer test. [containsPoint](https://api.playcanvas.com/engine/classes/BoundingSphere.md#containspoint), [intersectsBoundingSphere](https://api.playcanvas.com/engine/classes/BoundingSphere.md#intersectsboundingsphere) and [intersectsRay](https://api.playcanvas.com/engine/classes/BoundingSphere.md#intersectsray) return a boolean and allocate nothing. Unlike [BoundingBox](https://api.playcanvas.com/engine/classes/BoundingBox.md), 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** ```ts // 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 } ``` ## Constructors ### constructor ```ts new BoundingSphere(center?: Vec3, radius?: number) ``` Creates a new BoundingSphere instance. **Parameters** - `center` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), 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** ```ts // Create a new bounding sphere centered on the origin with a radius of 0.5 const sphere = new BoundingSphere(); ``` ## Properties ### center ```ts readonly center: Vec3 ``` Center of sphere. ### radius ```ts radius: number ``` The radius of the bounding sphere. ## Methods ### containsPoint ```ts containsPoint(point: Vec3): boolean ``` Test if a point is inside the sphere. **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Point to test. **Returns** `boolean`: True if the point is inside the sphere and false otherwise. **Example** ```ts 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 ```ts intersectsBoundingSphere(sphere: BoundingSphere): boolean ``` Test if a Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere. **Parameters** - `sphere` ([`BoundingSphere`](https://api.playcanvas.com/engine/classes/BoundingSphere.md)): Bounding Sphere to test. **Returns** `boolean`: True if the Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere and false otherwise. ### intersectsRay ```ts intersectsRay(ray: Ray, point?: Vec3): boolean ``` Test if a ray intersects with the sphere. **Parameters** - `ray` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): Ray to test against (direction must be normalized). - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Color.md # Color Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/color.js#L30 An RGBA color. Each color component is a floating point value in the range 0 to 1. The [r](https://api.playcanvas.com/engine/classes/Color.md#r) (red), [g](https://api.playcanvas.com/engine/classes/Color.md#g) (green) and [b](https://api.playcanvas.com/engine/classes/Color.md#b) (blue) components define a color in RGB color space. The [a](https://api.playcanvas.com/engine/classes/Color.md#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](https://api.playcanvas.com/engine/classes/Color.md#linear) and [gamma](https://api.playcanvas.com/engine/classes/Color.md#gamma) when a value crosses that boundary. [fromString](https://api.playcanvas.com/engine/classes/Color.md#fromstring) and [toString](https://api.playcanvas.com/engine/classes/Color.md#tostring) exchange colors with the `#RRGGBB` and `#RRGGBBAA` notation used by CSS, and [lerp](https://api.playcanvas.com/engine/classes/Color.md#lerp) blends two colors. Methods modify the color they are called on and return it for chaining. Use [clone](https://api.playcanvas.com/engine/classes/Color.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Color.md#copy) to overwrite. The named constants such as [WHITE](https://api.playcanvas.com/engine/classes/Color.md#white) and [RED](https://api.playcanvas.com/engine/classes/Color.md#red) are frozen shared instances, so copy one before modifying it. **Example** ```ts // Set a material color from a CSS hex string material.diffuse.fromString('#ff8800'); material.update(); ``` **Example** ```ts // Fade between two colors without allocating const tint = new Color(); tint.lerp(Color.RED, Color.BLUE, t); ``` ## Constructors ### constructor ```ts 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** ```ts const c1 = new Color(); // defaults to 0, 0, 0, 1 const c2 = new Color(0.1, 0.2, 0.3, 0.4); ``` ```ts new Color(arr: number[]) ``` Creates a new Color instance. **Parameters** - `arr` (`number[]`): The array to set the color values from. **Example** ```ts const c = new Color([0.1, 0.2, 0.3, 0.4]); ``` ## Properties ### a ```ts a: number ``` The alpha component of the color. ### b ```ts b: number ``` The blue component of the color. ### g ```ts g: number ``` The green component of the color. ### r ```ts r: number ``` The red component of the color. ### BLACK ```ts static readonly BLACK: Color ``` A constant color set to black [0, 0, 0, 1]. ### BLUE ```ts static readonly BLUE: Color ``` A constant color set to blue [0, 0, 1, 1]. ### CYAN ```ts static readonly CYAN: Color ``` A constant color set to cyan [0, 1, 1, 1]. ### GRAY ```ts static readonly GRAY: Color ``` A constant color set to gray [0.5, 0.5, 0.5, 1]. ### GREEN ```ts static readonly GREEN: Color ``` A constant color set to green [0, 1, 0, 1]. ### MAGENTA ```ts static readonly MAGENTA: Color ``` A constant color set to magenta [1, 0, 1, 1]. ### RED ```ts static readonly RED: Color ``` A constant color set to red [1, 0, 0, 1]. ### WHITE ```ts static readonly WHITE: Color ``` A constant color set to white [1, 1, 1, 1]. ### YELLOW ```ts static readonly YELLOW: Color ``` A constant color set to yellow [1, 1, 0, 1]. ## Methods ### clone ```ts clone(): Color ``` Returns a clone of the specified color. **Returns** [`Color`](https://api.playcanvas.com/engine/classes/Color.md): A duplicate color object. **Example** ```ts const c = new Color(1, 0, 0, 1); const cClone = c.clone(); // cClone is [1, 0, 0, 1] ``` ### copy ```ts copy(rhs: Color): Color ``` Copies the contents of a source color to a destination color. **Parameters** - `rhs` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)): A color to copy to the specified color. **Returns** [`Color`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts 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 ```ts equals(rhs: Color): boolean ``` Reports whether two colors are equal. **Parameters** - `rhs` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)): The color to compare to the specified color. **Returns** `boolean`: True if the colors are equal and false otherwise. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts const c = new Color(); c.fromArray([1, 0, 1, 1]); // c is set to [1, 0, 1, 1] ``` ### fromString ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts const c = new Color(); c.fromString('#ff0000'); // c is now [1, 0, 0, 1] ``` ### gamma ```ts gamma(src?: Color): Color ``` Converts the color from linear to gamma color space. **Parameters** - `src` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md), optional): The color to convert to gamma color space. If not set, the operation is done in place. **Returns** [`Color`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts 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 ```ts lerp(lhs: Color, rhs: Color, alpha: number): Color ``` Returns the result of a linear interpolation between two specified colors. **Parameters** - `lhs` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)): The color to interpolate from. - `rhs` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)): 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`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts 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 ```ts linear(src?: Color): Color ``` Converts the color from gamma to linear color space. **Parameters** - `src` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md), optional): The color to convert to linear color space. If not set, the operation is done in place. **Returns** [`Color`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Color.md): Self for chaining. **Example** ```ts const c = new Color(); c.set(1, 0, 0, 1); // c is now red [1, 0, 0, 1] ``` ### toArray ```ts 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. ```ts 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 ```ts 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** ```ts const c = new Color(1, 1, 1); // Outputs #ffffff console.log(c.toString()); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Curve.md # Curve Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/curve.js#L22 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](https://api.playcanvas.com/engine/classes/Curve.md#add), then evaluate the curve at any time with [value](https://api.playcanvas.com/engine/classes/Curve.md#value). The [type](https://api.playcanvas.com/engine/classes/Curve.md#type) selects how values between keys are computed: [CURVE_LINEAR](https://api.playcanvas.com/engine/variables/CURVE_LINEAR.md), [CURVE_SMOOTHSTEP](https://api.playcanvas.com/engine/variables/CURVE_SMOOTHSTEP.md), [CURVE_SPLINE](https://api.playcanvas.com/engine/variables/CURVE_SPLINE.md) or [CURVE_STEP](https://api.playcanvas.com/engine/variables/CURVE_STEP.md). Curves drive values that change over time or over a normalized range, such as particle size over a particle's lifetime. **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts 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** ```ts 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 ]); ``` ## Properties ### keys ```ts 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 ```ts tension: number = 0.5 ``` Controls how [CURVE_SPLINE](https://api.playcanvas.com/engine/variables/CURVE_SPLINE.md) 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 ```ts type: number = CURVE_SMOOTHSTEP ``` The curve interpolation scheme. Can be: - [CURVE_LINEAR](https://api.playcanvas.com/engine/variables/CURVE_LINEAR.md) - [CURVE_SMOOTHSTEP](https://api.playcanvas.com/engine/variables/CURVE_SMOOTHSTEP.md) - [CURVE_SPLINE](https://api.playcanvas.com/engine/variables/CURVE_SPLINE.md) - [CURVE_STEP](https://api.playcanvas.com/engine/variables/CURVE_STEP.md) Defaults to [CURVE_SMOOTHSTEP](https://api.playcanvas.com/engine/variables/CURVE_SMOOTHSTEP.md). ## Accessors ### length ```ts get length(): number ``` Gets the number of keys in the curve. ## Methods ### add ```ts 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** ```ts 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 ```ts clear(): Curve ``` Removes all keys from the curve. **Returns** [`Curve`](https://api.playcanvas.com/engine/classes/Curve.md): The curve instance. **Example** ```ts const curve = new Curve([0, 1, 1, 2]); curve.clear(); // curve now has no keys ``` ### clone ```ts clone(): Curve ``` Returns a clone of the specified curve object. **Returns** [`Curve`](https://api.playcanvas.com/engine/classes/Curve.md): A clone of the specified curve. **Example** ```ts const curve = new Curve([0, 0, 1, 10]); const clonedCurve = curve.clone(); ``` ### closest ```ts 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** ```ts const curve = new Curve([0, 1, 0.5, 2, 1, 3]); const key = curve.closest(0.6); // returns [0.5, 2] ``` ### get ```ts 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** ```ts const curve = new Curve([0, 1, 1, 2]); const key = curve.get(0); // returns [0, 1] ``` ### remove ```ts 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** ```ts const curve = new Curve([0, 1, 1, 2]); curve.remove(0); // removes the key at time 0 ``` ### sort ```ts sort(): void ``` Sorts keys by time. ### value ```ts 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** ```ts const curve = new Curve([0, 0, 1, 10]); const value = curve.value(0.5); // returns interpolated value at time 0.5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CurveSet.md # CurveSet Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/curve-set.js#L24 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](https://api.playcanvas.com/engine/classes/CurveSet.md#type) applies that interpolation to every curve in the set, and [value](https://api.playcanvas.com/engine/classes/CurveSet.md#value) returns the value of each curve at a time as one array. Reach an individual [Curve](https://api.playcanvas.com/engine/classes/Curve.md) with [get](https://api.playcanvas.com/engine/classes/CurveSet.md#get). **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts new CurveSet(...args: any[]) ``` Creates a new CurveSet instance. **Parameters** - `args` (`any[]`): Variable arguments with several possible formats: - No arguments: Creates a CurveSet with a single default curve. - Single number argument: Creates a CurveSet with the specified number of default curves. - Single array argument: An array of arrays, where each sub-array contains keys (pairs of numbers with the time first and value second). - Multiple arguments: Each argument becomes a separate curve. **Example** ```ts // 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 ] ]); ``` ## Properties ### curves ```ts curves: Curve[] = [] ``` The array of curves in the set. ## Accessors ### length ```ts get length(): number ``` Gets the number of curves in the curve set. ### type ```ts get type(): number set type(value: number) ``` Gets the interpolation scheme applied to all curves in the curve set. ## Methods ### add ```ts add(data?: number[]): Curve ``` Appends a new curve to the curve set. The new curve adopts the curve set's current [CurveSet#type](https://api.playcanvas.com/engine/classes/CurveSet.md#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`](https://api.playcanvas.com/engine/classes/Curve.md): The newly created curve. **Example** ```ts const curveSet = new CurveSet([[0, 0, 1, 1]]); const curve = curveSet.add([0, 0, 1, 0.5]); // append a second curve ``` ### clear ```ts clear(): CurveSet ``` Removes all curves from the curve set, leaving it empty. **Returns** [`CurveSet`](https://api.playcanvas.com/engine/classes/CurveSet.md): The curve set instance. **Example** ```ts const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); curveSet.clear(); // the set now has no curves ``` ### clearKeys ```ts 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](https://api.playcanvas.com/engine/classes/CurveSet.md#value) still returns an array of the same length. **Returns** [`CurveSet`](https://api.playcanvas.com/engine/classes/CurveSet.md): The curve set instance. **Example** ```ts 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 ```ts clone(): CurveSet ``` Returns a clone of the specified curve set object. **Returns** [`CurveSet`](https://api.playcanvas.com/engine/classes/CurveSet.md): A clone of the specified curve set. **Example** ```ts const curveSet = new CurveSet([[0, 0, 1, 1]]); const clonedCurveSet = curveSet.clone(); ``` ### get ```ts get(index: number): Curve ``` Return a specific curve in the curve set. **Parameters** - `index` (`number`): The index of the curve to return. **Returns** [`Curve`](https://api.playcanvas.com/engine/classes/Curve.md): The curve at the specified index. **Example** ```ts const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); const curve = curveSet.get(0); // returns the first curve ``` ### remove ```ts remove(indexOrCurve: number | Curve): Curve | null ``` Removes a curve from the curve set. **Parameters** - `indexOrCurve` (`number |` [`Curve`](https://api.playcanvas.com/engine/classes/Curve.md)): The index of the curve to remove, or the curve instance itself. **Returns** [`Curve`](https://api.playcanvas.com/engine/classes/Curve.md) `| null`: The removed curve, or null if it was not found. **Example** ```ts 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 ```ts 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** ```ts 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 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/FloatPacking.md # FloatPacking Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/float-packing.js#L24 Utility static class providing functionality to pack float values to various storage representations. [float2Half](https://api.playcanvas.com/engine/classes/FloatPacking.md#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** ```ts // 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]); } ``` ## Methods ### float2Half ```ts 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** ```ts const half = FloatPacking.float2Half(1.5); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Frustum.md # Frustum Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/frustum.js#L65 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](https://api.playcanvas.com/engine/classes/CameraComponent.md#frustum). A frustum is six [Plane](https://api.playcanvas.com/engine/classes/Plane.md)s, read and written with [getPlane](https://api.playcanvas.com/engine/classes/Frustum.md#getplane) and [setPlane](https://api.playcanvas.com/engine/classes/Frustum.md#setplane), and normally derived from a camera's combined view-projection matrix with [setFromMat4](https://api.playcanvas.com/engine/classes/Frustum.md#setfrommat4). [containsPoint](https://api.playcanvas.com/engine/classes/Frustum.md#containspoint) and [containsAabb](https://api.playcanvas.com/engine/classes/Frustum.md#containsaabb) return a boolean. [containsSphere](https://api.playcanvas.com/engine/classes/Frustum.md#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** ```ts // Skip work for objects the camera cannot see const frustum = entity.camera.frustum; if (frustum.containsAabb(meshInstance.aabb)) { // visible: update it } ``` ## Constructors ### constructor ```ts new Frustum() ``` Create a new Frustum instance. **Example** ```ts const frustum = new Frustum(); ``` ## Methods ### add ```ts 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`](https://api.playcanvas.com/engine/classes/Frustum.md)): The other frustum to add. **Returns** [`Frustum`](https://api.playcanvas.com/engine/classes/Frustum.md): Self for chaining. ### clone ```ts clone(): Frustum ``` Returns a clone of the specified frustum. **Returns** [`Frustum`](https://api.playcanvas.com/engine/classes/Frustum.md): A duplicate frustum. **Example** ```ts const frustum = new Frustum(); const clone = frustum.clone(); ``` ### containsAabb ```ts 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](https://api.playcanvas.com/engine/classes/Frustum.md#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`](https://api.playcanvas.com/engine/classes/BoundingBox.md)): 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point to test. **Returns** `boolean`: True if the point is inside the frustum, false otherwise. ### containsSphere ```ts 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`](https://api.playcanvas.com/engine/classes/BoundingSphere.md)): 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 ```ts copy(src: Frustum): Frustum ``` Copies the contents of a source frustum to a destination frustum. **Parameters** - `src` ([`Frustum`](https://api.playcanvas.com/engine/classes/Frustum.md)): A source frustum to copy to the destination frustum. **Returns** [`Frustum`](https://api.playcanvas.com/engine/classes/Frustum.md): Self for chaining. **Example** ```ts const src = entity.camera.frustum; const dst = new Frustum(); dst.copy(src); ``` ### getPlane ```ts 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`](https://api.playcanvas.com/engine/classes/Plane.md)): The plane to write to. **Returns** [`Plane`](https://api.playcanvas.com/engine/classes/Plane.md): The supplied plane, containing the frustum plane. **Example** ```ts const plane = new Plane(); entity.camera.frustum.getPlane(0, plane); ``` ### setFromMat4 ```ts setFromMat4(matrix: Mat4): void ``` Updates the frustum shape based on the supplied 4x4 matrix. **Parameters** - `matrix` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The matrix describing the shape of the frustum. **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Plane.md)): The plane to store. **Returns** [`Frustum`](https://api.playcanvas.com/engine/classes/Frustum.md): Self for chaining. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Kernel.md # Kernel Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/kernel.js#L14 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](https://api.playcanvas.com/engine/classes/Kernel.md#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** ```ts // A kernel with 3 rings and 8 points in the innermost ring const offsets = Kernel.concentric(3, 8); // [0, 0, x1, y1, x2, y2, ...] ``` ## Methods ### concentric ```ts 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** ```ts // 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, ...] ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Mat3.md # Mat3 Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/mat3.js#L28 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](https://api.playcanvas.com/engine/classes/Mat3.md#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](https://api.playcanvas.com/engine/classes/Mat3.md#setfromquat), or take the upper-left 3x3 of a [Mat4](https://api.playcanvas.com/engine/classes/Mat4.md) with [setFromMat4](https://api.playcanvas.com/engine/classes/Mat3.md#setfrommat4), and apply it to a [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) with [transformVector](https://api.playcanvas.com/engine/classes/Mat3.md#transformvector). [getX](https://api.playcanvas.com/engine/classes/Mat3.md#getx), [getY](https://api.playcanvas.com/engine/classes/Mat3.md#gety) and [getZ](https://api.playcanvas.com/engine/classes/Mat3.md#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](https://api.playcanvas.com/engine/classes/Mat3.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Mat3.md#copy) to overwrite. [IDENTITY](https://api.playcanvas.com/engine/classes/Mat3.md#identity) and [ZERO](https://api.playcanvas.com/engine/classes/Mat3.md#zero) are frozen shared instances. **Example** ```ts // 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); ``` ## Constructors ### constructor ```ts new Mat3() ``` Create a new Mat3 instance. It is initialized to the identity matrix. ## Properties ### data ```ts data: Float32Array ``` Matrix elements in the form of a flat array. ### IDENTITY ```ts static readonly IDENTITY: Mat3 ``` A constant matrix set to the identity. ### ZERO ```ts static readonly ZERO: Mat3 ``` A constant matrix with all elements set to 0. ## Methods ### clone ```ts clone(): Mat3 ``` Creates a duplicate of the specified matrix. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): A duplicate matrix. **Example** ```ts 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 ```ts copy(rhs: Mat3): Mat3 ``` Copies the contents of a source 3x3 matrix to a destination 3x3 matrix. **Parameters** - `rhs` ([`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md)): A 3x3 matrix to be copied. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts 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 ```ts equals(rhs: Mat3): boolean ``` Reports whether two matrices are equal. **Parameters** - `rhs` ([`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md)): The other matrix. **Returns** `boolean`: True if the matrices are equal and false otherwise. **Example** ```ts 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 ```ts getX(x?: Vec3): Vec3 ``` Extracts the x-axis from the specified matrix. **Parameters** - `x` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the x axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The x-axis of the specified matrix. **Example** ```ts const m = new Mat3(); const xAxis = m.getX(); // Vec3(1, 0, 0) for identity matrix ``` ### getY ```ts getY(y?: Vec3): Vec3 ``` Extracts the y-axis from the specified matrix. **Parameters** - `y` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the y axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The y-axis of the specified matrix. **Example** ```ts const m = new Mat3(); const yAxis = m.getY(); // Vec3(0, 1, 0) for identity matrix ``` ### getZ ```ts getZ(z?: Vec3): Vec3 ``` Extracts the z-axis from the specified matrix. **Parameters** - `z` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the z axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The z-axis of the specified matrix. **Example** ```ts const m = new Mat3(); const zAxis = m.getZ(); // Vec3(0, 0, 1) for identity matrix ``` ### isIdentity ```ts isIdentity(): boolean ``` Reports whether the specified matrix is the identity matrix. **Returns** `boolean`: True if the matrix is identity and false otherwise. **Example** ```ts const m = new Mat3(); console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); ``` ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts const dst = new Mat3(); dst.set([0, 1, 2, 3, 4, 5, 6, 7, 8]); ``` ### setFromMat4 ```ts setFromMat4(m: Mat4): Mat3 ``` Converts the specified 4x4 matrix to a Mat3. **Parameters** - `m` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix to convert. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts const m4 = new Mat4(); const m3 = new Mat3().setFromMat4(m4); ``` ### setFromQuat ```ts setFromQuat(r: Quat): Mat3 ``` Sets this matrix to the given quaternion rotation. **Parameters** - `r` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): A quaternion rotation. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts const r = new Quat(1, 2, 3, 4).normalize(); const m = new Mat3(); m.setFromQuat(r); ``` ### setIdentity ```ts setIdentity(): Mat3 ``` Sets the matrix to the identity matrix. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts m.setIdentity(); console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); ``` ### toString ```ts toString(): string ``` Converts the matrix to string form. **Returns** `string`: The matrix in string form. **Example** ```ts const m = new Mat3(); // Outputs [1, 0, 0, 0, 1, 0, 0, 0, 1] console.log(m.toString()); ``` ### transformVector ```ts transformVector(vec: Vec3, res?: Vec3): Vec3 ``` Transforms a 3-dimensional vector by a 3x3 matrix. **Parameters** - `vec` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector to be transformed. - `res` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): An optional 3-dimensional vector to receive the result of the transformation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The input vector v transformed by the current instance. **Example** ```ts const m = new Mat3(); const v = new Vec3(1, 2, 3); const result = m.transformVector(v); ``` ### transpose ```ts transpose(src?: Mat3): Mat3 ``` Generates the transpose of the specified 3x3 matrix. **Parameters** - `src` ([`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md), optional): The matrix to transpose. If not set, the matrix is transposed in-place. **Returns** [`Mat3`](https://api.playcanvas.com/engine/classes/Mat3.md): Self for chaining. **Example** ```ts const m = new Mat3(); // Transpose in place m.transpose(); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Mat4.md # Mat4 Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/mat4.js#L48 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](https://api.playcanvas.com/engine/classes/Mat4.md#data), a 16-element `Float32Array` in column-major order: the translation occupies elements 12, 13 and 14. Build a transform with [setTRS](https://api.playcanvas.com/engine/classes/Mat4.md#settrs), [setFromEulerAngles](https://api.playcanvas.com/engine/classes/Mat4.md#setfromeulerangles) or [setFromAxisAngle](https://api.playcanvas.com/engine/classes/Mat4.md#setfromaxisangle), a camera matrix with [setLookAt](https://api.playcanvas.com/engine/classes/Mat4.md#setlookat), [setPerspective](https://api.playcanvas.com/engine/classes/Mat4.md#setperspective) or [setOrtho](https://api.playcanvas.com/engine/classes/Mat4.md#setortho), and read parts back with [getTranslation](https://api.playcanvas.com/engine/classes/Mat4.md#gettranslation), [getScale](https://api.playcanvas.com/engine/classes/Mat4.md#getscale) and [getEulerAngles](https://api.playcanvas.com/engine/classes/Mat4.md#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](https://api.playcanvas.com/engine/classes/Mat4.md#transformpoint) applies the full transform including translation, while [transformVector](https://api.playcanvas.com/engine/classes/Mat4.md#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](https://api.playcanvas.com/engine/classes/Mat4.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Mat4.md#copy) to overwrite. [IDENTITY](https://api.playcanvas.com/engine/classes/Mat4.md#identity) and [ZERO](https://api.playcanvas.com/engine/classes/Mat4.md#zero) are frozen shared instances, and the matrix returned by [GraphNode#getWorldTransform](https://api.playcanvas.com/engine/classes/GraphNode.md#getworldtransform) is internal storage to be treated as read-only. **Example** ```ts // 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** ```ts // Transform a local point into world space const worldPoint = entity.getWorldTransform().transformPoint(localPoint); ``` ## Constructors ### constructor ```ts new Mat4() ``` Create a new Mat4 instance. It is initialized to the identity matrix. ## Properties ### data ```ts data: Float32Array ``` Matrix elements in the form of a flat array. ### IDENTITY ```ts static readonly IDENTITY: Mat4 ``` A constant matrix set to the identity. ### ZERO ```ts static readonly ZERO: Mat4 ``` A constant matrix with all elements set to 0. ## Methods ### add ```ts add(rhs: Mat4): Mat4 ``` Adds the specified 4x4 matrix to the current instance. **Parameters** - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the second operand of the addition. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts const m = new Mat4(); m.add(Mat4.ONE); console.log("The result of the addition is: " + m.toString()); ``` ### add2 ```ts add2(lhs: Mat4, rhs: Mat4): Mat4 ``` Adds the specified 4x4 matrices together and stores the result in the current instance. **Parameters** - `lhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the first operand of the addition. - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the second operand of the addition. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts const m = new Mat4(); m.add2(Mat4.IDENTITY, Mat4.ONE); console.log("The result of the addition is: " + m.toString()); ``` ### clone ```ts clone(): Mat4 ``` Creates a duplicate of the specified matrix. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): A duplicate matrix. **Example** ```ts const src = new Mat4().setFromEulerAngles(10, 20, 30); const dst = src.clone(); console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different")); ``` ### copy ```ts copy(rhs: Mat4): Mat4 ``` Copies the contents of a source 4x4 matrix to a destination 4x4 matrix. **Parameters** - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): A 4x4 matrix to be copied. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts equals(rhs: Mat4): boolean ``` Reports whether two matrices are equal. **Parameters** - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The other matrix. **Returns** `boolean`: True if the matrices are equal and false otherwise. **Example** ```ts const a = new Mat4().setFromEulerAngles(10, 20, 30); const b = new Mat4(); console.log("The two matrices are " + (a.equals(b) ? "equal" : "different")); ``` ### getEulerAngles ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): A 3-d vector to receive the Euler angles. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): A 3-d vector containing the Euler angles. **Example** ```ts // 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 ```ts getScale(scale?: Vec3): Vec3 ``` Extracts the scale component from the specified 4x4 matrix. **Parameters** - `scale` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Vector to receive the scale. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The scale in X, Y and Z of the specified 4x4 matrix. **Example** ```ts // Query the scale component const scale = m.getScale(); ``` ### getTranslation ```ts getTranslation(t?: Vec3): Vec3 ``` Extracts the translational component from the specified 4x4 matrix. **Parameters** - `t` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the translation of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The translation of the specified 4x4 matrix. **Example** ```ts // Create a 4x4 matrix const m = new Mat4(); // Query the translation component const t = new Vec3(); m.getTranslation(t); ``` ### getX ```ts getX(x?: Vec3): Vec3 ``` Extracts the x-axis from the specified 4x4 matrix. **Parameters** - `x` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the x axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The x-axis of the specified 4x4 matrix. **Example** ```ts // Create a 4x4 matrix const m = new Mat4(); // Query the x-axis component const x = new Vec3(); m.getX(x); ``` ### getY ```ts getY(y?: Vec3): Vec3 ``` Extracts the y-axis from the specified 4x4 matrix. **Parameters** - `y` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the y axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The y-axis of the specified 4x4 matrix. **Example** ```ts // Create a 4x4 matrix const m = new Mat4(); // Query the y-axis component const y = new Vec3(); m.getY(y); ``` ### getZ ```ts getZ(z?: Vec3): Vec3 ``` Extracts the z-axis from the specified 4x4 matrix. **Parameters** - `z` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to receive the z axis of the matrix. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The z-axis of the specified 4x4 matrix. **Example** ```ts // Create a 4x4 matrix const m = new Mat4(); // Query the z-axis component const z = new Vec3(); m.getZ(z); ``` ### invert ```ts invert(src?: Mat4): Mat4 ``` Sets the matrix to the inverse of a source matrix. **Parameters** - `src` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md), optional): The matrix to invert. If not set, the matrix is inverted in-place. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts // 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 ```ts isIdentity(): boolean ``` Reports whether the specified matrix is the identity matrix. **Returns** `boolean`: True if the matrix is identity and false otherwise. **Example** ```ts const m = new Mat4(); console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); ``` ### mul ```ts mul(rhs: Mat4): Mat4 ``` Multiplies the current instance by the specified 4x4 matrix. **Parameters** - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the second multiplicand of the operation. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts mul2(lhs: Mat4, rhs: Mat4): Mat4 ``` Multiplies the specified 4x4 matrices together and stores the result in the current instance. **Parameters** - `lhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the first multiplicand of the operation. - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix used as the second multiplicand of the operation. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/Mat4.md#mul2). **Parameters** - `lhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The affine transformation 4x4 matrix used as the first multiplicand of the operation. - `rhs` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md)): The affine transformation 4x4 matrix used as the second multiplicand of the operation. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts set(src: number[]): Mat4 ``` Sets matrix data from an array. **Parameters** - `src` (`number[]`): Source array. Must have 16 values. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts const m = new Mat4(); m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); ``` ### setFromAxisAngle ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The normalized axis vector around which to rotate. - `angle` (`number`): The angle of rotation in degrees. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts // Create a 4x4 rotation matrix const rm = new Mat4().setFromAxisAngle(Vec3.UP, 90); ``` ### setFromEulerAngles ```ts 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`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts const m = new Mat4(); m.setFromEulerAngles(45, 90, 180); ``` ### setIdentity ```ts setIdentity(): Mat4 ``` Sets the specified matrix to the identity matrix. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts m.setIdentity(); console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); ``` ### setLookAt ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): 3-d vector holding view position. - `target` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 3-d vector holding reference point. - `up` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 3-d vector holding the up direction. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts // Create a 4x4 orthographic projection matrix const ortho = new Mat4().setOrtho(-2, 2, -2, 2, 1, 1000); ``` ### setPerspective ```ts 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`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts // Create a 4x4 perspective projection matrix const persp = new Mat4().setPerspective(45, 16 / 9, 1, 1000); ``` ### setReflection ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The normal of the plane to reflect by. - `distance` (`number`): The distance of plane to reflect by. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts // Create a reflection matrix for a horizontal plane at y=0 const reflection = new Mat4().setReflection(Vec3.UP, 0); ``` ### setTRS ```ts 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** - `t` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): A 3-d vector translation. - `r` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): A quaternion rotation. - `s` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): A 3-d vector scale. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts 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 ```ts toString(): string ``` Converts the specified matrix to string form. **Returns** `string`: The matrix in string form. **Example** ```ts 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 ```ts transformPoint(vec: Vec3, res?: Vec3): Vec3 ``` Transforms a 3-dimensional point by a 4x4 matrix. **Parameters** - `vec` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional point to be transformed. - `res` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): An optional 3-dimensional point to receive the result of the transformation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The input point v transformed by the current instance. **Example** ```ts // 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 ```ts transformVec4(vec: Vec4, res?: Vec4): Vec4 ``` Transforms a 4-dimensional vector by a 4x4 matrix. **Parameters** - `vec` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector to be transformed. - `res` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): An optional 4-dimensional vector to receive the result of the transformation. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): The input vector v transformed by the current instance. **Example** ```ts // 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 ```ts transformVector(vec: Vec3, res?: Vec3): Vec3 ``` Transforms a 3-dimensional vector by a 4x4 matrix. **Parameters** - `vec` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector to be transformed. - `res` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): An optional 3-dimensional vector to receive the result of the transformation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The input vector v transformed by the current instance. **Example** ```ts // 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 ```ts transpose(src?: Mat4): Mat4 ``` Sets the matrix to the transpose of a source matrix. **Parameters** - `src` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md), optional): The matrix to transpose. If not set, the matrix is transposed in-place. **Returns** [`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md): Self for chaining. **Example** ```ts const m = new Mat4(); // Transpose in place m.transpose(); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/OrientedBox.md # OrientedBox Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/oriented-box.js#L36 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](https://api.playcanvas.com/engine/classes/Mat4.md) 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](https://api.playcanvas.com/engine/classes/OrientedBox.md#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](https://api.playcanvas.com/engine/classes/OrientedBox.md#containspoint), [intersectsRay](https://api.playcanvas.com/engine/classes/OrientedBox.md#intersectsray) and [intersectsBoundingSphere](https://api.playcanvas.com/engine/classes/OrientedBox.md#intersectsboundingsphere) return a boolean and allocate nothing. **Example** ```ts // 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 } ``` ## Constructors ### constructor ```ts new OrientedBox(worldTransform?: Mat4, halfExtents?: Vec3) ``` Create a new OrientedBox instance. **Parameters** - `worldTransform` ([`Mat4`](https://api.playcanvas.com/engine/classes/Mat4.md), optional): Transform that has the orientation and position of the box. Scale is assumed to be one. Defaults to identity matrix. - `halfExtents` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Half the distance across the box in each local axis. Defaults to (0.5, 0.5, 0.5). ## Accessors ### worldTransform ```ts get worldTransform(): Mat4 set worldTransform(value: Mat4) ``` Gets the world transform of the OBB. ## Methods ### containsPoint ```ts containsPoint(point: Vec3): boolean ``` Test if a point is inside an OBB. **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Point to test. **Returns** `boolean`: True if the point is inside the OBB and false otherwise. ### intersectsBoundingSphere ```ts intersectsBoundingSphere(sphere: BoundingSphere): boolean ``` Test if a Bounding Sphere is overlapping, enveloping, or inside this OBB. **Parameters** - `sphere` ([`BoundingSphere`](https://api.playcanvas.com/engine/classes/BoundingSphere.md)): Bounding Sphere to test. **Returns** `boolean`: True if the Bounding Sphere is overlapping, enveloping or inside this OBB and false otherwise. ### intersectsRay ```ts intersectsRay(ray: Ray, point?: Vec3): boolean ``` Test if a ray intersects with the OBB. **Parameters** - `ray` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): Ray to test against (direction must be normalized). - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Plane.md # Plane Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/plane.js#L28 An infinite plane. Internally, it's represented in a parametric equation form: `ax + by + cz + distance = 0`. A plane is a [normal](https://api.playcanvas.com/engine/classes/Plane.md#normal) and a [distance](https://api.playcanvas.com/engine/classes/Plane.md#distance) from the origin along that normal. Define one with the constructor or [setFromPointNormal](https://api.playcanvas.com/engine/classes/Plane.md#setfrompointnormal) from a normal and a point the plane passes through, or with [set](https://api.playcanvas.com/engine/classes/Plane.md#set) from the four coefficients. None of these normalize the normal they are given, and [distance](https://api.playcanvas.com/engine/classes/Plane.md#distance) is only a true distance when the normal is unit length, so call [normalize](https://api.playcanvas.com/engine/classes/Plane.md#normalize) afterwards if it is not. [intersectsRay](https://api.playcanvas.com/engine/classes/Plane.md#intersectsray) and [intersectsLine](https://api.playcanvas.com/engine/classes/Plane.md#intersectsline) return whether a hit occurred and write the hit point into an optional vector. The ray's direction must be normalized. **Example** ```ts // 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); } ``` ## Constructors ### constructor ```ts new Plane(normal?: Vec3, distance?: number) ``` Create a new Plane instance. **Parameters** - `normal` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional, default `Vec3.UP`): Normal of the plane. The constructor copies this parameter. Defaults to [Vec3.UP](https://api.playcanvas.com/engine/classes/Vec3.md#up). - `distance` (`number`, optional, default `0`): The distance from the plane to the origin, along its normal. Defaults to 0. ## Properties ### distance ```ts distance: number ``` The distance from the plane to the origin, along its normal. ### normal ```ts normal: Vec3 ``` The normal of the plane. ## Methods ### clone ```ts clone(): Plane ``` Returns a clone of the specified plane. **Returns** [`Plane`](https://api.playcanvas.com/engine/classes/Plane.md): A duplicate plane. ### copy ```ts copy(src: Plane): Plane ``` Copies the contents of a source plane to a destination plane. **Parameters** - `src` ([`Plane`](https://api.playcanvas.com/engine/classes/Plane.md)): A source plane to copy to the destination plane. **Returns** [`Plane`](https://api.playcanvas.com/engine/classes/Plane.md): Self for chaining. ### intersectsLine ```ts intersectsLine(start: Vec3, end: Vec3, point?: Vec3): boolean ``` Test if the plane intersects between two points. **Parameters** - `start` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Start position of line. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): End position of line. - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. ### intersectsRay ```ts intersectsRay(ray: Ray, point?: Vec3): boolean ``` Test if a ray intersects with the infinite plane. **Parameters** - `ray` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): Ray to test against (direction must be normalized). - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. ### normalize ```ts normalize(): Plane ``` Normalize the plane. **Returns** [`Plane`](https://api.playcanvas.com/engine/classes/Plane.md): Self for chaining. ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Plane.md): Self for chaining. ### setFromPointNormal ```ts setFromPointNormal(point: Vec3, normal: Vec3): Plane ``` Sets the plane based on a specified normal and a point on the plane. **Parameters** - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The point on the plane. - `normal` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The normal of the plane. **Returns** [`Plane`](https://api.playcanvas.com/engine/classes/Plane.md): Self for chaining. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Quat.md # Quat Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/quat.js#L36 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](https://api.playcanvas.com/engine/classes/Quat.md#setfromeulerangles), [setFromAxisAngle](https://api.playcanvas.com/engine/classes/Quat.md#setfromaxisangle), [setFromDirections](https://api.playcanvas.com/engine/classes/Quat.md#setfromdirections) or [setFromMat4](https://api.playcanvas.com/engine/classes/Quat.md#setfrommat4), and read one back with [getEulerAngles](https://api.playcanvas.com/engine/classes/Quat.md#geteulerangles) or [getAxisAngle](https://api.playcanvas.com/engine/classes/Quat.md#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](https://api.playcanvas.com/engine/classes/Mat4.md) uses, and [transformVector](https://api.playcanvas.com/engine/classes/Quat.md#transformvector) applies a rotation to a [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md). Interpolate with [slerp](https://api.playcanvas.com/engine/classes/Quat.md#slerp) for constant angular speed, or with the cheaper [lerp](https://api.playcanvas.com/engine/classes/Quat.md#lerp) when the two rotations are close together. Methods modify the quaternion they are called on and return it for chaining. Use [clone](https://api.playcanvas.com/engine/classes/Quat.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Quat.md#copy) to overwrite. The static constants [IDENTITY](https://api.playcanvas.com/engine/classes/Quat.md#identity) and [ZERO](https://api.playcanvas.com/engine/classes/Quat.md#zero) are frozen shared instances, and the quaternion returned by [GraphNode#getRotation](https://api.playcanvas.com/engine/classes/GraphNode.md#getrotation) is internal storage to be treated as read-only. **Example** ```ts // Rotate an entity 90 degrees about the world Y axis const rotation = new Quat().setFromAxisAngle(Vec3.UP, 90); entity.setRotation(rotation); ``` **Example** ```ts // Turn smoothly towards a target orientation each frame const smoothed = new Quat().slerp(entity.getRotation(), targetRotation, 0.1); entity.setRotation(smoothed); ``` ## Constructors ### constructor ```ts 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** ```ts const q1 = new Quat(); // defaults to 0, 0, 0, 1 const q2 = new Quat(1, 2, 3, 4); ``` ```ts new Quat(arr: number[]) ``` Creates a new Quat instance. **Parameters** - `arr` (`number[]`): The array to set the quaternion values from. **Example** ```ts const q = new Quat([1, 2, 3, 4]); ``` ## Properties ### w ```ts w: number ``` The w component of the quaternion. ### x ```ts x: number ``` The x component of the quaternion. ### y ```ts y: number ``` The y component of the quaternion. ### z ```ts z: number ``` The z component of the quaternion. ### IDENTITY ```ts static readonly IDENTITY: Quat ``` A constant quaternion set to [0, 0, 0, 1] (the identity). Represents no rotation. ### ZERO ```ts static readonly ZERO: Quat ``` A constant quaternion set to [0, 0, 0, 0]. ## Methods ### clone ```ts clone(): Quat ``` Returns an identical copy of the specified quaternion. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): A new quaternion identical to this one. **Example** ```ts 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 ```ts copy(rhs: Quat): Quat ``` Copies the contents of a source quaternion to a destination quaternion. **Parameters** - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion to be copied. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const src = new Quat(); const dst = new Quat(); dst.copy(src); console.log("The two quaternions are " + (src.equals(dst) ? "equal" : "different")); ``` ### dot ```ts dot(other: Quat): number ``` Calculates the dot product of two quaternions. **Parameters** - `other` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion to calculate the dot product with. **Returns** `number`: The dot product of the two quaternions. **Example** ```ts 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 ```ts equals(rhs: Quat): boolean ``` Reports whether two quaternions are equal. **Parameters** - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion to be compared against. **Returns** `boolean`: True if the quaternions are equal and false otherwise. **Example** ```ts const a = new Quat(); const b = new Quat(); console.log("The two quaternions are " + (a.equals(b) ? "equal" : "different")); ``` ### equalsApprox ```ts equalsApprox(rhs: Quat, epsilon?: number): boolean ``` Reports whether two quaternions are equal using an absolute error tolerance. **Parameters** - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): 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** ```ts const a = new Quat(); const b = new Quat(); console.log("The two quaternions are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); ``` ### fromArray ```ts fromArray(arr: number[] | ArrayBufferView, offset?: number): Quat ``` Set the values of the quaternion from an array. **Parameters** - `arr` (`number[] | ArrayBufferView`): 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`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const q = new Quat(); q.fromArray([20, 10, 5, 0]); // q is set to [20, 10, 5, 0] ``` ### getAxisAngle ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector to receive the axis of rotation. **Returns** `number`: Angle, in degrees, of the rotation. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), 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`](https://api.playcanvas.com/engine/classes/Vec3.md): 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** ```ts 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 ```ts invert(src?: Quat): Quat ``` Generates the inverse of the specified quaternion. **Parameters** - `src` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md), optional): The quaternion to invert. If not set, the operation is done in place. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts // Create a quaternion rotated 180 degrees around the y-axis const rot = new Quat().setFromEulerAngles(0, 180, 0); // Invert in place rot.invert(); ``` ### length ```ts length(): number ``` Returns the magnitude of the specified quaternion. **Returns** `number`: The magnitude of the specified quaternion. **Example** ```ts const q = new Quat(0, 0, 0, 5); const len = q.length(); // Outputs 5 console.log("The length of the quaternion is: " + len); ``` ### lengthSq ```ts lengthSq(): number ``` Returns the magnitude squared of the specified quaternion. **Returns** `number`: The magnitude squared of the quaternion. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion to interpolate from. - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): 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`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts 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 ```ts mul(rhs: Quat): Quat ``` Returns the result of multiplying the specified quaternions together. **Parameters** - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion used as the second multiplicand of the operation. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts 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 ```ts mul2(lhs: Quat, rhs: Quat): Quat ``` Returns the result of multiplying the specified quaternions together. **Parameters** - `lhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion used as the first multiplicand of the operation. - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion used as the second multiplicand of the operation. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Quat.md), optional): The quaternion to scale. If not set, the operation is done in place. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const q = new Quat(1, 2, 3, 4); q.mulScalar(2); // q is now [2, 4, 6, 8] ``` ### normalize ```ts normalize(src?: Quat): Quat ``` Normalizes the specified quaternion. **Parameters** - `src` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md), optional): The quaternion to normalize. If not set, the operation is done in place. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const v = new Quat(0, 0, 0, 5); v.normalize(); // Outputs [0, 0, 0, 1] console.log(v.toString()); ``` ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts 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 ```ts setFromAxisAngle(axis: Vec3, angle: number): Quat ``` Sets a quaternion from an angular rotation around an axis. **Parameters** - `axis` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): World space axis around which to rotate. Should be normalized. - `angle` (`number`): Angle to rotate around the given axis in degrees. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const q = new Quat(); q.setFromAxisAngle(Vec3.UP, 90); ``` ### setFromDirections ```ts setFromDirections(from: Vec3, to: Vec3): Quat ``` Set the quaternion that represents the shortest rotation from one direction to another. **Parameters** - `from` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The direction to rotate from. It should be normalized. - `to` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The direction to rotate to. It should be normalized. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts const q = new Quat(); const from = new Vec3(0, 0, 1); const to = new Vec3(0, 1, 0); q.setFromDirections(from, to); ``` ### setFromEulerAngles ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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`](https://api.playcanvas.com/engine/classes/Quat.md): The quaternion itself (this), now representing the orientation from the specified XYZ Euler angles. Allows for method chaining. **Example** ```ts // 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** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Mat4.md)): The 4x4 matrix to convert. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Quat.md)): The quaternion to interpolate from. - `rhs` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md)): 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`](https://api.playcanvas.com/engine/classes/Quat.md): Self for chaining. **Example** ```ts 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 ```ts 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. ```ts 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 ```ts toString(): string ``` Converts the quaternion to string form. **Returns** `string`: The quaternion in string form. **Example** ```ts const q = new Quat(0, 0, 0, 1); // Outputs [0, 0, 0, 1] console.log(q.toString()); ``` ### transformVector ```ts transformVector(vec: Vec3, res?: Vec3): Vec3 ``` Transforms a 3-dimensional vector by the specified quaternion. **Parameters** - `vec` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector to be transformed. - `res` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): An optional 3-dimensional vector to receive the result of the transformation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The transformed vector (res if specified, otherwise a new Vec3). **Example** ```ts // 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); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Ray.md # Ray Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/ray.js#L20 An infinite ray. Rays are commonly used for picking, raycasting and intersection tests. A ray is an [origin](https://developer.mozilla.org/docs/Web/API/Window/origin) and a [direction](https://api.playcanvas.com/engine/classes/Ray.md#direction). It performs no intersection itself: pass it to the `intersectsRay` method of a [BoundingBox](https://api.playcanvas.com/engine/classes/BoundingBox.md), [BoundingSphere](https://api.playcanvas.com/engine/classes/BoundingSphere.md), [OrientedBox](https://api.playcanvas.com/engine/classes/OrientedBox.md), [Plane](https://api.playcanvas.com/engine/classes/Plane.md) or [Tri](https://api.playcanvas.com/engine/classes/Tri.md). Keep the direction normalized, as those tests require it. The constructor copies the vectors it is given, and [set](https://api.playcanvas.com/engine/classes/Ray.md#set) updates both in place. **Example** ```ts // 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(); ``` ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The starting point of the ray. The constructor copies this parameter. Defaults to the origin (0, 0, 0). - `direction` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), 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** ```ts // 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); ``` ## Properties ### direction ```ts readonly direction: Vec3 ``` The direction of the ray. ### origin ```ts readonly origin: Vec3 ``` The starting point of the ray. ## Methods ### clone ```ts clone(): Ray ``` Returns a clone of the Ray. **Returns** [`Ray`](https://api.playcanvas.com/engine/classes/Ray.md): A duplicate Ray. ### copy ```ts copy(src: Ray): Ray ``` Copies the contents of a source Ray. **Parameters** - `src` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): The Ray to copy from. **Returns** [`Ray`](https://api.playcanvas.com/engine/classes/Ray.md): Self for chaining. ### set ```ts set(origin: Vec3, direction: Vec3): Ray ``` Sets origin and direction to the supplied vector values. **Parameters** - `origin` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The starting point of the ray. - `direction` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The direction of the ray. **Returns** [`Ray`](https://api.playcanvas.com/engine/classes/Ray.md): Self for chaining. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Tri.md # Tri Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/tri.js#L32 A triangle defined by three [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) vectors. The vertices are [v0](https://api.playcanvas.com/engine/classes/Tri.md#v0), [v1](https://api.playcanvas.com/engine/classes/Tri.md#v1) and [v2](https://api.playcanvas.com/engine/classes/Tri.md#v2); the constructor and [set](https://api.playcanvas.com/engine/classes/Tri.md#set) copy the vectors they are given. [intersectsRay](https://api.playcanvas.com/engine/classes/Tri.md#intersectsray) tests a [Ray](https://api.playcanvas.com/engine/classes/Ray.md) 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** ```ts 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}`); } ``` ## Constructors ### constructor ```ts new Tri(v0?: Vec3, v1?: Vec3, v2?: Vec3) ``` Creates a new Tri object. **Parameters** - `v0` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional, default `Vec3.ZERO`): The first 3-dimensional vector. - `v1` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional, default `Vec3.ZERO`): The second 3-dimensional vector. - `v2` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional, default `Vec3.ZERO`): The third 3-dimensional vector. **Example** ```ts 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); ``` ## Properties ### v0 ```ts readonly v0: Vec3 ``` The first 3-dimensional vector of the triangle. ### v1 ```ts readonly v1: Vec3 ``` The second 3-dimensional vector of the triangle. ### v2 ```ts readonly v2: Vec3 ``` The third 3-dimensional vector of the triangle. ## Methods ### intersectsRay ```ts intersectsRay(ray: Ray, point?: Vec3): boolean ``` Test if a ray intersects with the triangle. **Parameters** - `ray` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md)): Ray to test against (direction must be normalized). - `point` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): If there is an intersection, the intersection point will be copied into here. **Returns** `boolean`: True if there is an intersection. ### set ```ts set(v0: Vec3, v1: Vec3, v2: Vec3): Tri ``` Sets the specified triangle to the supplied 3-dimensional vectors. **Parameters** - `v0` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The value set on the first 3-dimensional vector of the triangle. - `v1` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The value set on the second 3-dimensional vector of the triangle. - `v2` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The value set on the third 3-dimensional vector of the triangle. **Returns** [`Tri`](https://api.playcanvas.com/engine/classes/Tri.md): Self for chaining. **Example** ```ts 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 ```ts toString(): string ``` Converts the specified triangle to string form. **Returns** `string`: The triangle in string form. **Example** ```ts const t = new Tri(Vec3.UP, Vec3.RIGHT, Vec3.BACK); // Outputs [[0, 1, 0], [1, 0, 0], [0, 0, 1]] console.log(t.toString()); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Vec2.md # Vec2 Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec2.js#L29 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](https://api.playcanvas.com/engine/classes/Vec2.md#distance) and [dot](https://api.playcanvas.com/engine/classes/Vec2.md#dot) return a number. Two-operand forms such as [add2](https://api.playcanvas.com/engine/classes/Vec2.md#add2) and [sub2](https://api.playcanvas.com/engine/classes/Vec2.md#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](https://api.playcanvas.com/engine/classes/Vec2.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Vec2.md#copy) to overwrite one vector with another. The static constants such as [ZERO](https://api.playcanvas.com/engine/classes/Vec2.md#zero) and [UP](https://api.playcanvas.com/engine/classes/Vec2.md#up) are frozen shared instances: read them freely, but writing to one throws. Copy a constant before modifying it. **Example** ```ts // 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** ```ts // Chain mutating operations; each returns the vector it was called on const toTarget = new Vec2().sub2(target, position).normalize(); const distance = target.distance(position); ``` ## Constructors ### constructor ```ts 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** ```ts const v1 = new Vec2(); // defaults to 0, 0 const v2 = new Vec2(1, 2); ``` ```ts new Vec2(arr: number[]) ``` Creates a new Vec2 instance. **Parameters** - `arr` (`number[]`): The array to set the vector values from. **Example** ```ts const v = new Vec2([1, 2]); ``` ## Properties ### x ```ts x: number ``` The first component of the vector. ### y ```ts y: number ``` The second component of the vector. ### DOWN ```ts static readonly DOWN: Vec2 ``` A constant vector set to [0, -1]. ### HALF ```ts static readonly HALF: Vec2 ``` A constant vector set to [0.5, 0.5]. ### LEFT ```ts static readonly LEFT: Vec2 ``` A constant vector set to [-1, 0]. ### ONE ```ts static readonly ONE: Vec2 ``` A constant vector set to [1, 1]. ### RIGHT ```ts static readonly RIGHT: Vec2 ``` A constant vector set to [1, 0]. ### UP ```ts static readonly UP: Vec2 ``` A constant vector set to [0, 1]. ### ZERO ```ts static readonly ZERO: Vec2 ``` A constant vector set to [0, 0]. ## Methods ### add ```ts add(rhs: Vec2): Vec2 ``` Adds a 2-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The vector to add to the specified vector. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts add2(lhs: Vec2, rhs: Vec2): Vec2 ``` Adds two 2-dimensional vectors together and returns the result. **Parameters** - `lhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The first vector operand for the addition. - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second vector operand for the addition. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts addScalar(scalar: number): Vec2 ``` Adds a number to each element of a vector. **Parameters** - `scalar` (`number`): The number to add. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const vec = new Vec2(3, 4); vec.addScalar(2); // Outputs [5, 6] console.log("The result of the addition is: " + vec.toString()); ``` ### addScaled ```ts 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`](https://api.playcanvas.com/engine/classes/Vec2.md)): The vector to add to the specified vector. - `scalar` (`number`): The number to multiply the added vector with. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts 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** ```ts const v = new Vec2(6, 0); const angle = v.angle(); // Outputs 90.. console.log("The angle of the vector is: " + angle); ``` ### angleTo ```ts angleTo(rhs: Vec2): number ``` Returns the shortest Euler angle between two 2-dimensional vectors. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector to calculate angle to. **Returns** `number`: The shortest angle in degrees between two 2-dimensional vectors. **Example** ```ts 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 ```ts ceil(src?: Vec2): Vec2 ``` Each element is rounded up to the next largest integer. **Parameters** - `src` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md), optional): The vector to ceil. If not set, the operation is done in place. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(1.2, 3.1); v.ceil(); // v is now [2, 4] ``` ### clone ```ts clone(): Vec2 ``` Returns an identical copy of the specified 2-dimensional vector. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): A 2-dimensional vector containing the result of the cloning. **Example** ```ts const v = new Vec2(10, 20); const vclone = v.clone(); console.log("The result of the cloning is: " + vclone.toString()); ``` ### copy ```ts copy(rhs: Vec2): Vec2 ``` Copies the contents of a source 2-dimensional vector to a destination 2-dimensional vector. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): A vector to copy to the specified vector. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts cross(rhs: Vec2): number ``` Returns the result of a cross product operation performed on the two specified 2-dimensional vectors. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second 2-dimensional vector operand of the cross product. **Returns** `number`: The cross product of the two vectors. **Example** ```ts 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 ```ts distance(rhs: Vec2): number ``` Returns the distance between the two specified 2-dimensional vectors. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second 2-dimensional vector to test. **Returns** `number`: The distance between the two vectors. **Example** ```ts 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 ```ts distanceSq(rhs: Vec2): number ``` Returns the squared distance between the two specified 2-dimensional vectors. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second 2-dimensional vector to test. **Returns** `number`: The squared distance between the two vectors. **Example** ```ts 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 ```ts div(rhs: Vec2): Vec2 ``` Divides a 2-dimensional vector by another in place. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The vector to divide the specified vector by. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts div2(lhs: Vec2, rhs: Vec2): Vec2 ``` Divides one 2-dimensional vector by another and writes the result to the specified vector. **Parameters** - `lhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The dividend vector (the vector being divided). - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The divisor vector (the vector dividing the dividend). **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts divScalar(scalar: number): Vec2 ``` Divides each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to divide by. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const vec = new Vec2(3, 6); vec.divScalar(3); // Outputs [1, 2] console.log("The result of the division is: " + vec.toString()); ``` ### dot ```ts dot(rhs: Vec2): number ``` Returns the result of a dot product operation performed on the two specified 2-dimensional vectors. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second 2-dimensional vector operand of the dot product. **Returns** `number`: The result of the dot product operation. **Example** ```ts 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 ```ts equals(rhs: Vec2): boolean ``` Reports whether two vectors are equal. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The vector to compare to the specified vector. **Returns** `boolean`: True if the vectors are equal and false otherwise. **Example** ```ts const a = new Vec2(1, 2); const b = new Vec2(4, 5); console.log("The two vectors are " + (a.equals(b) ? "equal" : "different")); ``` ### equalsApprox ```ts equalsApprox(rhs: Vec2, epsilon?: number): boolean ``` Reports whether two vectors are equal using an absolute error tolerance. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): 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** ```ts const a = new Vec2(); const b = new Vec2(); console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); ``` ### floor ```ts floor(src?: Vec2): Vec2 ``` Each element is set to the largest integer less than or equal to its value. **Parameters** - `src` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md), optional): The vector to floor. If not set, the operation is done in place. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(1.2, 3.9); v.floor(); // v is now [1, 3] ``` ### fromArray ```ts fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec2 ``` Set the values of the vector from an array. **Parameters** - `arr` (`number[] | ArrayBufferView`): 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`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(); v.fromArray([20, 10]); // v is set to [20, 10] ``` ### length ```ts length(): number ``` Returns the magnitude of the specified 2-dimensional vector. **Returns** `number`: The magnitude of the specified 2-dimensional vector. **Example** ```ts const vec = new Vec2(3, 4); const len = vec.length(); // Outputs 5 console.log("The length of the vector is: " + len); ``` ### lengthSq ```ts lengthSq(): number ``` Returns the magnitude squared of the specified 2-dimensional vector. **Returns** `number`: The magnitude squared of the specified 2-dimensional vector. **Example** ```ts const vec = new Vec2(3, 4); const len = vec.lengthSq(); // Outputs 25 console.log("The length squared of the vector is: " + len); ``` ### lerp ```ts lerp(lhs: Vec2, rhs: Vec2, alpha: number): Vec2 ``` Returns the result of a linear interpolation between two specified 2-dimensional vectors. **Parameters** - `lhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector to interpolate from. - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): 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`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts max(rhs: Vec2): Vec2 ``` Each element is assigned a value from rhs parameter if it is larger. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector used as the source of elements to compare to. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const a = new Vec2(5, 1); const b = new Vec2(2, 8); a.max(b); // a is now [5, 8] ``` ### min ```ts min(rhs: Vec2): Vec2 ``` Each element is assigned a value from rhs parameter if it is smaller. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector used as the source of elements to compare to. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const a = new Vec2(5, 1); const b = new Vec2(2, 8); a.min(b); // a is now [2, 1] ``` ### mul ```ts mul(rhs: Vec2): Vec2 ``` Multiplies a 2-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts mul2(lhs: Vec2, rhs: Vec2): Vec2 ``` Returns the result of multiplying the specified 2-dimensional vectors together. **Parameters** - `lhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector used as the first multiplicand of the operation. - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The 2-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts mulScalar(scalar: number): Vec2 ``` Multiplies each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to multiply by. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const vec = new Vec2(3, 6); vec.mulScalar(3); // Outputs [9, 18] console.log("The result of the multiplication is: " + vec.toString()); ``` ### normalize ```ts 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`](https://api.playcanvas.com/engine/classes/Vec2.md), optional): The vector to normalize. If not set, the operation is done in place. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(25, 0); v.normalize(); // Outputs 1, 0 console.log("The result of the vector normalization is: " + v.toString()); ``` ### rotate ```ts 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`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts round(src?: Vec2): Vec2 ``` Each element is rounded up or down to the nearest integer. **Parameters** - `src` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md), optional): The vector to round. If not set, the operation is done in place. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(1.4, 3.6); v.round(); // v is now [1, 4] ``` ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const v = new Vec2(); v.set(5, 10); // Outputs 5, 10 console.log("The result of the vector set is: " + v.toString()); ``` ### sub ```ts sub(rhs: Vec2): Vec2 ``` Subtracts a 2-dimensional vector from another in place. **Parameters** - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The vector to subtract from the specified vector. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts sub2(lhs: Vec2, rhs: Vec2): Vec2 ``` Subtracts two 2-dimensional vectors from one another and returns the result. **Parameters** - `lhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The first vector operand for the subtraction. - `rhs` ([`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md)): The second vector operand for the subtraction. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts 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 ```ts subScalar(scalar: number): Vec2 ``` Subtracts a number from each element of a vector. **Parameters** - `scalar` (`number`): The number to subtract. **Returns** [`Vec2`](https://api.playcanvas.com/engine/classes/Vec2.md): Self for chaining. **Example** ```ts const vec = new Vec2(3, 4); vec.subScalar(2); // Outputs [1, 2] console.log("The result of the subtraction is: " + vec.toString()); ``` ### toArray ```ts 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. ```ts 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 ```ts toString(): string ``` Converts the vector to string form. **Returns** `string`: The vector in string form. **Example** ```ts const v = new Vec2(20, 10); // Outputs [20, 10] console.log(v.toString()); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Vec3.md # Vec3 Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec3.js#L34 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](https://api.playcanvas.com/engine/classes/Vec3.md#distance) and [dot](https://api.playcanvas.com/engine/classes/Vec3.md#dot) return a number. Two-operand forms such as [add2](https://api.playcanvas.com/engine/classes/Vec3.md#add2), [sub2](https://api.playcanvas.com/engine/classes/Vec3.md#sub2) and [cross](https://api.playcanvas.com/engine/classes/Vec3.md#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](https://api.playcanvas.com/engine/classes/Vec3.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Vec3.md#copy) to overwrite one vector with another. The static constants such as [ZERO](https://api.playcanvas.com/engine/classes/Vec3.md#zero), [UP](https://api.playcanvas.com/engine/classes/Vec3.md#up) and [FORWARD](https://api.playcanvas.com/engine/classes/Vec3.md#forward) are frozen shared instances: read them freely, but writing to one throws. Vectors returned by engine getters such as [GraphNode#getPosition](https://api.playcanvas.com/engine/classes/GraphNode.md#getposition) are internal storage and should be treated as read-only; clone them if you need to keep or modify the value. **Example** ```ts // 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** ```ts // 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** ```ts // Keep a copy of an entity's position, then modify it safely const start = entity.getPosition().clone(); start.y += 1; ``` ## Constructors ### constructor ```ts 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** ```ts const v1 = new Vec3(); // defaults to 0, 0, 0 const v2 = new Vec3(1, 2, 3); ``` ```ts new Vec3(arr: number[]) ``` Creates a new Vec3 instance. **Parameters** - `arr` (`number[]`): The array to set the vector values from. **Example** ```ts const v = new Vec3([1, 2, 3]); ``` ## Properties ### x ```ts x: number ``` The first component of the vector. ### y ```ts y: number ``` The second component of the vector. ### z ```ts z: number ``` The third component of the vector. ### BACK ```ts static readonly BACK: Vec3 ``` A constant vector set to [0, 0, 1]. ### DOWN ```ts static readonly DOWN: Vec3 ``` A constant vector set to [0, -1, 0]. ### FORWARD ```ts static readonly FORWARD: Vec3 ``` A constant vector set to [0, 0, -1]. ### HALF ```ts static readonly HALF: Vec3 ``` A constant vector set to [0.5, 0.5, 0.5]. ### LEFT ```ts static readonly LEFT: Vec3 ``` A constant vector set to [-1, 0, 0]. ### ONE ```ts static readonly ONE: Vec3 ``` A constant vector set to [1, 1, 1]. ### RIGHT ```ts static readonly RIGHT: Vec3 ``` A constant vector set to [1, 0, 0]. ### UP ```ts static readonly UP: Vec3 ``` A constant vector set to [0, 1, 0]. ### ZERO ```ts static readonly ZERO: Vec3 ``` A constant vector set to [0, 0, 0]. ## Methods ### add ```ts add(rhs: Vec3): Vec3 ``` Adds a 3-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to add to the specified vector. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts add2(lhs: Vec3, rhs: Vec3): Vec3 ``` Adds two 3-dimensional vectors together and returns the result. **Parameters** - `lhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The first vector operand for the addition. - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second vector operand for the addition. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts addScalar(scalar: number): Vec3 ``` Adds a number to each element of a vector. **Parameters** - `scalar` (`number`): The number to add. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to add to the specified vector. - `scalar` (`number`): The number to multiply the added vector with. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts ceil(src?: Vec3): Vec3 ``` Each element is rounded up to the next largest integer. **Parameters** - `src` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to ceil. If not set, the operation is done in place. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const v = new Vec3(1.2, 3.1, 5.9); v.ceil(); // v is now [2, 4, 6] ``` ### clone ```ts clone(): Vec3 ``` Returns an identical copy of the specified 3-dimensional vector. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): A 3-dimensional vector containing the result of the cloning. **Example** ```ts const v = new Vec3(10, 20, 30); const vclone = v.clone(); console.log("The result of the cloning is: " + vclone.toString()); ``` ### copy ```ts copy(rhs: Vec3): Vec3 ``` Copies the contents of a source 3-dimensional vector to a destination 3-dimensional vector. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): A vector to copy to the specified vector. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The first 3-dimensional vector operand of the cross product. - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second 3-dimensional vector operand of the cross product. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts distance(rhs: Vec3): number ``` Returns the distance between the two specified 3-dimensional vectors. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second 3-dimensional vector to test. **Returns** `number`: The distance between the two vectors. **Example** ```ts 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 ```ts distanceSq(rhs: Vec3): number ``` Returns the squared distance between the two specified 3-dimensional vectors. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second 3-dimensional vector to test. **Returns** `number`: The squared distance between the two vectors. **Example** ```ts 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 ```ts div(rhs: Vec3): Vec3 ``` Divides a 3-dimensional vector by another in place. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to divide the specified vector by. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts div2(lhs: Vec3, rhs: Vec3): Vec3 ``` Divides one 3-dimensional vector by another and writes the result to the specified vector. **Parameters** - `lhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The dividend vector (the vector being divided). - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The divisor vector (the vector dividing the dividend). **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts divScalar(scalar: number): Vec3 ``` Divides each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to divide by. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts dot(rhs: Vec3): number ``` Returns the result of a dot product operation performed on the two specified 3-dimensional vectors. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second 3-dimensional vector operand of the dot product. **Returns** `number`: The result of the dot product operation. **Example** ```ts 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 ```ts equals(rhs: Vec3): boolean ``` Reports whether two vectors are equal. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to compare to the specified vector. **Returns** `boolean`: True if the vectors are equal and false otherwise. **Example** ```ts 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 ```ts equalsApprox(rhs: Vec3, epsilon?: number): boolean ``` Reports whether two vectors are equal using an absolute error tolerance. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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** ```ts const a = new Vec3(); const b = new Vec3(); console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); ``` ### floor ```ts floor(src?: Vec3): Vec3 ``` Each element is set to the largest integer less than or equal to its value. **Parameters** - `src` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to floor. If not set, the operation is done in place. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const v = new Vec3(1.2, 3.9, 5.5); v.floor(); // v is now [1, 3, 5] ``` ### fromArray ```ts fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec3 ``` Set the values of the vector from an array. **Parameters** - `arr` (`number[] | ArrayBufferView`): 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`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const v = new Vec3(); v.fromArray([20, 10, 5]); // v is set to [20, 10, 5] ``` ### length ```ts length(): number ``` Returns the magnitude of the specified 3-dimensional vector. **Returns** `number`: The magnitude of the specified 3-dimensional vector. **Example** ```ts const vec = new Vec3(3, 4, 0); const len = vec.length(); // Outputs 5 console.log("The length of the vector is: " + len); ``` ### lengthSq ```ts lengthSq(): number ``` Returns the magnitude squared of the specified 3-dimensional vector. **Returns** `number`: The magnitude squared of the specified 3-dimensional vector. **Example** ```ts const vec = new Vec3(3, 4, 0); const len = vec.lengthSq(); // Outputs 25 console.log("The length squared of the vector is: " + len); ``` ### lerp ```ts lerp(lhs: Vec3, rhs: Vec3, alpha: number): Vec3 ``` Returns the result of a linear interpolation between two specified 3-dimensional vectors. **Parameters** - `lhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector to interpolate from. - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts max(rhs: Vec3): Vec3 ``` Each element is assigned a value from rhs parameter if it is larger. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector used as the source of elements to compare to. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const a = new Vec3(5, 1, 7); const b = new Vec3(2, 8, 3); a.max(b); // a is now [5, 8, 7] ``` ### min ```ts min(rhs: Vec3): Vec3 ``` Each element is assigned a value from rhs parameter if it is smaller. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector used as the source of elements to compare to. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const a = new Vec3(5, 1, 7); const b = new Vec3(2, 8, 3); a.min(b); // a is now [2, 1, 3] ``` ### mul ```ts mul(rhs: Vec3): Vec3 ``` Multiplies a 3-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts mul2(lhs: Vec3, rhs: Vec3): Vec3 ``` Returns the result of multiplying the specified 3-dimensional vectors together. **Parameters** - `lhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector used as the first multiplicand of the operation. - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The 3-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts mulScalar(scalar: number): Vec3 ``` Multiplies each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to multiply by. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to normalize. If not set, the operation is done in place. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts project(rhs: Vec3): Vec3 ``` Projects this 3-dimensional vector onto the specified vector. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector onto which the original vector will be projected on. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts round(src?: Vec3): Vec3 ``` Each element is rounded up or down to the nearest integer. **Parameters** - `src` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): The vector to round. If not set, the operation is done in place. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts const v = new Vec3(1.4, 3.6, 5.5); v.round(); // v is now [1, 4, 6] ``` ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts sub(rhs: Vec3): Vec3 ``` Subtracts a 3-dimensional vector from another in place. **Parameters** - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The vector to subtract from the specified vector. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts sub2(lhs: Vec3, rhs: Vec3): Vec3 ``` Subtracts two 3-dimensional vectors from one another and returns the result. **Parameters** - `lhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The first vector operand for the subtraction. - `rhs` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The second vector operand for the subtraction. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts subScalar(scalar: number): Vec3 ``` Subtracts a number from each element of a vector. **Parameters** - `scalar` (`number`): The number to subtract. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Self for chaining. **Example** ```ts 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 ```ts 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. ```ts 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 ```ts toString(): string ``` Converts the vector to string form. **Returns** `string`: The vector in string form. **Example** ```ts const v = new Vec3(20, 10, 5); // Outputs [20, 10, 5] console.log(v.toString()); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Vec4.md # Vec4 Class · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec4.js#L25 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](https://api.playcanvas.com/engine/classes/Vec4.md#length) and [dot](https://api.playcanvas.com/engine/classes/Vec4.md#dot) return a number. Two-operand forms such as [add2](https://api.playcanvas.com/engine/classes/Vec4.md#add2) and [mul2](https://api.playcanvas.com/engine/classes/Vec4.md#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](https://api.playcanvas.com/engine/classes/Vec4.md#clone) for an independent copy and [copy](https://api.playcanvas.com/engine/classes/Vec4.md#copy) to overwrite one vector with another. The static constants [ZERO](https://api.playcanvas.com/engine/classes/Vec4.md#zero), [HALF](https://api.playcanvas.com/engine/classes/Vec4.md#half) and [ONE](https://api.playcanvas.com/engine/classes/Vec4.md#one) are frozen shared instances: read them freely, but writing to one throws. **Example** ```ts // 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] ``` ## Constructors ### constructor ```ts 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** ```ts const v1 = new Vec4(); // defaults to 0, 0, 0, 0 const v2 = new Vec4(1, 2, 3, 4); ``` ```ts new Vec4(arr: number[]) ``` Creates a new Vec4 instance. **Parameters** - `arr` (`number[]`): The array to set the vector values from. **Example** ```ts const v = new Vec4([1, 2, 3, 4]); ``` ## Properties ### w ```ts w: number ``` The fourth component of the vector. ### x ```ts x: number ``` The first component of the vector. ### y ```ts y: number ``` The second component of the vector. ### z ```ts z: number ``` The third component of the vector. ### HALF ```ts static readonly HALF: Vec4 ``` A constant vector set to [0.5, 0.5, 0.5, 0.5]. ### ONE ```ts static readonly ONE: Vec4 ``` A constant vector set to [1, 1, 1, 1]. ### ZERO ```ts static readonly ZERO: Vec4 ``` A constant vector set to [0, 0, 0, 0]. ## Methods ### add ```ts add(rhs: Vec4): Vec4 ``` Adds a 4-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The vector to add to the specified vector. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts add2(lhs: Vec4, rhs: Vec4): Vec4 ``` Adds two 4-dimensional vectors together and returns the result. **Parameters** - `lhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The first vector operand for the addition. - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The second vector operand for the addition. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts addScalar(scalar: number): Vec4 ``` Adds a number to each element of a vector. **Parameters** - `scalar` (`number`): The number to add. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec4.md)): The vector to add to the specified vector. - `scalar` (`number`): The number to multiply the added vector with. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts ceil(src?: Vec4): Vec4 ``` Each element is rounded up to the next largest integer. **Parameters** - `src` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The vector to ceil. If not set, the operation is done in place. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts const v = new Vec4(1.2, 3.1, 5.9, 7.4); v.ceil(); // v is now [2, 4, 6, 8] ``` ### clone ```ts clone(): Vec4 ``` Returns an identical copy of the specified 4-dimensional vector. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): A 4-dimensional vector containing the result of the cloning. **Example** ```ts const v = new Vec4(10, 20, 30, 40); const vclone = v.clone(); console.log("The result of the cloning is: " + vclone.toString()); ``` ### copy ```ts copy(rhs: Vec4): Vec4 ``` Copies the contents of a source 4-dimensional vector to a destination 4-dimensional vector. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): A vector to copy to the specified vector. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts div(rhs: Vec4): Vec4 ``` Divides a 4-dimensional vector by another in place. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The vector to divide the specified vector by. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts div2(lhs: Vec4, rhs: Vec4): Vec4 ``` Divides one 4-dimensional vector by another and writes the result to the specified vector. **Parameters** - `lhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The dividend vector (the vector being divided). - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The divisor vector (the vector dividing the dividend). **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts divScalar(scalar: number): Vec4 ``` Divides each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to divide by. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts dot(rhs: Vec4): number ``` Returns the result of a dot product operation performed on the two specified 4-dimensional vectors. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The second 4-dimensional vector operand of the dot product. **Returns** `number`: The result of the dot product operation. **Example** ```ts 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 ```ts equals(rhs: Vec4): boolean ``` Reports whether two vectors are equal. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The vector to compare to the specified vector. **Returns** `boolean`: True if the vectors are equal and false otherwise. **Example** ```ts 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 ```ts equalsApprox(rhs: Vec4, epsilon?: number): boolean ``` Reports whether two vectors are equal using an absolute error tolerance. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): 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** ```ts const a = new Vec4(); const b = new Vec4(); console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); ``` ### floor ```ts floor(src?: Vec4): Vec4 ``` Each element is set to the largest integer less than or equal to its value. **Parameters** - `src` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The vector to floor. If not set, the operation is done in place. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts const v = new Vec4(1.2, 3.9, 5.5, 7.8); v.floor(); // v is now [1, 3, 5, 7] ``` ### fromArray ```ts fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec4 ``` Set the values of the vector from an array. **Parameters** - `arr` (`number[] | ArrayBufferView`): 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`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts const v = new Vec4(); v.fromArray([20, 10, 5, 0]); // v is set to [20, 10, 5, 0] ``` ### length ```ts length(): number ``` Returns the magnitude of the specified 4-dimensional vector. **Returns** `number`: The magnitude of the specified 4-dimensional vector. **Example** ```ts const vec = new Vec4(3, 4, 0, 0); const len = vec.length(); // Outputs 5 console.log("The length of the vector is: " + len); ``` ### lengthSq ```ts lengthSq(): number ``` Returns the magnitude squared of the specified 4-dimensional vector. **Returns** `number`: The magnitude squared of the specified 4-dimensional vector. **Example** ```ts 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 ```ts lerp(lhs: Vec4, rhs: Vec4, alpha: number): Vec4 ``` Returns the result of a linear interpolation between two specified 4-dimensional vectors. **Parameters** - `lhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector to interpolate from. - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): 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`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts max(rhs: Vec4): Vec4 ``` Each element is assigned a value from rhs parameter if it is larger. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector used as the source of elements to compare to. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts min(rhs: Vec4): Vec4 ``` Each element is assigned a value from rhs parameter if it is smaller. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector used as the source of elements to compare to. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts mul(rhs: Vec4): Vec4 ``` Multiplies a 4-dimensional vector to another in place. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts mul2(lhs: Vec4, rhs: Vec4): Vec4 ``` Returns the result of multiplying the specified 4-dimensional vectors together. **Parameters** - `lhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector used as the first multiplicand of the operation. - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The 4-dimensional vector used as the second multiplicand of the operation. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts mulScalar(scalar: number): Vec4 ``` Multiplies each element of a vector by a number. **Parameters** - `scalar` (`number`): The number to multiply by. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts 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`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The vector to normalize. If not set, the operation is done in place. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts round(src?: Vec4): Vec4 ``` Each element is rounded up or down to the nearest integer. **Parameters** - `src` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md), optional): The vector to round. If not set, the operation is done in place. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts const v = new Vec4(1.4, 3.6, 5.5, 7.2); v.round(); // v is now [1, 4, 6, 7] ``` ### set ```ts 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`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts sub(rhs: Vec4): Vec4 ``` Subtracts a 4-dimensional vector from another in place. **Parameters** - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The vector to subtract from the specified vector. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts sub2(lhs: Vec4, rhs: Vec4): Vec4 ``` Subtracts two 4-dimensional vectors from one another and returns the result. **Parameters** - `lhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The first vector operand for the subtraction. - `rhs` ([`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md)): The second vector operand for the subtraction. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts subScalar(scalar: number): Vec4 ``` Subtracts a number from each element of a vector. **Parameters** - `scalar` (`number`): The number to subtract. **Returns** [`Vec4`](https://api.playcanvas.com/engine/classes/Vec4.md): Self for chaining. **Example** ```ts 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 ```ts 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. ```ts 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 ```ts toString(): string ``` Converts the vector to string form. **Returns** `string`: The vector in string form. **Example** ```ts const v = new Vec4(20, 10, 5, 0); // Outputs [20, 10, 5, 0] console.log(v.toString()); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.bytesToInt24.md # math.bytesToInt24 Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L89 ```ts 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** ```ts // 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); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.bytesToInt32.md # math.bytesToInt32 Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L113 ```ts 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** ```ts // 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); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.clamp.md # math.clamp Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L34 ```ts 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** ```ts math.clamp(5, 0, 10); // returns 5 math.clamp(-5, 0, 10); // returns 0 math.clamp(15, 0, 10); // returns 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.intToBytes24.md # math.intToBytes24 Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L49 ```ts 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** ```ts // Set bytes to [0x11, 0x22, 0x33] const bytes = math.intToBytes24(0x112233); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.intToBytes32.md # math.intToBytes32 Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L66 ```ts 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** ```ts // Set bytes to [0x11, 0x22, 0x33, 0x44] const bytes = math.intToBytes32(0x11223344); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.lerp.md # math.lerp Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L140 ```ts 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** ```ts math.lerp(0, 10, 0); // returns 0 math.lerp(0, 10, 0.5); // returns 5 math.lerp(0, 10, 1); // returns 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.lerpAngle.md # math.lerpAngle Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L175 ```ts 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** ```ts math.lerpAngle(350, 10, 0.5); // returns 0 (shortest path crosses 360/0 boundary) math.lerpAngle(0, 90, 0.5); // returns 45 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.lerpUnclamped.md # math.lerpUnclamped Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L157 ```ts 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** ```ts math.lerpUnclamped(0, 10, -0.5); // returns -5 math.lerpUnclamped(0, 10, 0.5); // returns 5 math.lerpUnclamped(0, 10, 1.5); // returns 15 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.nearestPowerOfTwo.md # math.nearestPowerOfTwo Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L227 ```ts 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** ```ts math.nearestPowerOfTwo(17); // returns 16 math.nearestPowerOfTwo(24); // returns 32 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.nextPowerOfTwo.md # math.nextPowerOfTwo Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L207 ```ts 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** ```ts math.nextPowerOfTwo(17); // returns 32 math.nextPowerOfTwo(32); // returns 32 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.powerOfTwo.md # math.powerOfTwo Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L194 ```ts 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** ```ts math.powerOfTwo(32); // returns true math.powerOfTwo(17); // returns false ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.random.md # math.random Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L241 ```ts 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** ```ts math.random(0, 10); // returns a random number between 0 and 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.roundUp.md # math.roundUp Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L304 ```ts 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** ```ts math.roundUp(17, 4); // returns 20 math.roundUp(16, 4); // returns 16 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.smootherstep.md # math.smootherstep Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L285 ```ts smootherstep(min: number, max: number, x: number): number ``` An improved version of the [math.smoothstep](https://api.playcanvas.com/engine/functions/math.smoothstep.md) 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** ```ts math.smootherstep(0, 10, 5); // returns 0.5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/math.smoothstep.md # math.smoothstep Function · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L263 ```ts 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** ```ts math.smoothstep(0, 10, 5); // returns 0.5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/math.md # math Namespace · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L7 Math API. ## Members - [DEG_TO_RAD](https://api.playcanvas.com/engine/variables/math.DEG_TO_RAD.md): Conversion factor between degrees and radians. - [RAD_TO_DEG](https://api.playcanvas.com/engine/variables/math.RAD_TO_DEG.md): Conversion factor between radians and degrees. - [bytesToInt24](https://api.playcanvas.com/engine/functions/math.bytesToInt24.md): Convert 3 8 bit Numbers into a single unsigned 24 bit Number. - [bytesToInt32](https://api.playcanvas.com/engine/functions/math.bytesToInt32.md): Convert 4 1-byte Numbers into a single unsigned 32bit Number. - [clamp](https://api.playcanvas.com/engine/functions/math.clamp.md): Clamp a number between min and max inclusive. - [intToBytes24](https://api.playcanvas.com/engine/functions/math.intToBytes24.md): Convert a 24-bit integer into an array of 3 bytes. - [intToBytes32](https://api.playcanvas.com/engine/functions/math.intToBytes32.md): Convert a 32-bit integer into an array of 4 bytes. - [lerp](https://api.playcanvas.com/engine/functions/math.lerp.md): Calculates the linear interpolation of two numbers. - [lerpAngle](https://api.playcanvas.com/engine/functions/math.lerpAngle.md): Calculates the linear interpolation of two angles ensuring that interpolation is correctly performed across the 360... - [lerpUnclamped](https://api.playcanvas.com/engine/functions/math.lerpUnclamped.md): Calculates the unclamped linear interpolation of two numbers. - [nearestPowerOfTwo](https://api.playcanvas.com/engine/functions/math.nearestPowerOfTwo.md): Returns the nearest (smaller or larger) power of 2 for the specified value. - [nextPowerOfTwo](https://api.playcanvas.com/engine/functions/math.nextPowerOfTwo.md): Returns the next power of 2 for the specified value. - [powerOfTwo](https://api.playcanvas.com/engine/functions/math.powerOfTwo.md): Returns true if argument is a power-of-two and false otherwise. - [random](https://api.playcanvas.com/engine/functions/math.random.md): Return a pseudo-random number between min and max. - [roundUp](https://api.playcanvas.com/engine/functions/math.roundUp.md): Rounds a number up to nearest multiple. - [smootherstep](https://api.playcanvas.com/engine/functions/math.smootherstep.md): An improved version of the math.smoothstep function which has zero 1st and 2nd order derivatives at t=0 and t=1. - [smoothstep](https://api.playcanvas.com/engine/functions/math.smoothstep.md): The function interpolates smoothly between two input values based on a third one that should be between the first two. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AmmoPhysicsWorld.md # AmmoPhysicsWorld Class · extends [`PhysicsWorld`](https://api.playcanvas.com/engine/classes/PhysicsWorld.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/ammo/ammo-physics-world.js#L164 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: ```javascript 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](https://api.playcanvas.com/engine/classes/AppOptions.md#physicsworld) is omitted, the engine creates this backend automatically once application libraries have loaded, if the Ammo global is present. ## Constructors ### constructor ```ts new AmmoPhysicsWorld() ``` Create a new AmmoPhysicsWorld instance. The Ammo library must be loaded before the backend is constructed. ## Inherited from [NullPhysicsWorld](https://api.playcanvas.com/engine/classes/NullPhysicsWorld.md) - `nativeWorld: any` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CollisionComponent.md # CollisionComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/component.js#L65 The CollisionComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to act as a collision volume. Use it on its own to define a trigger volume. Or use it in conjunction with a [RigidBodyComponent](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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: ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#collision) property: ```javascript 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: - [Compound Collision](https://playcanvas.github.io/#/physics/compound-collision) - [Falling Shapes](https://playcanvas.github.io/#/physics/falling-shapes) - [Offset Collision](https://playcanvas.github.io/#/physics/offset-collision) ## Accessors ### angularOffset ```ts get angularOffset(): Readonly set angularOffset(arg: Readonly) ``` Gets the rotational offset of the collision shape from the Entity rotation in local space. Use the setter to update the collision shape. ### asset ```ts get asset(): number | Asset | null set asset(arg: number | Asset | null) ``` Gets the asset or asset id for the model of the mesh collision volume. ### axis ```ts 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. ### checkVertexDuplicates ```ts get checkVertexDuplicates(): boolean set checkVertexDuplicates(arg: boolean) ``` Gets whether checking for duplicate vertices should be enabled when creating collision meshes. ### convexHull ```ts get convexHull(): boolean set convexHull(arg: boolean) ``` Gets whether the collision mesh should be treated as a convex hull. ### halfExtents ```ts get halfExtents(): Readonly set halfExtents(arg: Readonly) ``` 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. ### height ```ts get height(): number set height(arg: number) ``` Gets the total height of the capsule, cylinder or cone-shaped collision volume from tip to tip. ### linearOffset ```ts get linearOffset(): Readonly set linearOffset(arg: Readonly) ``` Gets the positional offset of the collision shape from the Entity position along the local axes. Use the setter to update the collision shape. ### model ```ts get model(): Model | null set model(arg: Model | null) ``` Gets the model that is added to the scene graph for the mesh collision volume. ### radius ```ts get radius(): number set radius(arg: number) ``` Gets the radius of the sphere, capsule, cylinder or cone-shaped collision volumes. ### renderAsset ```ts get renderAsset(): number | Asset | null set renderAsset(arg: number | Asset | null) ``` Gets the render asset id of the mesh collision volume. ### type ```ts 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. ## Methods ### getShapePosition ```ts getShapePosition(): Vec3 ``` Returns the world position for the collision shape, taking into account of any offsets. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world position for the collision shape. ### getShapeRotation ```ts getShapeRotation(): Quat ``` Returns the world rotation for the collision shape, taking into account of any offsets. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): The world rotation for the collision. ## Events ### EVENT_COLLISIONEND ```ts static EVENT_COLLISIONEND: string = 'collisionend' ``` Fired when two rigid bodies stop touching. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) that represents the other rigid body involved in the collision. **Example** ```ts entity.collision.on('collisionend', (other) => { console.log(`${entity.name} stopped touching ${other.name}`); }); ``` ### EVENT_COLLISIONSTART ```ts static EVENT_COLLISIONSTART: string = 'collisionstart' ``` Fired when two rigid bodies start touching. The handler is passed the [ContactResult](https://api.playcanvas.com/engine/classes/ContactResult.md) object which contains details of the contact between the two rigid bodies. **Example** ```ts entity.collision.on('collisionstart', (result) => { console.log(`${entity.name} started touching ${result.other.name}`); }); ``` ### EVENT_CONTACT ```ts static EVENT_CONTACT: string = 'contact' ``` Fired when a contact occurs between two rigid bodies. The handler is passed a [ContactResult](https://api.playcanvas.com/engine/classes/ContactResult.md) object which contains details of the contact between the two rigid bodies. **Example** ```ts entity.collision.on('contact', (result) => { console.log(`Contact between ${entity.name} and ${result.other.name}`); }); ``` ### EVENT_TRIGGERENTER ```ts static EVENT_TRIGGERENTER: string = 'triggerenter' ``` Fired when a rigid body enters a trigger volume. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) representing the rigid body that entered this collision volume. **Example** ```ts entity.collision.on('triggerenter', (other) => { console.log(`${other.name} entered trigger volume ${entity.name}`); }); ``` ### EVENT_TRIGGERLEAVE ```ts static EVENT_TRIGGERLEAVE: string = 'triggerleave' ``` Fired when a rigid body exits a trigger volume. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) representing the rigid body that exited this collision volume. **Example** ```ts entity.collision.on('triggerleave', (other) => { console.log(`${other.name} exited trigger volume ${entity.name}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/CollisionComponentSystem.md # CollisionComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/system.js#L600 Manages the [CollisionComponent](https://api.playcanvas.com/engine/classes/CollisionComponent.md)s of an application. Reach it through `app.systems.collision`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ContactPoint.md # ContactPoint Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/contact-point.js#L38 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](https://api.playcanvas.com/engine/classes/ContactResult.md) 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](https://api.playcanvas.com/engine/classes/Vec3.md#clone). **Example** ```ts // 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!"); } }); ``` ## Properties ### impulse ```ts 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 ```ts 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](https://api.playcanvas.com/engine/classes/CollisionComponent.md#linearoffset) and [CollisionComponent#angularOffset](https://api.playcanvas.com/engine/classes/CollisionComponent.md#angularoffset) applied, and ignores the entity's scale. ### localPointOther ```ts 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](https://api.playcanvas.com/engine/classes/ContactPoint.md#localpoint)). ### normal ```ts 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 ```ts point: Vec3 ``` The point on the entity where the contact occurred, in world space. ### pointOther ```ts pointOther: Vec3 ``` The point on the other entity where the contact occurred, in world space. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ContactResult.md # ContactResult Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/contact-result.js#L32 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](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md) and [CollisionComponent](https://api.playcanvas.com/engine/classes/CollisionComponent.md) instances. Unlike [SingleContactResult](https://api.playcanvas.com/engine/classes/SingleContactResult.md) 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: - [CollisionComponent.EVENT_CONTACT](https://api.playcanvas.com/engine/classes/CollisionComponent.md#event_contact) - [CollisionComponent.EVENT_COLLISIONSTART](https://api.playcanvas.com/engine/classes/CollisionComponent.md#event_collisionstart) - [RigidBodyComponent.EVENT_CONTACT](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md#event_contact) - [RigidBodyComponent.EVENT_COLLISIONSTART](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md#event_collisionstart) ## Properties ### contacts ```ts contacts: ContactPoint[] ``` An array of ContactPoints with the other entity. ### other ```ts other: Entity ``` The entity that was involved in the contact with this entity. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/JointComponent.md # JointComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/component.js#L110 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](https://api.playcanvas.com/engine/classes/JointComponent.md#entitya) and [entityB](https://api.playcanvas.com/engine/classes/JointComponent.md#entityb), both of which must have a [RigidBodyComponent](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md). If [entityB](https://api.playcanvas.com/engine/classes/JointComponent.md#entityb) is null, [entityA](https://api.playcanvas.com/engine/classes/JointComponent.md#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](https://api.playcanvas.com/engine/classes/JointComponent.md#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](https://api.playcanvas.com/engine/classes/JointComponent.md#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](https://api.playcanvas.com/engine/classes/JointComponent.md#entityb) (or the world anchor when [entityB](https://api.playcanvas.com/engine/classes/JointComponent.md#entityb) is null) moves along the joint's positive axes relative to [entityA](https://api.playcanvas.com/engine/classes/JointComponent.md#entitya). Angular degrees of freedom measure the opposite body: they are positive when [entityA](https://api.playcanvas.com/engine/classes/JointComponent.md#entitya) rotates counter-clockwise about the joint's axes relative to [entityB](https://api.playcanvas.com/engine/classes/JointComponent.md#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](https://api.playcanvas.com/engine/classes/JointComponent.md#entitya), [enableCollision](https://api.playcanvas.com/engine/classes/JointComponent.md#enablecollision) and [breakImpulse](https://api.playcanvas.com/engine/classes/JointComponent.md#breakimpulse)) apply to all types. To add a JointComponent to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript // 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); ``` ## Accessors ### angularDamping ```ts get angularDamping(): Vec3 set angularDamping(arg: Vec3) ``` ### angularEquilibrium ```ts get angularEquilibrium(): Vec3 set angularEquilibrium(arg: Vec3) ``` ### angularLimitsX ```ts get angularLimitsX(): Vec2 set angularLimitsX(arg: Vec2) ``` ### angularLimitsY ```ts get angularLimitsY(): Vec2 set angularLimitsY(arg: Vec2) ``` ### angularLimitsZ ```ts get angularLimitsZ(): Vec2 set angularLimitsZ(arg: Vec2) ``` ### angularMotionX ```ts get angularMotionX(): "free" | "limited" | "locked" set angularMotionX(arg: "free" | "limited" | "locked") ``` ### angularMotionY ```ts get angularMotionY(): "free" | "limited" | "locked" set angularMotionY(arg: "free" | "limited" | "locked") ``` ### angularMotionZ ```ts get angularMotionZ(): "free" | "limited" | "locked" set angularMotionZ(arg: "free" | "limited" | "locked") ``` ### angularStiffness ```ts get angularStiffness(): Vec3 set angularStiffness(arg: Vec3) ``` ### breakImpulse ```ts get breakImpulse(): number set breakImpulse(impulse: number) ``` ### enableCollision ```ts get enableCollision(): boolean set enableCollision(enableCollision: boolean) ``` ### enableLimits ```ts get enableLimits(): boolean set enableLimits(arg: boolean) ``` ### entityA ```ts get entityA(): Entity | null set entityA(arg: Entity | null) ``` ### entityB ```ts get entityB(): Entity | null set entityB(arg: Entity | null) ``` ### isBroken ```ts get isBroken(): boolean ``` ### limits ```ts get limits(): Vec2 set limits(arg: Vec2) ``` ### linearDamping ```ts get linearDamping(): Vec3 set linearDamping(arg: Vec3) ``` ### linearEquilibrium ```ts get linearEquilibrium(): Vec3 set linearEquilibrium(arg: Vec3) ``` ### linearLimitsX ```ts get linearLimitsX(): Vec2 set linearLimitsX(arg: Vec2) ``` ### linearLimitsY ```ts get linearLimitsY(): Vec2 set linearLimitsY(arg: Vec2) ``` ### linearLimitsZ ```ts get linearLimitsZ(): Vec2 set linearLimitsZ(arg: Vec2) ``` ### linearMotionX ```ts get linearMotionX(): "free" | "limited" | "locked" set linearMotionX(arg: "free" | "limited" | "locked") ``` ### linearMotionY ```ts get linearMotionY(): "free" | "limited" | "locked" set linearMotionY(arg: "free" | "limited" | "locked") ``` ### linearMotionZ ```ts get linearMotionZ(): "free" | "limited" | "locked" set linearMotionZ(arg: "free" | "limited" | "locked") ``` ### linearStiffness ```ts get linearStiffness(): Vec3 set linearStiffness(arg: Vec3) ``` ### maxMotorForce ```ts get maxMotorForce(): number set maxMotorForce(arg: number) ``` ### motorSpeed ```ts get motorSpeed(): number set motorSpeed(arg: number) ``` ### swingLimitY ```ts get swingLimitY(): number set swingLimitY(arg: number) ``` ### swingLimitZ ```ts get swingLimitZ(): number set swingLimitZ(arg: number) ``` ### twistLimit ```ts get twistLimit(): number set twistLimit(arg: number) ``` ### type ```ts get type(): "fixed" | "ball" | "hinge" | "slider" | "6dof" set type(type: "fixed" | "ball" | "hinge" | "slider" | "6dof") ``` ## Methods ### onBeforeRemove ```ts onBeforeRemove(): void ``` ### refreshFrames ```ts refreshFrames(): void ``` Destroys and recreates the underlying constraint, re-capturing the joint frames from the current world transforms of the joint entity, [entityA](https://api.playcanvas.com/engine/classes/JointComponent.md#entitya) and [entityB](https://api.playcanvas.com/engine/classes/JointComponent.md#entityb). Call this after moving the joint entity to re-anchor the joint, or to re-attach a joint that has broken. ## Events ### EVENT_BREAK ```ts static EVENT_BREAK: string = 'break' ``` Fired when the applied impulse on the joint exceeds [breakImpulse](https://api.playcanvas.com/engine/classes/JointComponent.md#breakimpulse) and the constraint breaks. The broken joint no longer constrains its bodies and [isBroken](https://api.playcanvas.com/engine/classes/JointComponent.md#isbroken) becomes true. Call [refreshFrames](https://api.playcanvas.com/engine/classes/JointComponent.md#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** ```ts entity.joint.on('break', () => { console.log('The joint broke'); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/JointComponentSystem.md # JointComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/system.js#L31 Manages the [JointComponent](https://api.playcanvas.com/engine/classes/JointComponent.md)s of an application. Reach it through `app.systems.joint`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Properties ### ComponentType ```ts ComponentType: typeof JointComponent ``` ## Methods ### destroy ```ts destroy(): void ``` ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `app: AppBase` - `id: string` - `schema: any[]` - `store: {}` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/NullPhysicsWorld.md # NullPhysicsWorld Class · extends [`PhysicsWorld`](https://api.playcanvas.com/engine/classes/PhysicsWorld.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/null/null-physics-world.js#L20 A no-op physics backend. The [PhysicsWorld](https://api.playcanvas.com/engine/classes/PhysicsWorld.md) 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: ```javascript 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. ## Inherited from [PhysicsWorld](https://api.playcanvas.com/engine/classes/PhysicsWorld.md) - `new NullPhysicsWorld()` - `nativeWorld: any = null` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/PhysicsWorld.md # PhysicsWorld Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/physics-world.js#L171 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](https://api.playcanvas.com/engine/classes/NullPhysicsWorld.md) uses this to let physics component lifecycle run without a physics engine loaded. Supply a backend to an application with [AppOptions#physicsWorld](https://api.playcanvas.com/engine/classes/AppOptions.md#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. ## Constructors ### constructor ```ts new PhysicsWorld() ``` ## Properties ### nativeWorld ```ts nativeWorld: any = null ``` The backend-native world object - btDiscreteDynamicsWorld when the Ammo backend is active, null otherwise. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RaycastResult.md # RaycastResult Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/raycast-result.js#L17 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](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#raycastfirst) and [RigidBodyComponentSystem#raycastAll](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#raycastall) methods when performing physics raycasts. ## Properties ### entity ```ts entity: Entity ``` The entity that was hit. ### hitFraction ```ts hitFraction: number ``` The normalized distance (between 0 and 1) at which the ray hit occurred from the starting point. ### normal ```ts normal: Vec3 ``` The normal vector of the surface where the ray hit in world space. ### point ```ts point: Vec3 ``` The point at which the ray hit the entity in world space. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RigidBodyComponent.md # RigidBodyComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/component.js#L76 The RigidBodyComponent, when combined with a [CollisionComponent](https://api.playcanvas.com/engine/classes/CollisionComponent.md), 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript // 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: ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#rigidbody) property: ```javascript 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: - [Falling shapes](https://playcanvas.github.io/#/physics/falling-shapes) - [Vehicle physics](https://playcanvas.github.io/#/physics/vehicle) ## Accessors ### angularDamping ```ts get angularDamping(): number set angularDamping(damping: number) ``` Gets the rate at which a body loses angular velocity over time. ### angularFactor ```ts get angularFactor(): Readonly set angularFactor(factor: Readonly) ``` Gets the scaling factor for angular movement of the body in each axis. Use the setter to update the physics body. ### angularVelocity ```ts get angularVelocity(): Readonly set angularVelocity(velocity: Readonly) ``` Gets the rotational speed of the body around each world axis. Use the setter to update the physics body. ### friction ```ts get friction(): number set friction(friction: number) ``` Gets the friction value used when contacts occur between two bodies. ### gravityScale ```ts get gravityScale(): number set gravityScale(scale: number) ``` Gets the scale applied to the world gravity for this body. ### group ```ts get group(): number set group(group: number) ``` Gets the collision group this body belongs to. ### linearDamping ```ts get linearDamping(): number set linearDamping(damping: number) ``` Gets the rate at which a body loses linear velocity over time. ### linearFactor ```ts get linearFactor(): Readonly set linearFactor(factor: Readonly) ``` Gets the scaling factor for linear movement of the body in each axis. Use the setter to update the physics body. ### linearVelocity ```ts get linearVelocity(): Readonly set linearVelocity(velocity: Readonly) ``` Gets the speed of the body in a given direction. Use the setter to update the physics body. ### mask ```ts get mask(): number set mask(mask: number) ``` Gets the collision mask sets which groups this body collides with. ### mass ```ts get mass(): number set mass(mass: number) ``` Gets the mass of the body. ### restitution ```ts get restitution(): number set restitution(restitution: number) ``` Gets the value that controls the amount of energy lost when two rigid bodies collide. ### rollingFriction ```ts get rollingFriction(): number set rollingFriction(friction: number) ``` Gets the torsional friction orthogonal to the contact point. ### type ```ts get type(): "static" | "dynamic" | "kinematic" set type(type: "static" | "dynamic" | "kinematic") ``` Gets the rigid body type determines how the body is simulated. ## Methods ### activate ```ts activate(): void ``` Forcibly activate the rigid body simulation. Only affects rigid bodies of type [BODYTYPE_DYNAMIC](https://api.playcanvas.com/engine/variables/BODYTYPE_DYNAMIC.md). ### applyForce ```ts 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](https://api.playcanvas.com/engine/classes/CollisionComponent.md#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** ```ts // Apply an approximation of gravity at the body's center this.entity.rigidbody.applyForce(0, -10, 0); ``` **Example** ```ts // 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); ``` ```ts 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](https://api.playcanvas.com/engine/classes/CollisionComponent.md#linearoffset). **Parameters** - `force` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector representing the force in world space. - `relativePoint` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Optional vector representing the relative point at which to apply the force in world space. **Returns** `void` **Example** ```ts // 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** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/CollisionComponent.md#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** ```ts // Apply an impulse along the world space positive y-axis at the body's origin entity.rigidbody.applyImpulse(0, 10, 0); ``` **Example** ```ts // 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); ``` ```ts 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](https://api.playcanvas.com/engine/classes/CollisionComponent.md#linearoffset). **Parameters** - `impulse` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector representing the impulse in world space. - `relativePoint` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Optional vector representing the relative point at which to apply the impulse in world space. **Returns** `void` **Example** ```ts // 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** ```ts // 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** ```ts // 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 ```ts 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** ```ts entity.rigidbody.applyTorque(0, 10, 0); ``` ```ts applyTorque(torque: Vec3): void ``` Apply torque (rotational force) to the body. **Parameters** - `torque` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector representing the torque force in world space. **Returns** `void` **Example** ```ts const torque = new Vec3(0, 10, 0); entity.rigidbody.applyTorque(torque); ``` ### applyTorqueImpulse ```ts 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** ```ts entity.rigidbody.applyTorqueImpulse(0, 10, 0); ``` ```ts applyTorqueImpulse(torque: Vec3): void ``` Apply a torque impulse (rotational force applied instantaneously) to the body. **Parameters** - `torque` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector representing the torque impulse in world space. **Returns** `void` **Example** ```ts const torque = new Vec3(0, 10, 0); entity.rigidbody.applyTorqueImpulse(torque); ``` ### isActive ```ts 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 ```ts isKinematic(): boolean ``` Returns true if the rigid body is of type [BODYTYPE_KINEMATIC](https://api.playcanvas.com/engine/variables/BODYTYPE_KINEMATIC.md). **Returns** `boolean`: True if kinematic. ### isStatic ```ts isStatic(): boolean ``` Returns true if the rigid body is of type [BODYTYPE_STATIC](https://api.playcanvas.com/engine/variables/BODYTYPE_STATIC.md). **Returns** `boolean`: True if static. ### isStaticOrKinematic ```ts isStaticOrKinematic(): boolean ``` Returns true if the rigid body is of type [BODYTYPE_STATIC](https://api.playcanvas.com/engine/variables/BODYTYPE_STATIC.md) or [BODYTYPE_KINEMATIC](https://api.playcanvas.com/engine/variables/BODYTYPE_KINEMATIC.md). **Returns** `boolean`: True if static or kinematic. ### teleport ```ts 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** ```ts // Teleport the entity to the origin entity.rigidbody.teleport(0, 0, 0); ``` **Example** ```ts // Teleport the entity to world space coordinate [1, 2, 3] and reset orientation entity.rigidbody.teleport(1, 2, 3, 0, 0, 0); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding the new world space position. - `angles` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): Vector holding the new world space Euler angles in degrees. **Returns** `void` **Example** ```ts // Teleport the entity to the origin entity.rigidbody.teleport(Vec3.ZERO); ``` **Example** ```ts // 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); ``` ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Vector holding the new world space position. - `rotation` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md), optional): Quaternion holding the new world space rotation. **Returns** `void` **Example** ```ts // Teleport the entity to the origin entity.rigidbody.teleport(Vec3.ZERO); ``` **Example** ```ts // 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); ``` ## Events ### EVENT_COLLISIONEND ```ts static EVENT_COLLISIONEND: string = 'collisionend' ``` Fired when two rigid bodies stop touching. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) that represents the other rigid body involved in the collision. **Example** ```ts entity.rigidbody.on('collisionend', (other) => { console.log(`${entity.name} stopped touching ${other.name}`); }); ``` ### EVENT_COLLISIONSTART ```ts static EVENT_COLLISIONSTART: string = 'collisionstart' ``` Fired when two rigid bodies start touching. The handler is passed a [ContactResult](https://api.playcanvas.com/engine/classes/ContactResult.md) object containing details of the contact between the two rigid bodies. **Example** ```ts entity.rigidbody.on('collisionstart', (result) => { console.log(`Collision started between ${entity.name} and ${result.other.name}`); }); ``` ### EVENT_CONTACT ```ts static EVENT_CONTACT: string = 'contact' ``` Fired when a contact occurs between two rigid bodies. The handler is passed a [ContactResult](https://api.playcanvas.com/engine/classes/ContactResult.md) object containing details of the contact between the two rigid bodies. **Example** ```ts entity.rigidbody.on('contact', (result) => { console.log(`Contact between ${entity.name} and ${result.other.name}`); }); ``` ### EVENT_TRIGGERENTER ```ts static EVENT_TRIGGERENTER: string = 'triggerenter' ``` Fired when a rigid body enters a trigger volume. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) representing the trigger volume that this rigid body entered. **Example** ```ts entity.rigidbody.on('triggerenter', (trigger) => { console.log(`Entity ${entity.name} entered trigger volume ${trigger.name}`); }); ``` ### EVENT_TRIGGERLEAVE ```ts static EVENT_TRIGGERLEAVE: string = 'triggerleave' ``` Fired when a rigid body exits a trigger volume. The handler is passed an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) representing the trigger volume that this rigid body exited. **Example** ```ts entity.rigidbody.on('triggerleave', (trigger) => { console.log(`Entity ${entity.name} exited trigger volume ${trigger.name}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md # RigidBodyComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/system.js#L74 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](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#gravity), performs raycasts and reports collisions. The system is only functional once a physics backend is installed: either by supplying [AppOptions#physicsWorld](https://api.playcanvas.com/engine/classes/AppOptions.md#physicsworld) when creating the application, or automatically when the application has loaded the Ammo.js [WasmModule](https://api.playcanvas.com/engine/classes/WasmModule.md). Use a recent Ammo.js build: mesh colliders only follow entity scale with a build that exposes `btScaledBvhTriangleMeshShape`. Set [RigidBodyComponentSystem#timeScale](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#timescale) to slow the simulation down, speed it up or pause it, for example while a pause menu is open, and call [RigidBodyComponentSystem#step](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#step) to advance it manually. ## Properties ### gravity ```ts 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** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/AppBase.md#timescale). The simulation can still be advanced manually with [RigidBodyComponentSystem#step](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#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](https://api.playcanvas.com/engine/classes/RigidBodyComponent.md#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** ```ts // Freeze the game world while the pause menu is open app.systems.rigidbody.timeScale = 0; ``` **Example** ```ts // Run physics at quarter speed for a slow motion effect app.systems.rigidbody.timeScale = 0.25; ``` ## Accessors ### physicsWorld ```ts get physicsWorld(): PhysicsWorld | null ``` Gets the installed physics backend, or null when no backend is installed. Supply a backend via [AppOptions#physicsWorld](https://api.playcanvas.com/engine/classes/AppOptions.md#physicsworld), or load the Ammo.js library to have one installed automatically. ## Methods ### raycastAll ```ts raycastAll(start: Vec3, end: Vec3, options?: object): RaycastResult[] ``` Raycast the world and return all entities the ray hits. It returns an array of [RaycastResult](https://api.playcanvas.com/engine/classes/RaycastResult.md), 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space point where the ray starts. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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](https://api.playcanvas.com/engine/classes/Tags.md#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`](https://api.playcanvas.com/engine/classes/RaycastResult.md)`[]`: An array of raycast hit results (0 length if there were no hits or no physics backend is installed). **Example** ```ts // 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** ```ts // 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** ```ts // 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** ```ts // 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** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/RaycastResult.md), otherwise returns null. **Parameters** - `start` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space point where the ray starts. - `end` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): 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](https://api.playcanvas.com/engine/classes/Tags.md#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`](https://api.playcanvas.com/engine/classes/RaycastResult.md) `| null`: The result of the raycasting, or null if there was no hit or no physics backend is installed. ### step ```ts 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](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md#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** ```ts // 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); } }); ``` ## Events ### EVENT_CONTACT ```ts static EVENT_CONTACT: string = 'contact' ``` Fired when a contact occurs between two rigid bodies. The handler is passed a [SingleContactResult](https://api.playcanvas.com/engine/classes/SingleContactResult.md) object containing details of the contact between the two bodies. **Example** ```ts app.systems.rigidbody.on('contact', (result) => { console.log(`Contact between ${result.a.name} and ${result.b.name}`); }); ``` ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SingleContactResult.md # SingleContactResult Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/single-contact-result.js#L28 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](https://api.playcanvas.com/engine/classes/RigidBodyComponentSystem.md). Individual rigid body components receive instances of [ContactResult](https://api.playcanvas.com/engine/classes/ContactResult.md) 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** ```ts app.systems.rigidbody.on('contact', (result) => { console.log(`Contact between ${result.a.name} and ${result.b.name}`); }); ``` ## Properties ### a ```ts a: Entity ``` The first entity involved in the contact. ### b ```ts b: Entity ``` The second entity involved in the contact. ### impulse ```ts impulse: number ``` The total accumulated impulse applied by the constraint solver during the last sub-step. Describes how hard two bodies collided. ### localPointA ```ts localPointA: Vec3 ``` The point on Entity A where the contact occurred, in the local space of A's rigid body (see [ContactPoint#localPoint](https://api.playcanvas.com/engine/classes/ContactPoint.md#localpoint)). ### localPointB ```ts localPointB: Vec3 ``` The point on Entity B where the contact occurred, in the local space of B's rigid body. ### normal ```ts normal: Vec3 ``` The normal vector of the contact on Entity B, in world space. ### pointA ```ts pointA: Vec3 ``` The point on Entity A where the contact occurred, in world space. ### pointB ```ts pointB: Vec3 ``` The point on Entity B where the contact occurred, in world space. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Trigger.md # Trigger Class · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/trigger.js#L19 Creates a trigger object used to create internal physics objects that interact with rigid bodies and trigger collision events with no collision response. ## Constructors ### constructor ```ts new Trigger(app: AppBase, component: CollisionComponent) ``` Create a new Trigger instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The running [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). - `component` ([`CollisionComponent`](https://api.playcanvas.com/engine/classes/CollisionComponent.md)): The component for which the trigger will be created. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Script.md # Script Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script.js#L54 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** ```javascript 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](https://developer.playcanvas.com/user-manual/scripting/). 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'`. ## Constructors ### constructor ```ts new Script(args: object) ``` Create a new Script instance. **Parameters** - `args` (`object`): The input arguments object. - `args.app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The AppBase that is running the script. - `args.entity` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): The Entity that the script is attached to. ## Properties ### app ```ts app: AppBase ``` The [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) that the instance of this script belongs to. ### entity ```ts entity: Entity ``` The [Entity](https://api.playcanvas.com/engine/classes/Entity.md) that the instance of this script belongs to. ## Accessors ### enabled ```ts 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](https://api.playcanvas.com/engine/classes/Entity.md) (and all ancestors) and [ScriptComponent](https://api.playcanvas.com/engine/classes/ScriptComponent.md) are also enabled; otherwise false. ### scriptName ```ts static get scriptName(): string | null static set scriptName(value: string | null) ``` Gets the unique name of the script. ## Methods ### initScript ```ts protected initScript(args: ScriptInitializationArgs): void ``` **Parameters** - `args` ([`ScriptInitializationArgs`](https://api.playcanvas.com/engine/interfaces/ScriptInitializationArgs.md)): The input arguments object. ## Events ### EVENT_ATTR ```ts static EVENT_ATTR: string = 'attr' ``` Fired when script attributes have changed. This event is available in two forms. They are as follows: 1. `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. 2. `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** ```ts 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** ```ts export class PlayerController extends Script { static scriptName = 'playerController'; initialize() { this.on('attr:speed', (newValue, oldValue) => { console.log(`Attribute 'speed' changed from '${oldValue}' to '${newValue}'`); }); } }; ``` ### EVENT_DESTROY ```ts static EVENT_DESTROY: string = 'destroy' ``` Fired when a script instance is destroyed and removed from component. **Example** ```ts 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 }); } }; ``` ### EVENT_DISABLE ```ts static EVENT_DISABLE: string = 'disable' ``` Fired when a script instance becomes disabled. **Example** ```ts export class PlayerController extends Script { static scriptName = 'playerController'; initialize() { this.on('disable', () => { // Script Instance is now disabled }); } }; ``` ### EVENT_ENABLE ```ts static EVENT_ENABLE: string = 'enable' ``` Fired when a script instance becomes enabled. **Example** ```ts export class PlayerController extends Script { static scriptName = 'playerController'; initialize() { this.on('enable', () => { // Script Instance is now enabled }); } }; ``` ### EVENT_ERROR ```ts 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** ```ts export class PlayerController extends Script { static scriptName = 'playerController'; initialize() { this.on('error', (err, method) => { // caught an exception console.log(err.stack); }); } }; ``` ### EVENT_STATE ```ts 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** ```ts export class PlayerController extends Script { static scriptName = 'playerController'; initialize() { this.on('state', (enabled) => { console.log(`Script Instance is now ${enabled ? 'enabled' : 'disabled'}`); }); } }; ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptAttributes.md # ScriptAttributes Class · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-attributes.js#L215 Container of Script Attribute definitions. Implements an interface to add/remove attributes and store their definition for a [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md). Note: An instance of ScriptAttributes is created automatically by each [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md). ## Constructors ### constructor ```ts new ScriptAttributes(scriptType: typeof ScriptType) ``` Create a new ScriptAttributes instance. **Parameters** - `scriptType` (`typeof` [`ScriptType`](https://api.playcanvas.com/engine/classes/ScriptType.md)): Script Type that attributes relate to. ## Methods ### add ```ts 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: - "asset" - "boolean" - "curve" - "entity" - "json" - "number" - "rgb" - "rgba" - "string" - "vec2" - "vec3" - "vec4" **Example** ```ts PlayerController.attributes.add('fullName', { type: 'string' }); ``` **Example** ```ts PlayerController.attributes.add('speed', { type: 'number', title: 'Speed', placeholder: 'km/h', default: 22.2 }); ``` **Example** ```ts PlayerController.attributes.add('resolution', { type: 'number', default: 32, enum: [ { '32x32': 32 }, { '64x64': 64 }, { '128x128': 128 } ] }); ``` **Example** ```ts 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 ```ts 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** ```ts // changing default value for an attribute 'fullName' var attr = PlayerController.attributes.get('fullName'); if (attr) attr.default = 'Unknown'; ``` ### has ```ts has(name: string): boolean ``` Detect if Attribute is added. **Parameters** - `name` (`string`): Name of an attribute. **Returns** `boolean`: True if Attribute is defined. **Example** ```ts if (PlayerController.attributes.has('fullName')) { // attribute fullName is defined } ``` ### remove ```ts remove(name: string): boolean ``` Remove Attribute. **Parameters** - `name` (`string`): Name of an attribute. **Returns** `boolean`: True if removed or false if not defined. **Example** ```ts PlayerController.attributes.remove('fullName'); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptComponent.md # ScriptComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/script/component.js#L47 The ScriptComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript const entity = new Entity(); entity.addComponent('script'); ``` Once the ScriptComponent is added to the entity, you can access it via the [Entity#script](https://api.playcanvas.com/engine/classes/Entity.md#script) property: ```javascript // 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](https://developer.playcanvas.com/user-manual/scripting/) of the User Manual. ## Accessors ### scripts ```ts 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. ## Methods ### create ```ts create(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`](https://api.playcanvas.com/engine/classes/ScriptComponent.md#createt) `| 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** ```ts const controller = entity.script.create(PlayerController, { properties: { speed: 4 } }); // PlayerController | null ``` ```ts 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](https://api.playcanvas.com/engine/classes/ScriptRegistry.md). **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`](https://api.playcanvas.com/engine/classes/Script.md) `| 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](https://api.playcanvas.com/engine/classes/ScriptRegistry.md). **Example** ```ts entity.script.create('playerController', { attributes: { speed: 4 } }); ``` ### destroy ```ts destroy(nameOrType: string | typeof Script): boolean ``` Destroy the script instance that is attached to an entity. **Parameters** - `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md). **Returns** `boolean`: If it was successfully destroyed. **Example** ```ts entity.script.destroy('playerController'); ``` ### get ```ts get(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`](https://api.playcanvas.com/engine/classes/ScriptComponent.md#gett) `| null`: If a script of the class is attached, the instance is returned. Otherwise null is returned. **Example** ```ts const controller = entity.script.get(PlayerController); // PlayerController | null ``` ```ts get(name: string): Script | null ``` Get a script instance (if attached) by its name. **Parameters** - `name` (`string`): The name of the script. **Returns** [`Script`](https://api.playcanvas.com/engine/classes/Script.md) `| 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](https://api.playcanvas.com/engine/classes/ScriptRegistry.md). **Example** ```ts const controller = entity.script.get('playerController'); ``` ### has ```ts has(nameOrType: string | typeof Script): boolean ``` Detect if script is attached to an entity. **Parameters** - `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md). **Returns** `boolean`: If script is attached to an entity. **Example** ```ts if (entity.script.has('playerController')) { // entity has script } ``` ### move ```ts 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`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md). - `ind` (`number`): New position index. **Returns** `boolean`: If it was successfully moved. **Example** ```ts entity.script.move('playerController', 0); ``` ## Events ### EVENT_CREATE ```ts static EVENT_CREATE: string = 'create' ``` Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is created and attached to the script component. This event is available in two forms. They are as follows: 1. `create` - Fired when a script instance is created. The name of the script type and the script type instance are passed as arguments. 2. `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** ```ts entity.script.on('create', (name, scriptInstance) => { console.log(`Instance of script '${name}' created`); }); ``` **Example** ```ts entity.script.on('create:player', (scriptInstance) => { console.log(`Instance of script 'player' created`); }); ``` ### EVENT_DESTROY ```ts static EVENT_DESTROY: string = 'destroy' ``` Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is destroyed and removed from the script component. This event is available in two forms. They are as follows: 1. `destroy` - Fired when a script instance is destroyed. The name of the script type and the script type instance are passed as arguments. 2. `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** ```ts entity.script.on('destroy', (name, scriptInstance) => { console.log(`Instance of script '${name}' destroyed`); }); ``` **Example** ```ts entity.script.on('destroy:player', (scriptInstance) => { console.log(`Instance of script 'player' destroyed`); }); ``` ### EVENT_DISABLE ```ts 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** ```ts entity.script.on('disable', () => { console.log(`Script component of entity '${entity.name}' has been disabled`); }); ``` ### EVENT_ENABLE ```ts 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** ```ts entity.script.on('enable', () => { console.log(`Script component of entity '${entity.name}' has been enabled`); }); ``` ### EVENT_ERROR ```ts static EVENT_ERROR: string = 'error' ``` Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance had an exception. The handler is passed the script instance, the exception and the method name that the exception originated from. **Example** ```ts entity.script.on('error', (scriptInstance, exception, methodName) => { console.log(`Script error: ${exception} in method '${methodName}'`); }); ``` ### EVENT_MOVE ```ts static EVENT_MOVE: string = 'move' ``` Fired when the index of a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is changed in the script component. This event is available in two forms. They are as follows: 1. `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. 2. `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** ```ts entity.script.on('move', (name, scriptInstance, newIndex, oldIndex) => { console.log(`Script '${name}' moved from index '${oldIndex}' to '${newIndex}'`); }); ``` **Example** ```ts entity.script.on('move:player', (scriptInstance, newIndex, oldIndex) => { console.log(`Script 'player' moved from index '${oldIndex}' to '${newIndex}'`); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when the script component has been removed from its entity. **Example** ```ts entity.script.on('remove', () => { console.log(`Script component removed from entity '${entity.name}'`); }); ``` ### EVENT_STATE ```ts 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** ```ts entity.script.on('state', (enabled) => { console.log(`Script component of entity '${entity.name}' changed state to '${enabled}'`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptComponentSystem.md # ScriptComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/script/system.js#L43 Manages the [ScriptComponent](https://api.playcanvas.com/engine/classes/ScriptComponent.md)s of an application. Reach it through `app.systems.script`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptRegistry.md # ScriptRegistry Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-registry.js#L19 Container for all [Script](https://api.playcanvas.com/engine/classes/Script.md) classes that are available to this application. Note that PlayCanvas scripts can access the Script Registry from inside the application with [AppBase#scripts](https://api.playcanvas.com/engine/classes/AppBase.md#scripts). ## Constructors ### constructor ```ts new ScriptRegistry(app: AppBase) ``` Create a new ScriptRegistry instance. **Parameters** - `app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): Application to attach registry to. ## Methods ### add ```ts 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](https://api.playcanvas.com/engine/classes/Script.md) classes), or assigned by [createScript](https://api.playcanvas.com/engine/functions/createScript.md) / [registerScript](https://api.playcanvas.com/engine/functions/registerScript.md). Note: when [createScript](https://api.playcanvas.com/engine/functions/createScript.md) or [registerScript](https://api.playcanvas.com/engine/functions/registerScript.md) is called, the script is added to the registry automatically, so calling this method directly is only required when registering a [Script](https://api.playcanvas.com/engine/classes/Script.md) 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`](https://api.playcanvas.com/engine/classes/Script.md)): 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** ```ts var PlayerController = createScript('playerController'); // playerController Script Type will be added to ScriptRegistry automatically console.log(app.scripts.has('playerController')); // outputs true ``` **Example** ```ts // 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 ```ts addSchema(id: string, schema: AttributeSchema): void ``` Registers a schema against a script instance. **Parameters** - `id` (`string`): The key to use to store the schema - `schema` ([`AttributeSchema`](https://api.playcanvas.com/engine/interfaces/AttributeSchema.md)): An schema definition for the script ### get ```ts get(name: string): typeof Script | null ``` Get a [Script](https://api.playcanvas.com/engine/classes/Script.md) class by name. **Parameters** - `name` (`string`): Name of the [Script](https://api.playcanvas.com/engine/classes/Script.md). **Returns** `typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md) `| null`: The script class if it exists in the registry or null otherwise. **Example** ```ts var PlayerController = app.scripts.get('playerController'); ``` ### getSchema ```ts getSchema(id: string): AttributeSchema | undefined ``` Returns a schema for a given script name. **Parameters** - `id` (`string`): The key to store the schema under **Returns** [`AttributeSchema`](https://api.playcanvas.com/engine/interfaces/AttributeSchema.md) `| undefined`: - The schema stored under the key ### has ```ts has(nameOrType: string | typeof Script): boolean ``` Check if a [Script](https://api.playcanvas.com/engine/classes/Script.md) class with the specified name is in the registry. **Parameters** - `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md). **Returns** `boolean`: True if the [Script](https://api.playcanvas.com/engine/classes/Script.md) class is in the registry. **Example** ```ts if (app.scripts.has('playerController')) { // playerController is in ScriptRegistry } ``` ### list ```ts list(): typeof Script[] ``` Get list of all [Script](https://api.playcanvas.com/engine/classes/Script.md) classes from registry. **Returns** `typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)`[]`: list of all [Script](https://api.playcanvas.com/engine/classes/Script.md) classes in registry. **Example** ```ts // logs array of all Script Type names available in registry console.log(app.scripts.list().map(function (o) { return o.name; })); ``` ### remove ```ts remove(nameOrType: string | typeof Script): boolean ``` Remove a [Script](https://api.playcanvas.com/engine/classes/Script.md) class from the registry. **Parameters** - `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md). **Returns** `boolean`: True if removed or False if already not in registry. **Example** ```ts app.scripts.remove('playerController'); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScriptType.md # ScriptType Class · extends [`Script`](https://api.playcanvas.com/engine/classes/Script.md) · category: Script · deprecated Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-type.js#L16 This is the legacy format for creating a PlayCanvas script returned when calling `createScript()`. Do not inherit from this class directly. **Deprecated**: Use [Script](https://api.playcanvas.com/engine/classes/Script.md) instead. ## Constructors ### constructor ```ts new ScriptType(args: object) ``` Create a new ScriptType instance. **Parameters** - `args` (`object`): The input arguments object. - `args.app` ([`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.md)): The AppBase that is running the script. - `args.entity` ([`Entity`](https://api.playcanvas.com/engine/classes/Entity.md)): The Entity that the script is attached to. ## Accessors ### attributes ```ts static get attributes(): ScriptAttributes ``` The interface to define attributes for Script Types. Refer to [ScriptAttributes](https://api.playcanvas.com/engine/classes/ScriptAttributes.md). **Example** ```ts var PlayerController = createScript('playerController'); PlayerController.attributes.add('speed', { type: 'number', title: 'Speed', placeholder: 'km/h', default: 22.2 }); ``` ## Methods ### initScript ```ts protected initScript(args: any): void ``` **Parameters** - `args` (`any`): initialization arguments ### initScriptType ```ts protected initScriptType(args: any): void ``` Expose initScript as initScriptType for backwards compatibility **Parameters** - `args` (`any`): Initialization arguments ### extend ```ts static 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** ```ts var PlayerController = createScript('playerController'); PlayerController.extend({ initialize: function () { // called once on initialize }, update: function (dt) { // called each tick } }); ``` ## Inherited from [Script](https://api.playcanvas.com/engine/classes/Script.md) - `app: AppBase` - `entity: Entity` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `static 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'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/createScript.md # createScript Function · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-create.js#L48 ```ts createScript(name: string, app?: AppBase): typeof ScriptType | null ``` Create and register a new [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md). It returns new class type (constructor function), which is auto-registered to [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md) 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`](https://api.playcanvas.com/engine/classes/AppBase.md), optional): Optional application handler, to choose which [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md) to add a script to. By default it will use `Application.getApplication()` to get current [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). **Returns** `typeof` [`ScriptType`](https://api.playcanvas.com/engine/classes/ScriptType.md) `| null`: A class type (constructor function) that inherits [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md), which the developer is meant to further extend by adding attributes and prototype methods. Returns null if there was an error. **Example** ```ts 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); }; ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/registerScript.md # registerScript Function · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-create.js#L113 ```ts registerScript(script: typeof ScriptType, name?: string, app?: AppBase): void ``` Register an existing class type as a Script Type with [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md). Useful when defining an ES6 script class that extends [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md) (see example). **Parameters** - `script` (`typeof` [`ScriptType`](https://api.playcanvas.com/engine/classes/ScriptType.md)): The existing class type (constructor function) to be registered as a Script Type. Class must extend [ScriptType](https://api.playcanvas.com/engine/classes/ScriptType.md) (see example). Please note: A class created using [createScript](https://api.playcanvas.com/engine/functions/createScript.md) is auto-registered, and should therefore not be passed into [registerScript](https://api.playcanvas.com/engine/functions/registerScript.md) (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`](https://api.playcanvas.com/engine/classes/AppBase.md), optional): Optional application handler, to choose which [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md) to register the script type with. By default it will use `Application.getApplication()` to get the current [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). **Example** ```ts // 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'}); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/script.createLoadingScreen.md # script.createLoadingScreen Function · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L47 ```ts createLoadingScreen(callback: CreateScreenCallback): void ``` Handles the creation of the loading screen of the application. A script can subscribe to the events of a [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md) 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`](https://api.playcanvas.com/engine/types/CreateScreenCallback.md)): A function which can set up and tear down a customized loading screen. **Example** ```ts script.createLoadingScreen((app) => { const showSplashScreen = () => {}; const hideSplashScreen = () => {}; const showProgress = (progress) => {}; app.on("preload:start", showSplashScreen); app.on("preload:progress", showProgress); app.on("start", hideSplashScreen); }); ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/script.md # script Namespace · category: Script Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L25 The script namespace holds the createLoadingScreen function that is used to override the default PlayCanvas loading screen. ## Members - [createLoadingScreen](https://api.playcanvas.com/engine/functions/script.createLoadingScreen.md): Handles the creation of the loading screen of the application. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AudioListenerComponent.md # AudioListenerComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/audio-listener/component.js#L32 The AudioListenerComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to represent the point from where positional [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md)s 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript const entity = new Entity(); entity.addComponent('audiolistener'); ``` Once the AudioListenerComponent is added to the entity, you can access it via the [Entity#audiolistener](https://api.playcanvas.com/engine/classes/Entity.md#audiolistener) property: ```javascript entity.audiolistener.enabled = false; // Disable the audio listener console.log(entity.audiolistener.enabled); // Get the enabled state and print it ``` Relevant Engine API examples: - [Positional Sound](https://playcanvas.github.io/#/sound/positional) ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/AudioListenerComponentSystem.md # AudioListenerComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/audio-listener/system.js#L16 Manages the [AudioListenerComponent](https://api.playcanvas.com/engine/classes/AudioListenerComponent.md)s of an application. Reach it through `app.systems.audiolistener`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Sound.md # Sound Class · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/sound.js#L12 Represents the raw audio data of a playable sound. A Sound is the resource of an audio [Asset](https://api.playcanvas.com/engine/classes/Asset.md). An audio asset can be assigned to a [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) owned by a [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md). The [buffer](https://api.playcanvas.com/engine/classes/Sound.md#buffer) is the decoded Web Audio `AudioBuffer`, so [duration](https://api.playcanvas.com/engine/classes/Sound.md#duration) is known as soon as the asset has loaded. Playing a sound creates one [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) per playback, normally through a slot rather than by constructing the instance directly. ## Constructors ### constructor ```ts new Sound(buffer: AudioBuffer) ``` Create a new Sound instance. **Parameters** - `buffer` (`AudioBuffer`): The decoded audio data. ## Properties ### buffer ```ts buffer: AudioBuffer ``` Contains the decoded audio data. ## Accessors ### duration ```ts get duration(): number ``` Gets the duration of the sound. If the sound is not loaded it returns 0. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundComponent.md # SoundComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/component.js#L56 The SoundComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to play audio. The SoundComponent can manage multiple [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md)s, 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](https://api.playcanvas.com/engine/classes/AudioListenerComponent.md) 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](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#sound) property: ```javascript 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: ```javascript entity.sound.addSlot('beep', { asset: asset }); ``` Relevant Engine API examples: - [Positional Sound](https://playcanvas.github.io/#/sound/positional) ## Accessors ### distanceModel ```ts 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. ### maxDistance ```ts get maxDistance(): number set maxDistance(value: number) ``` Gets the maximum distance from the listener at which audio falloff stops. ### pitch ```ts get pitch(): number set pitch(value: number) ``` Gets the pitch modifier to play the audio with. ### positional ```ts get positional(): boolean set positional(newValue: boolean) ``` Gets whether the component plays positional sound. ### refDistance ```ts get refDistance(): number set refDistance(value: number) ``` Gets the reference distance for reducing volume as the sound source moves further from the listener. ### rollOffFactor ```ts get rollOffFactor(): number set rollOffFactor(value: number) ``` Gets the factor used in the falloff equation. ### slots ```ts get slots(): Readonly> set slots(newValue: Readonly>) ``` Gets a dictionary that contains the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md)s managed by this SoundComponent. Use addSlot and removeSlot to change slots. ### volume ```ts get volume(): number set volume(value: number) ``` Gets the volume modifier to play the audio with. ## Methods ### addSlot ```ts addSlot(name: string, options?: object): SoundSlot | null ``` Creates a new [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) 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`](https://api.playcanvas.com/engine/classes/SoundSlot.md) `| null`: The new slot or null if the slot already exists. **Example** ```ts // 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 ```ts 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](https://api.playcanvas.com/engine/classes/SoundSlot.md) to look for. **Returns** `boolean`: True if the slot with the specified name exists and its asset is loaded. ### isPaused ```ts isPaused(name: string): boolean ``` Returns true if the slot with the specified name is currently paused. **Parameters** - `name` (`string`): The name of the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) to look for. **Returns** `boolean`: True if the slot with the specified name exists and is currently paused. ### isPlaying ```ts isPlaying(name: string): boolean ``` Returns true if the slot with the specified name is currently playing. **Parameters** - `name` (`string`): The name of the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) to look for. **Returns** `boolean`: True if the slot with the specified name exists and is currently playing. ### isStopped ```ts isStopped(name: string): boolean ``` Returns true if the slot with the specified name is currently stopped. **Parameters** - `name` (`string`): The name of the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) to look for. **Returns** `boolean`: True if the slot with the specified name exists and is currently stopped. ### pause ```ts 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](https://api.playcanvas.com/engine/classes/SoundComponent.md#resume). **Parameters** - `name` (`string`, optional): The name of the slot to pause. Leave undefined to pause everything. **Example** ```ts // pause all sounds this.entity.sound.pause(); // pause a specific sound this.entity.sound.pause('beep'); ``` ### play ```ts 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](https://api.playcanvas.com/engine/classes/SoundSlot.md) to play. **Returns** [`SoundInstance`](https://api.playcanvas.com/engine/classes/SoundInstance.md) `| 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** ```ts // 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 ```ts removeSlot(name: string): void ``` Removes the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) with the specified name. **Parameters** - `name` (`string`): The name of the slot. **Example** ```ts // remove a slot called 'beep' this.entity.sound.removeSlot('beep'); ``` ### resume ```ts 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** ```ts // resume all sounds this.entity.sound.resume(); // resume a specific sound this.entity.sound.resume('beep'); ``` ### slot ```ts slot(name: string): SoundSlot | undefined ``` Returns the slot with the specified name. **Parameters** - `name` (`string`): The name of the slot. **Returns** [`SoundSlot`](https://api.playcanvas.com/engine/classes/SoundSlot.md) `| undefined`: The slot. **Example** ```ts // get a slot and set its volume this.entity.sound.slot('beep').volume = 0.5; ``` ### stop ```ts 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** ```ts // stop all sounds this.entity.sound.stop(); // stop a specific sound this.entity.sound.stop('beep'); ``` ## Events ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when a sound instance stops playing because it reached its end. The handler is passed the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) and the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that ended. **Example** ```ts entity.sound.on('end', (slot, instance) => { console.log(`Sound ${slot.name} ended`); }); ``` ### EVENT_PAUSE ```ts static EVENT_PAUSE: string = 'pause' ``` Fired when a sound instance is paused. The handler is passed the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) and the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that was paused. **Example** ```ts entity.sound.on('pause', (slot, instance) => { console.log(`Sound ${slot.name} paused`); }); ``` ### EVENT_PLAY ```ts static EVENT_PLAY: string = 'play' ``` Fired when a sound instance starts playing. The handler is passed the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) and the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that started playing. **Example** ```ts entity.sound.on('play', (slot, instance) => { console.log(`Sound ${slot.name} started playing`); }); ``` ### EVENT_RESUME ```ts static EVENT_RESUME: string = 'resume' ``` Fired when a sound instance is resumed. The handler is passed the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) and the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that was resumed. **Example** ```ts entity.sound.on('resume', (slot, instance) => { console.log(`Sound ${slot.name} resumed`); }); ``` ### EVENT_STOP ```ts static EVENT_STOP: string = 'stop' ``` Fired when a sound instance is stopped. The handler is passed the [SoundSlot](https://api.playcanvas.com/engine/classes/SoundSlot.md) and the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that was stopped. **Example** ```ts entity.sound.on('stop', (slot, instance) => { console.log(`Sound ${slot.name} stopped`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundComponentSystem.md # SoundComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/system.js#L42 Manages the [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md)s of an application. Reach it through `app.systems.sound`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Properties ### manager ```ts manager: SoundManager ``` Gets / sets the sound manager. ## Accessors ### context ```ts get context(): AudioContext | null ``` Gets the AudioContext currently used by the sound manager. ### volume ```ts get volume(): number set volume(volume: number) ``` Gets the volume for the entire Sound system. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundInstance.md # SoundInstance Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/instance.js#L47 A SoundInstance plays a [Sound](https://api.playcanvas.com/engine/classes/Sound.md). One instance is one playback. It wraps an `AudioBufferSourceNode`, available as [source](https://api.playcanvas.com/engine/classes/SoundInstance.md#source) once playing, with a gain for [volume](https://api.playcanvas.com/engine/classes/SoundInstance.md#volume), and carries [pitch](https://api.playcanvas.com/engine/classes/SoundInstance.md#pitch), [loop](https://api.playcanvas.com/engine/classes/SoundInstance.md#loop), [startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime) and [duration](https://api.playcanvas.com/engine/classes/SoundInstance.md#duration) to select the region of the sound it plays. [play](https://api.playcanvas.com/engine/classes/SoundInstance.md#play), [pause](https://api.playcanvas.com/engine/classes/SoundInstance.md#pause), [resume](https://api.playcanvas.com/engine/classes/SoundInstance.md#resume) and [stop](https://api.playcanvas.com/engine/classes/SoundInstance.md#stop) drive it and fire the events of the same names, with `end` fired when playback finishes on its own; [isPlaying](https://api.playcanvas.com/engine/classes/SoundInstance.md#isplaying), [isPaused](https://api.playcanvas.com/engine/classes/SoundInstance.md#ispaused) and [isStopped](https://api.playcanvas.com/engine/classes/SoundInstance.md#isstopped) report the state, and [currentTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#currenttime) can be read or set to seek. Instances are normally created by [SoundSlot#play](https://api.playcanvas.com/engine/classes/SoundSlot.md#play) on a [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md), which returns the instance so a script can adjust or stop that one playback. [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes) inserts Web Audio nodes such as filters between the source and the destination. **Example** ```ts const instance = entity.sound.play('engine'); instance.pitch = 1.5; instance.once('end', () => console.log('finished')); ``` ## Constructors ### constructor ```ts new SoundInstance(manager: SoundManager, sound: Sound, options: object) ``` Create a new SoundInstance instance. **Parameters** - `manager` ([`SoundManager`](https://api.playcanvas.com/engine/classes/SoundManager.md)): The sound manager. - `sound` ([`Sound`](https://api.playcanvas.com/engine/classes/Sound.md)): 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. ## Properties ### source ```ts source: AudioBufferSourceNode | null = null ``` Gets the source that plays the sound resource. Source is only available after calling play. ## Accessors ### currentTime ```ts get currentTime(): number set currentTime(value: number) ``` Gets the current time of the sound that is playing, relative to [startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime). ### duration ```ts get duration(): number set duration(value: number) ``` Gets the duration of the sound that the instance will play starting from [startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime). The returned value is clamped to the time available after the normalized start time. ### isPaused ```ts get isPaused(): boolean ``` Gets whether the instance is currently paused. ### isPlaying ```ts get isPlaying(): boolean ``` Gets whether the instance is currently playing. ### isStopped ```ts get isStopped(): boolean ``` Gets whether the instance is currently stopped. ### isSuspended ```ts get isSuspended(): boolean ``` Gets whether the instance is currently suspended because the window is not focused. ### loop ```ts get loop(): boolean set loop(value: boolean) ``` Gets whether the instance will restart when it finishes playing. ### pitch ```ts get pitch(): number set pitch(pitch: number) ``` Gets the pitch modifier to play the sound with. ### sound ```ts get sound(): Sound set sound(value: Sound) ``` Gets the sound resource that the instance will play. ### startTime ```ts get startTime(): number set startTime(value: number) ``` Gets the start time from which the sound will start playing. ### volume ```ts get volume(): number set volume(volume: number) ``` Gets the volume modifier to play the sound with. In range 0-1. ## Methods ### clearExternalNodes ```ts clearExternalNodes(): void ``` Clears any external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes). ### getExternalNodes ```ts getExternalNodes(): AudioNode[] ``` Gets any external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes). **Returns** `AudioNode[]`: Returns an array that contains the two nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes). ### pause ```ts 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 ```ts 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 ```ts 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 ```ts 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** ```ts 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 ```ts 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. ## Events ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when the sound currently played by the instance ends. **Example** ```ts instance.on('end', () => { console.log('Instance ended'); }); ``` ### EVENT_PAUSE ```ts static EVENT_PAUSE: string = 'pause' ``` Fired when the instance is paused. **Example** ```ts instance.on('pause', () => { console.log('Instance paused'); }); ``` ### EVENT_PLAY ```ts static EVENT_PLAY: string = 'play' ``` Fired when the instance starts playing its source. **Example** ```ts instance.on('play', () => { console.log('Instance started playing'); }); ``` ### EVENT_RESUME ```ts static EVENT_RESUME: string = 'resume' ``` Fired when the instance is resumed. **Example** ```ts instance.on('resume', () => { console.log('Instance resumed'); }); ``` ### EVENT_STOP ```ts static EVENT_STOP: string = 'stop' ``` Fired when the instance is stopped. **Example** ```ts instance.on('stop', () => { console.log('Instance stopped'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundInstance3d.md # SoundInstance3d Class · extends [`SoundInstance`](https://api.playcanvas.com/engine/classes/SoundInstance.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/instance3d.js#L26 A SoundInstance3d plays a [Sound](https://api.playcanvas.com/engine/classes/Sound.md) in 3D. It is what a positional [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md) creates. The sound is placed at [position](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#position) and its volume falls off with distance from the [AudioListenerComponent](https://api.playcanvas.com/engine/classes/AudioListenerComponent.md) according to [distanceModel](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#distancemodel), one of [DISTANCE_LINEAR](https://api.playcanvas.com/engine/variables/DISTANCE_LINEAR.md), [DISTANCE_INVERSE](https://api.playcanvas.com/engine/variables/DISTANCE_INVERSE.md) and [DISTANCE_EXPONENTIAL](https://api.playcanvas.com/engine/variables/DISTANCE_EXPONENTIAL.md), shaped by [refDistance](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#refdistance), [maxDistance](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#maxdistance) and [rollOffFactor](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#rollofffactor). The owning slot keeps [position](https://api.playcanvas.com/engine/classes/SoundInstance3d.md#position) in step with its entity, so these properties are usually set on the component rather than on each instance. ## Constructors ### constructor ```ts new SoundInstance3d(manager: SoundManager, sound: Sound, options?: object) ``` Create a new SoundInstance3d instance. **Parameters** - `manager` ([`SoundManager`](https://api.playcanvas.com/engine/classes/SoundManager.md)): The sound manager. - `sound` ([`Sound`](https://api.playcanvas.com/engine/classes/Sound.md)): 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: - [DISTANCE_LINEAR](https://api.playcanvas.com/engine/variables/DISTANCE_LINEAR.md) - [DISTANCE_INVERSE](https://api.playcanvas.com/engine/variables/DISTANCE_INVERSE.md) - [DISTANCE_EXPONENTIAL](https://api.playcanvas.com/engine/variables/DISTANCE_EXPONENTIAL.md) Defaults to [DISTANCE_LINEAR](https://api.playcanvas.com/engine/variables/DISTANCE_LINEAR.md). - `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`](https://api.playcanvas.com/engine/classes/Vec3.md), 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. ## Accessors ### distanceModel ```ts 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. ### maxDistance ```ts get maxDistance(): number set maxDistance(value: number) ``` Gets the maximum distance from the listener at which audio falloff stops. ### position ```ts get position(): Vec3 set position(value: Vec3) ``` Gets the position of the sound in 3D space. ### refDistance ```ts get refDistance(): number set refDistance(value: number) ``` Gets the reference distance for reducing volume as the sound source moves further from the listener. ### rollOffFactor ```ts get rollOffFactor(): number set rollOffFactor(value: number) ``` Gets the factor used in the falloff equation. ## Inherited from [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) - `source: AudioBufferSourceNode | null = null` - `get currentTime(): number` · `set currentTime(value: number)` - `get duration(): number` · `set duration(value: number)` - `get isPaused(): boolean` - `get isPlaying(): boolean` - `get isStopped(): boolean` - `get isSuspended(): boolean` - `get 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(): void` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `getExternalNodes(): AudioNode[]` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `pause(): boolean` - `play(): boolean` - `resume(): boolean` - `setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void` - `stop(): boolean` - `static EVENT_END: string = 'end'` - `static EVENT_PAUSE: string = 'pause'` - `static EVENT_PLAY: string = 'play'` - `static EVENT_RESUME: string = 'resume'` - `static EVENT_STOP: string = 'stop'` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundManager.md # SoundManager Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/manager.js#L26 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](https://api.playcanvas.com/engine/classes/SoundInstance.md) plays through and the listener from which positional sounds are heard, applies the master [volume](https://api.playcanvas.com/engine/classes/SoundManager.md#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. ## Constructors ### constructor ```ts new SoundManager() ``` Create a new SoundManager instance. ## Properties ### listener ```ts listener: Listener ``` The listener associated with this manager. ## Accessors ### volume ```ts get volume(): number set volume(volume: number) ``` Gets the global volume for the manager. ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/SoundSlot.md # SoundSlot Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/slot.js#L54 The SoundSlot controls the playback of [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md)s. SoundSlots are managed by [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md)s. To add and remove SoundSlots on a SoundComponent, use [SoundComponent#addSlot](https://api.playcanvas.com/engine/classes/SoundComponent.md#addslot) and [SoundComponent#removeSlot](https://api.playcanvas.com/engine/classes/SoundComponent.md#removeslot) respectively. A slot holds one audio [asset](https://api.playcanvas.com/engine/classes/SoundSlot.md#asset) and the settings applied to every instance it creates: [volume](https://api.playcanvas.com/engine/classes/SoundSlot.md#volume), [pitch](https://api.playcanvas.com/engine/classes/SoundSlot.md#pitch), [loop](https://api.playcanvas.com/engine/classes/SoundSlot.md#loop), [startTime](https://api.playcanvas.com/engine/classes/SoundSlot.md#starttime) and [duration](https://api.playcanvas.com/engine/classes/SoundSlot.md#duration), plus [autoPlay](https://api.playcanvas.com/engine/classes/SoundSlot.md#autoplay) to start as soon as the asset has loaded and [overlap](https://api.playcanvas.com/engine/classes/SoundSlot.md#overlap) to let several instances play at once instead of stopping the previous one. [play](https://api.playcanvas.com/engine/classes/SoundSlot.md#play) returns the new [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) and [instances](https://api.playcanvas.com/engine/classes/SoundSlot.md#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** ```ts 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 ``` ## Properties ### instances ```ts instances: SoundInstance[] = [] ``` An array that contains all the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md)s currently being played by the slot. ### name ```ts name: string ``` The name of the slot. ## Accessors ### asset ```ts get asset(): number | null set asset(value: number | null) ``` Gets the asset id. ### autoPlay ```ts get autoPlay(): boolean set autoPlay(value: boolean) ``` Gets whether the slot will begin playing as soon as it is loaded. ### duration ```ts get duration(): number set duration(value: number) ``` Gets the duration of the sound that the slot will play starting from [startTime](https://api.playcanvas.com/engine/classes/SoundSlot.md#starttime). The returned value is clamped to the time available after the normalized start time. ### isLoaded ```ts get isLoaded(): boolean ``` Gets whether the asset of the slot is loaded. ### isPaused ```ts get isPaused(): boolean ``` Gets whether the slot is currently paused. ### isPlaying ```ts get isPlaying(): boolean ``` Gets whether the slot is currently playing. ### isStopped ```ts get isStopped(): boolean ``` Gets whether the slot is currently stopped. ### loop ```ts get loop(): boolean set loop(value: boolean) ``` Gets whether the slot will restart when it finishes playing. ### overlap ```ts get overlap(): boolean set overlap(value: boolean) ``` Gets whether the sounds played from this slot will be played independently of each other. ### pitch ```ts get pitch(): number set pitch(value: number) ``` Gets the pitch modifier to play the sound with. ### startTime ```ts get startTime(): number set startTime(value: number) ``` Gets the start time from which the sound will start playing. ### volume ```ts get volume(): number set volume(value: number) ``` Gets the volume modifier to play the sound with. ## Methods ### clearExternalNodes ```ts clearExternalNodes(): void ``` Clears any external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundSlot.md#setexternalnodes). ### getExternalNodes ```ts getExternalNodes(): AudioNode[] ``` Gets an array that contains the two external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundSlot.md#setexternalnodes). **Returns** `AudioNode[]`: An array of 2 elements that contains the first and last nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundSlot.md#setexternalnodes). ### load ```ts load(): void ``` Loads the asset assigned to this slot. ### pause ```ts pause(): boolean ``` Pauses all sound instances. To continue playback call [resume](https://api.playcanvas.com/engine/classes/SoundSlot.md#resume). **Returns** `boolean`: True if the sound instances paused successfully, false otherwise. ### play ```ts play(): SoundInstance ``` Plays a sound. If [overlap](https://api.playcanvas.com/engine/classes/SoundSlot.md#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`](https://api.playcanvas.com/engine/classes/SoundInstance.md): The new sound instance. ### resume ```ts resume(): boolean ``` Resumes playback of all paused sound instances. **Returns** `boolean`: True if any instances were resumed. ### setExternalNodes ```ts 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** ```ts 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 ```ts stop(): boolean ``` Stops playback of all sound instances. **Returns** `boolean`: True if any instances were stopped. ## Events ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when a sound instance stops playing because it reached its end. The handler is passed the [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) that ended. **Example** ```ts slot.on('end', (instance) => { console.log('Sound instance playback ended'); }); ``` ### EVENT_LOAD ```ts static EVENT_LOAD: string = 'load' ``` Fired when the sound [Asset](https://api.playcanvas.com/engine/classes/Asset.md) assigned to the slot is loaded. The handler is passed the loaded [Sound](https://api.playcanvas.com/engine/classes/Sound.md) resource. **Example** ```ts slot.on('load', (sound) => { console.log('Sound resource loaded'); }); ``` ### EVENT_PAUSE ```ts static EVENT_PAUSE: string = 'pause' ``` Fired when a [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) is paused on a slot. The handler is passed the sound instance that is paused. **Example** ```ts slot.on('pause', (instance) => { console.log('Sound instance paused'); }); ``` ### EVENT_PLAY ```ts static EVENT_PLAY: string = 'play' ``` Fired when a [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) starts playing on a slot. The handler is passed the sound instance that started playing. **Example** ```ts slot.on('play', (instance) => { console.log('Sound instance started playing'); }); ``` ### EVENT_RESUME ```ts static EVENT_RESUME: string = 'resume' ``` Fired when a [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) is resumed on a slot. The handler is passed the sound instance that is resumed. **Example** ```ts slot.on('resume', (instance) => { console.log('Sound instance resumed'); }); ``` ### EVENT_STOP ```ts static EVENT_STOP: string = 'stop' ``` Fired when a [SoundInstance](https://api.playcanvas.com/engine/classes/SoundInstance.md) is stopped on a slot. The handler is passed the sound instance that is stopped. **Example** ```ts slot.on('stop', (instance) => { console.log('Sound instance stopped'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ButtonComponent.md # ButtonComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/component.js#L82 The ButtonComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to behave like a button, with different visual states for hover and press interactions. It is designed to be used together with an [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) on the same entity, which provides the button's visual appearance and input hit area. Set [imageEntity](https://api.playcanvas.com/engine/classes/ButtonComponent.md#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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#button) property: ```javascript 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: - [Buttons](https://playcanvas.github.io/#/user-interface/buttons) - [Toggles and radio groups](https://playcanvas.github.io/#/user-interface/common-widgets) ## Accessors ### active ```ts get active(): boolean set active(arg: boolean) ``` Gets the button's active state. ### fadeDuration ```ts get fadeDuration(): number set fadeDuration(arg: number) ``` Gets the duration to be used when fading between tints, in milliseconds. ### hitPadding ```ts get hitPadding(): Vec4 set hitPadding(arg: Vec4) ``` Gets the padding to be used in hit-test calculations. ### hoverSpriteAsset ```ts get hoverSpriteAsset(): Asset | null set hoverSpriteAsset(arg: Asset | null) ``` Gets the sprite to be used as the button image when the user hovers over it. ### hoverSpriteFrame ```ts get hoverSpriteFrame(): number set hoverSpriteFrame(arg: number) ``` Gets the frame to be used from the hover sprite. ### hoverTint ```ts get hoverTint(): Color set hoverTint(arg: Color) ``` Gets the tint color to be used on the button image when the user hovers over it. ### imageEntity ```ts get imageEntity(): Entity | null set imageEntity(arg: Entity | null) ``` Gets the entity to be used as the button background. ### inactiveSpriteAsset ```ts get inactiveSpriteAsset(): Asset | null set inactiveSpriteAsset(arg: Asset | null) ``` Gets the sprite to be used as the button image when the button is not interactive. ### inactiveSpriteFrame ```ts get inactiveSpriteFrame(): number set inactiveSpriteFrame(arg: number) ``` Gets the frame to be used from the inactive sprite. ### inactiveTint ```ts get inactiveTint(): Color set inactiveTint(arg: Color) ``` Gets the tint color to be used on the button image when the button is not interactive. ### pressedSpriteAsset ```ts get pressedSpriteAsset(): Asset | null set pressedSpriteAsset(arg: Asset | null) ``` Gets the sprite to be used as the button image when the user presses it. ### pressedSpriteFrame ```ts get pressedSpriteFrame(): number set pressedSpriteFrame(arg: number) ``` Gets the frame to be used from the pressed sprite. ### pressedTint ```ts get pressedTint(): Color set pressedTint(arg: Color) ``` Gets the tint color to be used on the button image when the user presses it. ### transitionMode ```ts get transitionMode(): number set transitionMode(arg: number) ``` Gets the button transition mode. ## Events ### EVENT_CLICK ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md) or [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.button.on('click', (event) => { console.log(`Clicked entity ${entity.name}`); }); ``` ### EVENT_HOVEREND ```ts static EVENT_HOVEREND: string = 'hoverend' ``` Fired when the button changes state to be not hovered. **Example** ```ts entity.button.on('hoverend', () => { console.log(`Entity ${entity.name} unhovered`); }); ``` ### EVENT_HOVERSTART ```ts static EVENT_HOVERSTART: string = 'hoverstart' ``` Fired when the button changes state to be hovered. **Example** ```ts entity.button.on('hoverstart', () => { console.log(`Entity ${entity.name} hovered`); }); ``` ### EVENT_MOUSEDOWN ```ts static EVENT_MOUSEDOWN: string = 'mousedown' ``` Fired when the mouse is pressed while the cursor is on the component. The handler is passed a [ElementMouseEvent](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.button.on('mousedown', (event) => { console.log(`Mouse down on entity ${entity.name}`); }); ``` ### EVENT_MOUSEENTER ```ts static EVENT_MOUSEENTER: string = 'mouseenter' ``` Fired when the mouse cursor enters the component. The handler is passed a [ElementMouseEvent](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.button.on('mouseenter', (event) => { console.log(`Mouse entered entity ${entity.name}`); }); ``` ### EVENT_MOUSELEAVE ```ts static EVENT_MOUSELEAVE: string = 'mouseleave' ``` Fired when the mouse cursor leaves the component. The handler is passed a [ElementMouseEvent](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.button.on('mouseleave', (event) => { console.log(`Mouse left entity ${entity.name}`); }); ``` ### EVENT_MOUSEUP ```ts static EVENT_MOUSEUP: string = 'mouseup' ``` Fired when the mouse is released while the cursor is on the component. The handler is passed a [ElementMouseEvent](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.button.on('mouseup', (event) => { console.log(`Mouse up on entity ${entity.name}`); }); ``` ### EVENT_PRESSEDEND ```ts static EVENT_PRESSEDEND: string = 'pressedend' ``` Fired when the button changes state to be not pressed. **Example** ```ts entity.button.on('pressedend', () => { console.log(`Entity ${entity.name} unpressed`); }); ``` ### EVENT_PRESSEDSTART ```ts static EVENT_PRESSEDSTART: string = 'pressedstart' ``` Fired when the button changes state to be pressed. **Example** ```ts entity.button.on('pressedstart', () => { console.log(`Entity ${entity.name} pressed`); }); ``` ### EVENT_SELECTEND ```ts static EVENT_SELECTEND: string = 'selectend' ``` Fired when a xr select ends on the component. The handler is passed a [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.button.on('selectend', (event) => { console.log(`Select ended on entity ${entity.name}`); }); ``` ### EVENT_SELECTENTER ```ts static EVENT_SELECTENTER: string = 'selectenter' ``` Fired when a xr select now hovering over the component. The handler is passed a [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.button.on('selectenter', (event) => { console.log(`Select entered entity ${entity.name}`); }); ``` ### EVENT_SELECTLEAVE ```ts static EVENT_SELECTLEAVE: string = 'selectleave' ``` Fired when a xr select not hovering over the component. The handler is passed a [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.button.on('selectleave', (event) => { console.log(`Select left entity ${entity.name}`); }); ``` ### EVENT_SELECTSTART ```ts static EVENT_SELECTSTART: string = 'selectstart' ``` Fired when a xr select starts on the component. The handler is passed a [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.button.on('selectstart', (event) => { console.log(`Select started on entity ${entity.name}`); }); ``` ### EVENT_TOUCHCANCEL ```ts static EVENT_TOUCHCANCEL: string = 'touchcancel' ``` Fired when a touch is canceled on the component. The handler is passed a [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.button.on('touchcancel', (event) => { console.log(`Touch canceled on entity ${entity.name}`); }); ``` ### EVENT_TOUCHEND ```ts static EVENT_TOUCHEND: string = 'touchend' ``` Fired when a touch ends on the component. The handler is passed a [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.button.on('touchend', (event) => { console.log(`Touch ended on entity ${entity.name}`); }); ``` ### EVENT_TOUCHLEAVE ```ts static EVENT_TOUCHLEAVE: string = 'touchleave' ``` Fired when a touch leaves the component. The handler is passed a [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.button.on('touchleave', (event) => { console.log(`Touch left entity ${entity.name}`); }); ``` ### EVENT_TOUCHSTART ```ts static EVENT_TOUCHSTART: string = 'touchstart' ``` Fired when a touch starts on the component. The handler is passed a [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.button.on('touchstart', (event) => { console.log(`Touch started on entity ${entity.name}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ButtonComponentSystem.md # ButtonComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/system.js#L45 Manages the [ButtonComponent](https://api.playcanvas.com/engine/classes/ButtonComponent.md)s of an application. Reach it through `app.systems.button`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementComponent.md # ElementComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/component.js#L100 ElementComponents are used to construct user interfaces. The [type](https://api.playcanvas.com/engine/classes/ElementComponent.md#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](https://api.playcanvas.com/engine/classes/ScreenComponent.md) ancestor in the hierarchy, it will be transformed with respect to the coordinate system of the screen. If there is no [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript const entity = new Entity(); entity.addComponent('element'); // This defaults to a 'group' element ``` To create a simple text-based element: ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#element) property: ```javascript 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: - [Anchors](https://playcanvas.github.io/#/user-interface/anchors) - [Image fitting](https://playcanvas.github.io/#/user-interface/image-fit) - [Sliced panels](https://playcanvas.github.io/#/user-interface/panel) - [Masking](https://playcanvas.github.io/#/user-interface/masking) - [Rendering 3D into an image](https://playcanvas.github.io/#/user-interface/render-to-image) - [Custom shader](https://playcanvas.github.io/#/user-interface/custom-shader) - [Basic text rendering](https://playcanvas.github.io/#/user-interface/text) - [Auto font sizing](https://playcanvas.github.io/#/user-interface/text-auto-font-size) - [Emojis](https://playcanvas.github.io/#/user-interface/text-emojis) - [Justified text](https://playcanvas.github.io/#/user-interface/text-justify) - [Text localization](https://playcanvas.github.io/#/user-interface/text-localization) - [Text markup](https://playcanvas.github.io/#/user-interface/text-markup) - [Typewriter text](https://playcanvas.github.io/#/user-interface/text-typewriter) ## Properties ### screen ```ts screen: Entity | null ``` The Entity with a [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md) that this component belongs to. This is automatically set when the component is a child of a ScreenComponent. ## Accessors ### aabb ```ts get aabb(): BoundingBox | null ``` Gets the world space axis-aligned bounding box for this element component. ### alignment ```ts get alignment(): Vec2 set alignment(arg: Vec2) ``` Gets the horizontal and vertical alignment of the text. ### anchor ```ts get anchor(): Readonly set anchor(value: Readonly) ``` Gets the anchor for this element component. Use the setter to update the anchor. ### autoFitHeight ```ts 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. ### autoFitWidth ```ts 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. ### autoHeight ```ts get autoHeight(): boolean set autoHeight(arg: boolean) ``` Gets whether to automatically set the height of the component to be the same as the [textHeight](https://api.playcanvas.com/engine/classes/ElementComponent.md#textheight). ### autoWidth ```ts get autoWidth(): boolean set autoWidth(arg: boolean) ``` Gets whether to automatically set the width of the component to be the same as the [textWidth](https://api.playcanvas.com/engine/classes/ElementComponent.md#textwidth). ### batchGroupId ```ts get batchGroupId(): number set batchGroupId(value: number) ``` Gets the batch group (see [BatchGroup](https://api.playcanvas.com/engine/classes/BatchGroup.md)) for this element. ### bottom ```ts get bottom(): number set bottom(value: number) ``` Gets the distance from the bottom edge of the anchor. ### calculatedHeight ```ts get calculatedHeight(): number set calculatedHeight(value: number) ``` Gets the height at which the element will be rendered. ### calculatedWidth ```ts get calculatedWidth(): number set calculatedWidth(value: number) ``` Gets the width at which the element will be rendered. ### canvasCorners ```ts get canvasCorners(): Vec2[] ``` Gets the array of 4 [Vec2](https://api.playcanvas.com/engine/classes/Vec2.md)s 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. ### color ```ts get color(): Readonly set color(arg: Readonly) ``` Gets the color of the element. Use the setter to update the color. ### drawOrder ```ts get drawOrder(): number set drawOrder(value: number) ``` Gets the draw order of the component. ### enableMarkup ```ts get enableMarkup(): boolean set enableMarkup(arg: boolean) ``` Gets whether markup processing is enabled for this element. ### fitMode ```ts get fitMode(): string set fitMode(value: string) ``` Gets the fit mode of the element. ### font ```ts get font(): Font | CanvasFont set font(arg: Font | CanvasFont) ``` Gets the font used for rendering the text. ### fontAsset ```ts get fontAsset(): number | Asset | null set fontAsset(arg: number | Asset | null) ``` Gets the id of the font asset used for rendering the text. ### fontSize ```ts get fontSize(): number set fontSize(arg: number) ``` Gets the size of the font. ### height ```ts get height(): number set height(value: number) ``` Gets the height of the element. ### justify ```ts get justify(): boolean set justify(arg: boolean) ``` Gets whether wrapped lines are stretched to be flush with both edges of the element. ### key ```ts get key(): string set key(arg: string) ``` Gets the localization key to use to get the localized text from [Application#i18n](https://api.playcanvas.com/engine/classes/Application.md#i18n). ### layers ```ts get layers(): readonly number[] set layers(value: readonly number[]) ``` Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this element belongs. ### left ```ts get left(): number set left(value: number) ``` Gets the distance from the left edge of the anchor. ### lineHeight ```ts get lineHeight(): number set lineHeight(arg: number) ``` Gets the height of each line of text. ### lines ```ts get lines(): string[] ``` Gets the lines of rendered text, split by line breaks and word wrapping. Only works for [ELEMENTTYPE_TEXT](https://api.playcanvas.com/engine/variables/ELEMENTTYPE_TEXT.md) elements, and is populated when the text is laid out, so it reads as `undefined` until the first update. ### margin ```ts get margin(): Readonly set margin(value: Readonly) ``` Gets the distance from the left, bottom, right and top edges of the anchor. Use the setter to update the margin. ### mask ```ts get mask(): boolean set mask(arg: boolean) ``` Gets whether the Image Element should be treated as a mask. ### material ```ts get material(): Material set material(arg: Material) ``` Gets the material to use when rendering an image. ### materialAsset ```ts get materialAsset(): number | Asset | null set materialAsset(arg: number | Asset | null) ``` Gets the id of the material asset to use when rendering an image. ### maxFontSize ```ts get maxFontSize(): number set maxFontSize(arg: number) ``` Gets the maximum size that the font can scale to when [autoFitWidth](https://api.playcanvas.com/engine/classes/ElementComponent.md#autofitwidth) or [autoFitHeight](https://api.playcanvas.com/engine/classes/ElementComponent.md#autofitheight) are true. ### maxLines ```ts 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. ### minFontSize ```ts get minFontSize(): number set minFontSize(arg: number) ``` Gets the minimum size that the font can scale to when [autoFitWidth](https://api.playcanvas.com/engine/classes/ElementComponent.md#autofitwidth) or [autoFitHeight](https://api.playcanvas.com/engine/classes/ElementComponent.md#autofitheight) are true. ### opacity ```ts get opacity(): number set opacity(arg: number) ``` Gets the opacity of the element. ### outlineColor ```ts get outlineColor(): Color set outlineColor(arg: Color) ``` Gets the text outline effect color and opacity. ### outlineThickness ```ts get outlineThickness(): number set outlineThickness(arg: number) ``` Gets the width of the text outline effect. ### pivot ```ts get pivot(): Readonly set pivot(value: Readonly) ``` Gets the position of the pivot of the component relative to its anchor. Use the setter to update the pivot. ### pixelsPerUnit ```ts get pixelsPerUnit(): number | null set pixelsPerUnit(arg: number | null) ``` Gets the number of pixels that map to one PlayCanvas unit. ### rangeEnd ```ts get rangeEnd(): number set rangeEnd(arg: number) ``` Gets the index of the last character to render. ### rangeStart ```ts get rangeStart(): number set rangeStart(arg: number) ``` Gets the index of the first character to render. ### rect ```ts get rect(): Readonly | null set rect(arg: Readonly | null) ``` Gets the region of the texture to use in order to render an image. Use the setter to update the region. ### right ```ts get right(): number set right(value: number) ``` Gets the distance from the right edge of the anchor. ### rtlReorder ```ts get rtlReorder(): boolean set rtlReorder(arg: boolean) ``` Gets whether to reorder the text for RTL languages. ### screenCorners ```ts get screenCorners(): Vec3[] ``` Gets the array of 4 [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md)s that represent the bottom left, bottom right, top right and top left corners of the component relative to its parent [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md). ### shadowColor ```ts get shadowColor(): Color set shadowColor(arg: Color) ``` Gets the text shadow effect color and opacity. ### shadowOffset ```ts get shadowOffset(): Vec2 set shadowOffset(arg: Vec2) ``` Gets the offset of the text shadow, relative to the text. ### spacing ```ts get spacing(): number set spacing(arg: number) ``` Gets the spacing between the letters of the text. ### sprite ```ts get sprite(): Sprite set sprite(arg: Sprite) ``` Gets the sprite to render. ### spriteAsset ```ts get spriteAsset(): number | Asset | null set spriteAsset(arg: number | Asset | null) ``` Gets the id of the sprite asset to render. ### spriteFrame ```ts get spriteFrame(): number set spriteFrame(arg: number) ``` Gets the frame of the sprite to render. ### text ```ts get text(): string set text(arg: string) ``` Gets the text to render. ### textHeight ```ts get textHeight(): number ``` Gets the height of the text rendered by the component. Only works for [ELEMENTTYPE_TEXT](https://api.playcanvas.com/engine/variables/ELEMENTTYPE_TEXT.md) elements. ### texture ```ts get texture(): Texture set texture(arg: Texture) ``` Gets the texture to render. ### textureAsset ```ts get textureAsset(): number | Asset | null set textureAsset(arg: number | Asset | null) ``` Gets the id of the texture asset to render. ### textWidth ```ts get textWidth(): number ``` Gets the width of the text rendered by the component. Only works for [ELEMENTTYPE_TEXT](https://api.playcanvas.com/engine/variables/ELEMENTTYPE_TEXT.md) elements. ### top ```ts get top(): number set top(value: number) ``` Gets the distance from the top edge of the anchor. ### type ```ts get type(): string set type(value: string) ``` Gets the type of the ElementComponent. ### unicodeConverter ```ts get unicodeConverter(): boolean set unicodeConverter(arg: boolean) ``` Gets whether to convert unicode characters. ### useInput ```ts get useInput(): boolean set useInput(value: boolean) ``` Gets whether the component will receive mouse and touch input events. ### width ```ts get width(): number set width(value: number) ``` Gets the width of the element. ### worldCorners ```ts get worldCorners(): Vec3[] ``` Gets the array of 4 [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md)s 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. ### wrapLines ```ts get wrapLines(): boolean set wrapLines(arg: boolean) ``` Gets whether to automatically wrap lines based on the element width. ## Events ### EVENT_CLICK ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md), [ElementTouchEvent](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md) or [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('click', (event) => { console.log(`Click event on entity ${entity.name}`); }); ``` ### EVENT_MOUSEDOWN ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mousedown', (event) => { console.log(`Mouse down event on entity ${entity.name}`); }); ``` ### EVENT_MOUSEENTER ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mouseenter', (event) => { console.log(`Mouse enter event on entity ${entity.name}`); }); ``` ### EVENT_MOUSELEAVE ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mouseleave', (event) => { console.log(`Mouse leave event on entity ${entity.name}`); }); ``` ### EVENT_MOUSEMOVE ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mousemove', (event) => { console.log(`Mouse move event on entity ${entity.name}`); }); ``` ### EVENT_MOUSEUP ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mouseup', (event) => { console.log(`Mouse up event on entity ${entity.name}`); }); ``` ### EVENT_MOUSEWHEEL ```ts 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](https://api.playcanvas.com/engine/classes/ElementMouseEvent.md). **Example** ```ts entity.element.on('mousewheel', (event) => { console.log(`Mouse wheel event on entity ${entity.name}`); }); ``` ### EVENT_SELECTEND ```ts 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](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('selectend', (event) => { console.log(`Select end event on entity ${entity.name}`); }); ``` ### EVENT_SELECTENTER ```ts 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](https://api.playcanvas.com/engine/classes/XrInputSource.md#elementinput) is true. The handler is passed an [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('selectenter', (event) => { console.log(`Select enter event on entity ${entity.name}`); }); ``` ### EVENT_SELECTLEAVE ```ts 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](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('selectleave', (event) => { console.log(`Select leave event on entity ${entity.name}`); }); ``` ### EVENT_SELECTMOVE ```ts 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](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('selectmove', (event) => { console.log(`Select move event on entity ${entity.name}`); }); ``` ### EVENT_SELECTSTART ```ts 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](https://api.playcanvas.com/engine/classes/XrInputSource.md#elementinput) is true. The handler is passed an [ElementSelectEvent](https://api.playcanvas.com/engine/classes/ElementSelectEvent.md). **Example** ```ts entity.element.on('selectstart', (event) => { console.log(`Select start event on entity ${entity.name}`); }); ``` ### EVENT_TOUCHCANCEL ```ts 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](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.element.on('touchcancel', (event) => { console.log(`Touch cancel event on entity ${entity.name}`); }); ``` ### EVENT_TOUCHEND ```ts 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](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.element.on('touchend', (event) => { console.log(`Touch end event on entity ${entity.name}`); }); ``` ### EVENT_TOUCHMOVE ```ts 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](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.element.on('touchmove', (event) => { console.log(`Touch move event on entity ${entity.name}`); }); ``` ### EVENT_TOUCHSTART ```ts 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](https://api.playcanvas.com/engine/classes/ElementTouchEvent.md). **Example** ```ts entity.element.on('touchstart', (event) => { console.log(`Touch start event on entity ${entity.name}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementComponentSystem.md # ElementComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/system.js#L43 Manages the [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s of an application. Reach it through `app.systems.element`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementDragHelper.md # ElementDragHelper Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/element-drag-helper.js#L36 Helper class that makes it easy to create Elements that can be dragged by the mouse or touch. Relevant Engine API examples: - [Drag and drop](https://playcanvas.github.io/#/user-interface/drag-and-drop) ## Constructors ### constructor ```ts new ElementDragHelper(element: ElementComponent, axis?: string) ``` Create a new ElementDragHelper instance. **Parameters** - `element` ([`ElementComponent`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The Element that should become draggable. - `axis` (`string`, optional): Optional axis to constrain to, either 'x', 'y' or null. ## Events ### EVENT_DRAGEND ```ts static EVENT_DRAGEND: string = 'drag:end' ``` Fired when the current new drag operation ends. **Example** ```ts elementDragHelper.on('drag:end', () => { console.log('Drag ended'); }); ``` ### EVENT_DRAGMOVE ```ts static EVENT_DRAGMOVE: string = 'drag:move' ``` Fired whenever the position of the dragged element changes. The handler is passed the current [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) position of the dragged element. **Example** ```ts elementDragHelper.on('drag:move', (position) => { console.log(`Dragged element position is ${position}`); }); ``` ### EVENT_DRAGSTART ```ts static EVENT_DRAGSTART: string = 'drag:start' ``` Fired when a new drag operation starts. **Example** ```ts elementDragHelper.on('drag:start', () => { console.log('Drag started'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementInput.md # ElementInput Class · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L356 Handles mouse and touch events for [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. When input events occur on an ElementComponent this fires the appropriate events on the ElementComponent. Relevant Engine API examples: - [Input events](https://playcanvas.github.io/#/user-interface/input-events) ## Constructors ### constructor ```ts 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. ## Methods ### addElement ```ts addElement(element: ElementComponent): void ``` Add a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) to the internal list of ElementComponents that are being checked for input. **Parameters** - `element` ([`ElementComponent`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent. ### attach ```ts attach(domElement: Element): void ``` Attach mouse and touch events to a DOM element. **Parameters** - `domElement` (`Element`): The DOM element. ### detach ```ts detach(): void ``` Remove mouse and touch events from the DOM element that it is attached to. ### removeElement ```ts removeElement(element: ElementComponent): void ``` Remove a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) from the internal list of ElementComponents that are being checked for input. **Parameters** - `element` ([`ElementComponent`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementInputEvent.md # ElementInputEvent Class · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L124 Represents an input event fired on a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md). When an event is raised on an ElementComponent it bubbles up to its parent ElementComponents unless we call stopPropagation(). ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent that this event was originally raised on. - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The CameraComponent that this event was originally raised via. ## Properties ### camera ```ts camera: CameraComponent ``` The CameraComponent that this event was originally raised via. ### element ```ts element: ElementComponent ``` The ElementComponent that this event was originally raised on. ### event ```ts 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`. ## Methods ### stopPropagation ```ts stopPropagation(): void ``` Stop propagation of the event to parent [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. This also stops propagation of the event to other event listeners of the original DOM Event. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementMouseEvent.md # ElementMouseEvent Class · extends [`ElementInputEvent`](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L180 Represents a Mouse event fired on a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md). ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent that this event was originally raised on. - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): 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. ## Properties ### altKey ```ts altKey: boolean ``` Whether the alt key was pressed. ### button ```ts button: number ``` The mouse button. ### ctrlKey ```ts ctrlKey: boolean ``` Whether the ctrl key was pressed. ### dx ```ts dx: number ``` The amount of horizontal movement of the cursor. ### dy ```ts dy: number ``` The amount of vertical movement of the cursor. ### metaKey ```ts metaKey: boolean ``` Whether the meta key was pressed. ### shiftKey ```ts shiftKey: boolean ``` Whether the shift key was pressed. ### wheelDelta ```ts wheelDelta: number ``` The amount of the wheel movement. ## Inherited from [ElementInputEvent](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) - `camera: CameraComponent` - `element: ElementComponent` - `event: MouseEvent | TouchEvent | XRInputSourceEvent | null` - `stopPropagation(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementSelectEvent.md # ElementSelectEvent Class · extends [`ElementInputEvent`](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L321 Represents a XRInputSourceEvent fired on a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md). ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent that this event was originally raised on. - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): The CameraComponent that this event was originally raised via. - `inputSource` ([`XrInputSource`](https://api.playcanvas.com/engine/classes/XrInputSource.md)): The XR input source that this event was originally raised from. ## Properties ### inputSource ```ts inputSource: XrInputSource ``` The XR input source that this event was originally raised from. ## Inherited from [ElementInputEvent](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) - `camera: CameraComponent` - `element: ElementComponent` - `event: MouseEvent | TouchEvent | XRInputSourceEvent | null` - `stopPropagation(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ElementTouchEvent.md # ElementTouchEvent Class · extends [`ElementInputEvent`](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L274 Represents a TouchEvent fired on a [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md). It carries the browser's own TouchEvent and Touch objects. ## Constructors ### constructor ```ts 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`](https://api.playcanvas.com/engine/classes/ElementComponent.md)): The ElementComponent that this event was originally raised on. - `camera` ([`CameraComponent`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): 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. ## Properties ### changedTouches ```ts changedTouches: TouchList ``` The Touch objects representing individual points of contact whose states changed between the previous touch event and this one. ### touch ```ts touch: Touch ``` The browser Touch that triggered the event. Match a touch across events by its `identifier`. ### touches ```ts touches: TouchList ``` The Touch objects representing all current points of contact with the surface, regardless of target or changed status. ## Inherited from [ElementInputEvent](https://api.playcanvas.com/engine/classes/ElementInputEvent.md) - `camera: CameraComponent` - `element: ElementComponent` - `event: MouseEvent | TouchEvent | XRInputSourceEvent | null` - `stopPropagation(): void` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/Font.md # Font Class · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/font/font.js#L13 Represents the resource of a font asset. ## Constructors ### constructor ```ts new Font(textures: Texture[], data: any) ``` Create a new Font instance. **Parameters** - `textures` ([`Texture`](https://api.playcanvas.com/engine/classes/Texture.md)`[]`): The font textures. - `data` (`any`): The font data. ## Properties ### intensity ```ts intensity: number ``` The font intensity. ### textures ```ts textures: Texture[] ``` The font textures. ## Methods ### destroy ```ts 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](https://api.playcanvas.com/engine/classes/Asset.md#unload)). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LayoutChildComponent.md # LayoutChildComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-child/component.js#L35 The LayoutChildComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to control the sizing and fitting behavior applied to it by its parent [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md). 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#layoutchild) property: ```javascript entity.layoutchild.minWidth = 80; // Increase the minimum width console.log(entity.layoutchild.minWidth); // Get the minimum width and print it ``` ## Accessors ### excludeFromLayout ```ts get excludeFromLayout(): boolean set excludeFromLayout(value: boolean) ``` Gets whether the child will be excluded from all layout calculations. ### fitHeightProportion ```ts 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. ### fitWidthProportion ```ts 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. ### maxHeight ```ts get maxHeight(): number | null set maxHeight(value: number | null) ``` Gets the maximum height the element should be rendered at. ### maxWidth ```ts get maxWidth(): number | null set maxWidth(value: number | null) ``` Gets the maximum width the element should be rendered at. ### minHeight ```ts get minHeight(): number set minHeight(value: number) ``` Gets the minimum height the element should be rendered at. ### minWidth ```ts get minWidth(): number set minWidth(value: number) ``` Gets the minimum width the element should be rendered at. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LayoutChildComponentSystem.md # LayoutChildComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-child/system.js#L15 Manages the [LayoutChildComponent](https://api.playcanvas.com/engine/classes/LayoutChildComponent.md)s of an application. Reach it through `app.systems.layoutchild`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md # LayoutGroupComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/component.js#L57 The LayoutGroupComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to position and scale its child [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#layoutgroup) property: ```javascript 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: - [Layout Group](https://playcanvas.github.io/#/user-interface/layout-group) ## Accessors ### alignment ```ts get alignment(): Vec2 set alignment(value: Vec2) ``` Gets the horizontal and vertical alignment of child elements. ### heightFitting ```ts get heightFitting(): number set heightFitting(value: number) ``` Gets the height fitting mode to be applied when positioning and scaling child elements. ### orientation ```ts get orientation(): number set orientation(value: number) ``` Gets whether the layout should run horizontally or vertically. ### padding ```ts get padding(): Vec4 set padding(value: Vec4) ``` Gets the padding to be applied inside the container before positioning any children. ### reverseX ```ts get reverseX(): boolean set reverseX(value: boolean) ``` Gets whether to reverse the order of children along the x axis. ### reverseY ```ts get reverseY(): boolean set reverseY(value: boolean) ``` Gets whether to reverse the order of children along the y axis. ### spacing ```ts get spacing(): Vec2 set spacing(value: Vec2) ``` Gets the spacing to be applied between each child element. ### widthFitting ```ts get widthFitting(): number set widthFitting(value: number) ``` Gets the width fitting mode to be applied when positioning and scaling child elements. ### wrap ```ts 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. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/LayoutGroupComponentSystem.md # LayoutGroupComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/system.js#L36 Manages the [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md)s of an application. Reach it through `app.systems.layoutgroup`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScreenComponent.md # ScreenComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/component.js#L56 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](https://api.playcanvas.com/engine/classes/ScreenComponent.md#screenspace). It is possible to create an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) hierarchy underneath an Entity with a ScreenComponent to create complex user interfaces using the following components: - [ButtonComponent](https://api.playcanvas.com/engine/classes/ButtonComponent.md) - [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) - [LayoutChildComponent](https://api.playcanvas.com/engine/classes/LayoutChildComponent.md) - [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.md) - [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md) - [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.md) You should never need to use the ScreenComponent constructor directly. To add a ScreenComponent to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#screen) property: ```javascript 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: - [Screen Space Screen](https://playcanvas.github.io/#/user-interface/screen-scaling) - [World Space Screen](https://playcanvas.github.io/#/user-interface/world-ui) ## Properties ### cull ```ts cull: boolean = false ``` If true, then elements inside this screen will not be rendered when outside of the screen (only valid when [screenSpace](https://api.playcanvas.com/engine/classes/ScreenComponent.md#screenspace) is true). ## Accessors ### priority ```ts get priority(): number set priority(value: number) ``` Gets the screen's render priority. ### referenceResolution ```ts get referenceResolution(): Vec2 set referenceResolution(value: Vec2) ``` Gets the resolution that the ScreenComponent is designed for. ### resolution ```ts get resolution(): Vec2 set resolution(value: Vec2) ``` Gets the width and height of the ScreenComponent. ### scaleBlend ```ts get scaleBlend(): number set scaleBlend(value: number) ``` Gets the scale blend. ### scaleMode ```ts get scaleMode(): string set scaleMode(value: string) ``` Gets the scale mode. ### screenSpace ```ts get screenSpace(): boolean set screenSpace(value: boolean) ``` Gets whether the ScreenComponent will render its child [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s in screen space instead of world space. ## Methods ### syncDrawOrder ```ts syncDrawOrder(): void ``` Set the drawOrder of each child [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) 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. ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScreenComponentSystem.md # ScreenComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/system.js#L31 Manages the [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md)s of an application. Reach it through `app.systems.screen`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScrollbarComponent.md # ScrollbarComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scrollbar/component.js#L63 The ScrollbarComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to behave like a draggable scrollbar. It is typically used together with a [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.md) 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](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent). A draggable scrollbar requires a child handle entity with an input-enabled [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md), wired up via the scrollbar's [handleEntity](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md#handleentity) property: ```javascript // 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](https://api.playcanvas.com/engine/classes/Entity.md#scrollbar) property: ```javascript 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: - [Slider](https://playcanvas.github.io/#/user-interface/common-widgets) ## Accessors ### handleEntity ```ts get handleEntity(): Entity | null set handleEntity(arg: Entity | null) ``` Gets the entity to be used as the scrollbar handle. ### handleSize ```ts get handleSize(): number set handleSize(arg: number) ``` Gets the size of the handle relative to the size of the track. ### orientation ```ts get orientation(): number set orientation(arg: number) ``` Gets whether the scrollbar moves horizontally or vertically. ### value ```ts get value(): number set value(arg: number) ``` Gets the current position value of the scrollbar. ## Events ### EVENT_SETVALUE ```ts static EVENT_SETVALUE: string = 'set:value' ``` Fired whenever the scroll value changes. The handler is passed a number representing the current scroll value. **Example** ```ts entity.scrollbar.on('set:value', (value) => { console.log(`Scroll value is now ${value}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScrollbarComponentSystem.md # ScrollbarComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scrollbar/system.js#L17 Manages the [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md)s of an application. Reach it through `app.systems.scrollbar`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScrollViewComponent.md # ScrollViewComponent Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/component.js#L59 The ScrollViewComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) 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 [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.md)s. You should never need to use the ScrollViewComponent constructor directly. To add a ScrollViewComponent to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent): ```javascript 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](https://api.playcanvas.com/engine/classes/Entity.md#scrollview) property: ```javascript 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: - [Scroll View](https://playcanvas.github.io/#/user-interface/scroll-view) ## Accessors ### bounceAmount ```ts get bounceAmount(): number set bounceAmount(arg: number) ``` Gets how far the content should move before bouncing back. ### contentEntity ```ts get contentEntity(): Entity | null set contentEntity(arg: Entity | null) ``` Gets the entity which contains the scrolling content itself. ### friction ```ts get friction(): number set friction(arg: number) ``` Gets how freely the content should move if thrown. ### horizontal ```ts get horizontal(): boolean set horizontal(arg: boolean) ``` Gets whether horizontal scrolling is enabled. ### horizontalScrollbarEntity ```ts get horizontalScrollbarEntity(): Entity | null set horizontalScrollbarEntity(arg: Entity | null) ``` Gets the entity to be used as the horizontal scrollbar. ### horizontalScrollbarVisibility ```ts 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. ### mouseWheelSensitivity ```ts get mouseWheelSensitivity(): Vec2 set mouseWheelSensitivity(arg: Vec2) ``` Gets the mouse wheel horizontal and vertical sensitivity. ### scroll ```ts get scroll(): Vec2 set scroll(value: Vec2) ``` Gets the scroll value. ### scrollMode ```ts get scrollMode(): number set scrollMode(arg: number) ``` Gets the scroll mode of the scroll viewer. ### useMouseWheel ```ts get useMouseWheel(): boolean set useMouseWheel(arg: boolean) ``` Gets whether to use mouse wheel for scrolling (horizontally and vertically). ### vertical ```ts get vertical(): boolean set vertical(arg: boolean) ``` Gets whether vertical scrolling is enabled. ### verticalScrollbarEntity ```ts get verticalScrollbarEntity(): Entity | null set verticalScrollbarEntity(arg: Entity | null) ``` Gets the entity to be used as the vertical scrollbar. ### verticalScrollbarVisibility ```ts 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. ### viewportEntity ```ts 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. ## Events ### EVENT_SETSCROLL ```ts static EVENT_SETSCROLL: string = 'set:scroll' ``` Fired whenever the scroll position changes. The handler is passed a [Vec2](https://api.playcanvas.com/engine/classes/Vec2.md) containing the horizontal and vertical scroll values in the range 0..1. **Example** ```ts entity.scrollview.on('set:scroll', (scroll) => { console.log(`Horizontal scroll position: ${scroll.x}`); console.log(`Vertical scroll position: ${scroll.y}`); }); ``` ## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md) - `entity: Entity` - `system: ComponentSystem` - `get 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): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/ScrollViewComponentSystem.md # ScrollViewComponentSystem Class · extends [`ComponentSystem`](https://api.playcanvas.com/engine/classes/ComponentSystem.md) · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/system.js#L50 Manages the [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.md)s of an application. Reach it through `app.systems.scrollview`; components are created with [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent), never by calling the system directly. ## Inherited from [ComponentSystem](https://api.playcanvas.com/engine/classes/ComponentSystem.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrAnchor.md # XrAnchor Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L34 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. ## Accessors ### persistent ```ts get persistent(): boolean ``` Gets whether an anchor is persistent. ### uuid ```ts get uuid(): string | null ``` Gets the UUID string of a persisted anchor or null if the anchor is not persisted. ## Methods ### destroy ```ts destroy(): void ``` Destroy an anchor. ### forget ```ts 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`](https://api.playcanvas.com/engine/types/XrAnchorForgetCallback.md), optional): Optional callback function to be called when the anchor has been forgotten or if an error occurs. **Example** ```ts // 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 ```ts getPosition(): Vec3 ``` Get the world space position of an anchor. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space position of an anchor. ### getRotation ```ts getRotation(): Quat ``` Get the world space rotation of an anchor. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): The world space rotation of an anchor. ### persist ```ts 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`](https://api.playcanvas.com/engine/types/XrAnchorPersistCallback.md), optional): Optional callback function to be called when the persistent UUID has been generated or if an error occurs. **Example** ```ts // 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); } }); ``` ## Events ### EVENT_CHANGE ```ts static EVENT_CHANGE: string = 'change' ``` Fired when an anchor's position and/or rotation is changed. **Example** ```ts anchor.on('change', () => { // anchor has been updated entity.setPosition(anchor.getPosition()); entity.setRotation(anchor.getRotation()); }); ``` ### EVENT_DESTROY ```ts static EVENT_DESTROY: string = 'destroy' ``` Fired when an anchor is destroyed. **Example** ```ts // once anchor is destroyed anchor.once('destroy', () => { // destroy its related entity entity.destroy(); }); ``` ### EVENT_FORGET ```ts static EVENT_FORGET: string = 'forget' ``` Fired when an anchor has been forgotten. **Example** ```ts anchor.on('forget', () => { // anchor has been forgotten }); ``` ### EVENT_PERSIST ```ts 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** ```ts anchor.on('persist', (uuid) => { // anchor has been persisted }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrAnchors.md # XrAnchors Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchors.js#L35 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. ```javascript app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { anchors: true }); ``` ## Accessors ### available ```ts get available(): boolean ``` True if Anchors are available. This information is available only when session has started. ### list ```ts get list(): XrAnchor[] ``` List of available [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.md)s. ### persistence ```ts get persistence(): boolean ``` True if Anchors support persistence. ### supported ```ts get supported(): boolean ``` True if Anchors are supported. ### uuids ```ts get uuids(): string[] | null ``` Array of UUID strings of persistent anchors, or null if not available. ## Methods ### create ```ts 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`](https://api.playcanvas.com/engine/classes/Vec3.md)): Position for an anchor or a hit test result. - `rotation` ([`Quat`](https://api.playcanvas.com/engine/classes/Quat.md) `|` [`XrAnchorCreateCallback`](https://api.playcanvas.com/engine/types/XrAnchorCreateCallback.md), optional): Rotation for an anchor or a callback if creating from a hit test result. - `callback` ([`XrAnchorCreateCallback`](https://api.playcanvas.com/engine/types/XrAnchorCreateCallback.md), optional): Callback to fire when anchor was created or failed to be created. **Example** ```ts // create an anchor using a position and rotation app.xr.anchors.create(position, rotation, (err, anchor) => { if (!err) { // new anchor has been created } }); ``` **Example** ```ts // 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 ```ts 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`](https://api.playcanvas.com/engine/types/XrAnchorForgetCallback.md), optional): Callback to fire when anchor persistent data was removed or error if failed. **Example** ```ts // 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 ```ts restore(uuid: string, callback?: XrAnchorCreateCallback): void ``` Restore anchor using persistent UUID. **Parameters** - `uuid` (`string`): UUID string associated with persistent anchor. - `callback` ([`XrAnchorCreateCallback`](https://api.playcanvas.com/engine/types/XrAnchorCreateCallback.md), optional): Callback to fire when anchor was created or failed to be created. **Example** ```ts // restore an anchor using uuid string app.xr.anchors.restore(uuid, (err, anchor) => { if (!err) { // new anchor has been created } }); ``` **Example** ```ts // 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]); } ``` ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired when a new [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.md) is added. The handler is passed the [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.md) that was added. **Example** ```ts app.xr.anchors.on('add', (anchor) => { console.log('Anchor added'); }); ``` ### EVENT_AVAILABLE ```ts static EVENT_AVAILABLE: string = 'available' ``` Fired when anchors become available. **Example** ```ts app.xr.anchors.on('available', () => { console.log('Anchors are available'); }); ``` ### EVENT_DESTROY ```ts static EVENT_DESTROY: string = 'destroy' ``` Fired when an [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.md) is destroyed. The handler is passed the [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.md) that was destroyed. **Example** ```ts app.xr.anchors.on('destroy', (anchor) => { console.log('Anchor destroyed'); }); ``` ### EVENT_ERROR ```ts static EVENT_ERROR: string = 'error' ``` Fired when an anchor failed to be created. The handler is passed an Error object. **Example** ```ts app.xr.anchors.on('error', (err) => { console.error(err.message); }); ``` ### EVENT_UNAVAILABLE ```ts static EVENT_UNAVAILABLE: string = 'unavailable' ``` Fired when anchors become unavailable. **Example** ```ts app.xr.anchors.on('unavailable', () => { console.log('Anchors are unavailable'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrDomOverlay.md # XrDomOverlay Class · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-dom-overlay.js#L30 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. ```javascript app.xr.domOverlay.root = element; app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR); ``` ```javascript // 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(); }); ``` ## Accessors ### available ```ts 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. ### root ```ts get root(): Element | null set root(value: Element | null) ``` Gets the DOM element to be used as the root for DOM Overlay. ### state ```ts 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. ### supported ```ts get supported(): boolean ``` True if DOM Overlay is supported. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrFinger.md # XrFinger Class · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-finger.js#L11 Represents a finger of a tracked [XrHand](https://api.playcanvas.com/engine/classes/XrHand.md) with related joints and index. ## Accessors ### hand ```ts get hand(): XrHand ``` Gets the hand that the finger belongs to. ### index ```ts get index(): number ``` Gets the index of the finger. Enumeration is: thumb, index, middle, ring, little. ### joints ```ts 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. ### tip ```ts get tip(): XrJoint | null ``` Tip joint of the finger, or null if not available. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrHand.md # XrHand Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hand.js#L37 Represents a hand with fingers and joints. ## Accessors ### fingers ```ts get fingers(): XrFinger[] ``` Array of fingers of the hand. ### joints ```ts get joints(): XrJoint[] ``` Array of joints in the hand. ### tips ```ts get tips(): XrJoint[] ``` Array of joints that are fingertips. ### tracking ```ts get tracking(): boolean ``` True if tracking is available, otherwise tracking might be lost. ### wrist ```ts get wrist(): XrJoint | null ``` Wrist of a hand, or null if it is not available by WebXR underlying system. ## Methods ### getJointById ```ts 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`](https://api.playcanvas.com/engine/classes/XrJoint.md) `| null`: Joint or null if not available. ## Events ### EVENT_TRACKING ```ts static EVENT_TRACKING: string = 'tracking' ``` Fired when tracking becomes available. **Example** ```ts hand.on('tracking', () => { console.log('Hand tracking is available'); }); ``` ### EVENT_TRACKINGLOST ```ts static EVENT_TRACKINGLOST: string = 'trackinglost' ``` Fired when tracking is lost. **Example** ```ts hand.on('trackinglost', () => { console.log('Hand tracking is lost'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrHitTest.md # XrHitTest Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test.js#L28 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. ## Properties ### sources ```ts sources: XrHitTestSource[] = [] ``` List of active [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md). ## Accessors ### available ```ts get available(): boolean ``` True if Hit Test is available. This information is available only when the session has started. ### supported ```ts get supported(): boolean ``` True if AR Hit Test is supported. ## Methods ### start ```ts 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`](https://api.playcanvas.com/engine/types/XrHitTestStartCallback.md), 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](https://api.playcanvas.com/engine/variables/XRTRACKABLE_PLANE.md) ]. Can be any combination of the following: - [XRTRACKABLE_POINT](https://api.playcanvas.com/engine/variables/XRTRACKABLE_POINT.md): Point - indicates that the hit test results will be computed based on the feature points detected by the underlying Augmented Reality system. - [XRTRACKABLE_PLANE](https://api.playcanvas.com/engine/variables/XRTRACKABLE_PLANE.md): Plane - indicates that the hit test results will be computed based on the planes detected by the underlying Augmented Reality system. - [XRTRACKABLE_MESH](https://api.playcanvas.com/engine/variables/XRTRACKABLE_MESH.md): Mesh - indicates that the hit test results will be computed based on the meshes detected by the underlying Augmented Reality system. - `options.offsetRay` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md), 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](https://api.playcanvas.com/engine/classes/XrInputSource.md) should be provided. - `options.spaceType` (`string`, optional): Reference space type. Defaults to [XRSPACE_VIEWER](https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md). Can be one of the following: - [XRSPACE_VIEWER](https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md): Viewer - hit test will be facing relative to viewers space. - [XRSPACE_LOCAL](https://api.playcanvas.com/engine/variables/XRSPACE_LOCAL.md): Local - represents a tracking space with a native origin near the viewer at the time of creation. - [XRSPACE_LOCALFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_LOCALFLOOR.md): 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. Floor level value might be estimated by the underlying platform. - [XRSPACE_BOUNDEDFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_BOUNDEDFLOOR.md): 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. - [XRSPACE_UNBOUNDED](https://api.playcanvas.com/engine/variables/XRSPACE_UNBOUNDED.md): Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially long distances from their starting point. **Example** ```ts // 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** ```ts // 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** ```ts // 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 }); } }); ``` ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired when new [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) is added to the list. The handler is passed the [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) object that has been added. **Example** ```ts app.xr.hitTest.on('add', (hitTestSource) => { // new hit test source is added }); ``` ### EVENT_AVAILABLE ```ts static EVENT_AVAILABLE: string = 'available' ``` Fired when hit test becomes available. **Example** ```ts app.xr.hitTest.on('available', () => { console.log('Hit Testing is available'); }); ``` ### EVENT_ERROR ```ts static EVENT_ERROR: string = 'error' ``` Fired when failed create hit test source. The handler is passed the Error object. **Example** ```ts app.xr.hitTest.on('error', (err) => { console.error(err.message); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) is removed to the list. The handler is passed the [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) object that has been removed. **Example** ```ts app.xr.hitTest.on('remove', (hitTestSource) => { // hit test source is removed }); ``` ### EVENT_RESULT ```ts 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](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) that produced the hit result, the [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) position, the [Quat](https://api.playcanvas.com/engine/classes/Quat.md) rotation and the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) (if it is a transient hit test source). **Example** ```ts app.xr.hitTest.on('result', (hitTestSource, position, rotation, inputSource) => { target.setPosition(position); target.setRotation(rotation); }); ``` ### EVENT_UNAVAILABLE ```ts static EVENT_UNAVAILABLE: string = 'unavailable' ``` Fired when hit test becomes unavailable. **Example** ```ts app.xr.hitTest.on('unavailable', () => { console.log('Hit Testing is unavailable'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrHitTestSource.md # XrHitTestSource Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test-source.js#L40 Represents XR hit test source, which provides access to hit results of real world geometry from AR session. ```javascript // 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 }); } }); ``` ## Methods ### remove ```ts remove(): void ``` Stop and remove hit test source. ## Events ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) is removed. **Example** ```ts hitTestSource.once('remove', () => { // hit test source has been removed }); ``` ### EVENT_RESULT ```ts 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](https://api.playcanvas.com/engine/classes/Vec3.md) position, the [Quat](https://api.playcanvas.com/engine/classes/Quat.md) rotation, the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) (if it is a transient hit test source) and the [XRHitTestResult](https://developer.mozilla.org/en-US/docs/Web/API/XRHitTestResult) object that is created by WebXR API. **Example** ```ts hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => { target.setPosition(position); target.setRotation(rotation); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrImageTracking.md # XrImageTracking Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-image-tracking.js#L17 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. ## Accessors ### available ```ts 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. ### images ```ts get images(): XrTrackedImage[] ``` List of [XrTrackedImage](https://api.playcanvas.com/engine/classes/XrTrackedImage.md) that contain tracking information. ### supported ```ts get supported(): boolean ``` True if Image Tracking is supported. ## Methods ### add ```ts 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`](https://api.playcanvas.com/engine/classes/XrTrackedImage.md) `| 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** ```ts // image of a book cover that has width of 20cm (0.2m) app.xr.imageTracking.add(bookCoverImg, 0.2); ``` ### remove ```ts remove(trackedImage: XrTrackedImage): void ``` Remove an image from image tracking. **Parameters** - `trackedImage` ([`XrTrackedImage`](https://api.playcanvas.com/engine/classes/XrTrackedImage.md)): Tracked image to be removed. Modifying the tracked images list is only possible before an AR session is started. ## Events ### EVENT_ERROR ```ts 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** ```ts app.xr.imageTracking.on('error', (err) => { console.error(err.message); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrInput.md # XrInput Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-input.js#L20 Provides access to input sources for WebXR. Input sources represent: - hand held controllers - and their optional capabilities: gamepad and vibration - hands - with their individual joints - transient sources - such as touch screen taps and voice commands ## Accessors ### inputSources ```ts get inputSources(): XrInputSource[] ``` List of active [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) instances. ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired when a new [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) is added to the list. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that has been added. **Example** ```ts app.xr.input.on('add', (inputSource) => { // new input source is added }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when an [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) is removed from the list. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that has been removed. **Example** ```ts app.xr.input.on('remove', (inputSource) => { // input source is removed }); ``` ### EVENT_SELECT ```ts static EVENT_SELECT: string = 'select' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has triggered primary action. This could be pressing a trigger button, or touching a screen. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `select` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts 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 } }); ``` ### EVENT_SELECTEND ```ts static EVENT_SELECTEND: string = 'selectend' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has ended triggering primary action. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `selectend` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts app.xr.input.on('selectend', (inputSource, evt) => { console.log('Select ended'); }); ``` ### EVENT_SELECTSTART ```ts static EVENT_SELECTSTART: string = 'selectstart' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has started to trigger primary action. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `selectstart` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts app.xr.input.on('selectstart', (inputSource, evt) => { console.log('Select started'); }); ``` ### EVENT_SQUEEZE ```ts static EVENT_SQUEEZE: string = 'squeeze' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has triggered squeeze action. This is associated with "grabbing" action on the controllers. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `squeeze` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts app.xr.input.on('squeeze', (inputSource, evt) => { console.log('Squeeze'); }); ``` ### EVENT_SQUEEZEEND ```ts static EVENT_SQUEEZEEND: string = 'squeezeend' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has ended triggering squeeze action. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `squeezeend` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts app.xr.input.on('squeezeend', (inputSource, evt) => { console.log('Squeeze ended'); }); ``` ### EVENT_SQUEEZESTART ```ts static EVENT_SQUEEZESTART: string = 'squeezestart' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) has started to trigger squeeze action. The handler is passed the [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) that triggered the `squeezestart` event and the XRInputSourceEvent event from the WebXR API. **Example** ```ts app.xr.input.on('squeezestart', (inputSource, evt) => { if (obj.containsPoint(inputSource.getPosition())) { // grabbed an object } }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrInputSource.md # XrInputSource Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-input-source.js#L29 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. ## Accessors ### elementEntity ```ts get elementEntity(): Entity | null ``` If [elementInput](https://api.playcanvas.com/engine/classes/XrInputSource.md#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. ### elementInput ```ts get elementInput(): boolean set elementInput(value: boolean) ``` Gets whether the input source can interact with [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. ### gamepad ```ts get gamepad(): Gamepad | null ``` If input source has buttons, triggers, thumbstick or touchpad, then this object provides access to its states. ### grip ```ts 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. ### hand ```ts get hand(): XrHand | null ``` If input source is a tracked hand, then it will point to [XrHand](https://api.playcanvas.com/engine/classes/XrHand.md) otherwise it is null. ### handedness ```ts get handedness(): string ``` Describes which hand input source is associated with. Can be one of the following: - [XRHAND_NONE](https://api.playcanvas.com/engine/variables/XRHAND_NONE.md): None - input source is not meant to be held in hands. - [XRHAND_LEFT](https://api.playcanvas.com/engine/variables/XRHAND_LEFT.md): Left - indicates that input source is meant to be held in left hand. - [XRHAND_RIGHT](https://api.playcanvas.com/engine/variables/XRHAND_RIGHT.md): Right - indicates that input source is meant to be held in right hand. ### hitTestSources ```ts get hitTestSources(): XrHitTestSource[] ``` List of active [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) instances associated with this input source. ### id ```ts get id(): number ``` Unique number associated with instance of input source. Same physical devices when reconnected will not share this ID. ### inputSource ```ts get inputSource(): XRInputSource ``` XRInputSource object that is associated with this input source. ### profiles ```ts get profiles(): string[] ``` List of input profile names indicating both the preferred visual representation and behavior of the input source. ### selecting ```ts get selecting(): boolean ``` True if input source is in active primary action between selectstart and selectend events. ### squeezing ```ts get squeezing(): boolean ``` True if input source is in active squeeze action between squeezestart and squeezeend events. ### targetRayMode ```ts get targetRayMode(): string ``` Type of ray Input Device is based on. Can be one of the following: - [XRTARGETRAY_GAZE](https://api.playcanvas.com/engine/variables/XRTARGETRAY_GAZE.md): 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. - [XRTARGETRAY_SCREEN](https://api.playcanvas.com/engine/variables/XRTARGETRAY_SCREEN.md): 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. - [XRTARGETRAY_POINTER](https://api.playcanvas.com/engine/variables/XRTARGETRAY_POINTER.md): 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. ## Methods ### getDirection ```ts getDirection(): Vec3 ``` Get the world space direction of input source ray. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space direction of input source ray. ### getLinearVelocity ```ts getLinearVelocity(): Vec3 | null ``` Get the linear velocity (units per second) of the input source if it is handheld ([grip](https://api.playcanvas.com/engine/classes/XrInputSource.md#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`](https://api.playcanvas.com/engine/classes/Vec3.md) `| null`: The world space linear velocity of the handheld input source. ### getLocalPosition ```ts getLocalPosition(): Vec3 | null ``` Get the local space position of input source if it is handheld ([grip](https://api.playcanvas.com/engine/classes/XrInputSource.md#grip) is true). Local space is relative to parent of the XR camera. Otherwise it will return null. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md) `| null`: The local space position of handheld input source. ### getLocalRotation ```ts getLocalRotation(): Quat | null ``` Get the local space rotation of input source if it is handheld ([grip](https://api.playcanvas.com/engine/classes/XrInputSource.md#grip) is true). Local space is relative to parent of the XR camera. Otherwise it will return null. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md) `| null`: The local space rotation of handheld input source. ### getOrigin ```ts getOrigin(): Vec3 ``` Get the world space origin of input source ray. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space origin of input source ray. ### getPosition ```ts getPosition(): Vec3 | null ``` Get the world space position of input source if it is handheld ([grip](https://api.playcanvas.com/engine/classes/XrInputSource.md#grip) is true). Otherwise it will return null. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md) `| null`: The world space position of handheld input source. ### getRotation ```ts getRotation(): Quat | null ``` Get the world space rotation of input source if it is handheld ([grip](https://api.playcanvas.com/engine/classes/XrInputSource.md#grip) is true). Otherwise it will return null. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md) `| null`: The world space rotation of handheld input source. ### hitTestStart ```ts 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`](https://api.playcanvas.com/engine/types/XrHitTestStartCallback.md), 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](https://api.playcanvas.com/engine/variables/XRTRACKABLE_PLANE.md)]. Can be any combination of the following: - [XRTRACKABLE_POINT](https://api.playcanvas.com/engine/variables/XRTRACKABLE_POINT.md): Point - indicates that the hit test results will be computed based on the feature points detected by the underlying Augmented Reality system. - [XRTRACKABLE_PLANE](https://api.playcanvas.com/engine/variables/XRTRACKABLE_PLANE.md): Plane - indicates that the hit test results will be computed based on the planes detected by the underlying Augmented Reality system. - [XRTRACKABLE_MESH](https://api.playcanvas.com/engine/variables/XRTRACKABLE_MESH.md): Mesh - indicates that the hit test results will be computed based on the meshes detected by the underlying Augmented Reality system. - `options.offsetRay` ([`Ray`](https://api.playcanvas.com/engine/classes/Ray.md), optional): Optional ray by which hit test ray can be offset. **Example** ```ts 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 }); } }); }); ``` ## Events ### EVENT_HITTESTADD ```ts static EVENT_HITTESTADD: string = 'hittest:add' ``` Fired when new [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) is added to the input source. The handler is passed the [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) object that has been added. **Example** ```ts inputSource.on('hittest:add', (hitTestSource) => { // new hit test source is added }); ``` ### EVENT_HITTESTREMOVE ```ts static EVENT_HITTESTREMOVE: string = 'hittest:remove' ``` Fired when [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) is removed from the input source. The handler is passed the [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) object that has been removed. **Example** ```ts inputSource.on('hittest:remove', (hitTestSource) => { // hit test source is removed }); ``` ### EVENT_HITTESTRESULT ```ts 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](https://api.playcanvas.com/engine/classes/XrHitTestSource.md) object that produced the hit result, the [Vec3](https://api.playcanvas.com/engine/classes/Vec3.md) position, the [Quat](https://api.playcanvas.com/engine/classes/Quat.md) rotation and the [XRHitTestResult](https://developer.mozilla.org/en-US/docs/Web/API/XRHitTestResult) object that is created by the WebXR API. **Example** ```ts inputSource.on('hittest:result', (hitTestSource, position, rotation, hitTestResult) => { target.setPosition(position); target.setRotation(rotation); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.md) is removed. **Example** ```ts inputSource.once('remove', () => { // input source is not available anymore }); ``` ### EVENT_SELECT ```ts 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](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts const ray = new Ray(); inputSource.on('select', (evt) => { ray.set(inputSource.getOrigin(), inputSource.getDirection()); if (obj.intersectsRay(ray)) { // selected an object with input source } }); ``` ### EVENT_SELECTEND ```ts static EVENT_SELECTEND: string = 'selectend' ``` Fired when input source has ended triggering primary action. The handler is passed an [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts inputSource.on('selectend', (evt) => { console.log('Select ended'); }); ``` ### EVENT_SELECTSTART ```ts static EVENT_SELECTSTART: string = 'selectstart' ``` Fired when input source has started to trigger primary action. The handler is passed an [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts inputSource.on('selectstart', (evt) => { console.log('Select started'); }); ``` ### EVENT_SQUEEZE ```ts 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](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts inputSource.on('squeeze', (evt) => { console.log('Squeeze'); }); ``` ### EVENT_SQUEEZEEND ```ts static EVENT_SQUEEZEEND: string = 'squeezeend' ``` Fired when input source has ended triggering squeeze action. The handler is passed an [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts inputSource.on('squeezeend', (evt) => { console.log('Squeeze ended'); }); ``` ### EVENT_SQUEEZESTART ```ts static EVENT_SQUEEZESTART: string = 'squeezestart' ``` Fired when input source has started to trigger squeeze action. The handler is passed an [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) object from the WebXR API. **Example** ```ts inputSource.on('squeezestart', (evt) => { if (obj.containsPoint(inputSource.getPosition())) { // grabbed an object } }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrJoint.md # XrJoint Class · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-joint.js#L30 Represents the joint of a finger. ## Accessors ### finger ```ts get finger(): XrFinger | null ``` Finger that joint relates to. ### hand ```ts get hand(): XrHand ``` Hand that joint relates to. ### id ```ts get id(): XRHandJoint ``` Id of a joint based on WebXR Hand Input Specs. ### index ```ts 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. ### radius ```ts get radius(): number ``` The radius of a joint, which is a distance from joint to the edge of a skin. ### tip ```ts get tip(): boolean ``` True if joint is a tip of a finger. ### wrist ```ts get wrist(): boolean ``` True if joint is a wrist. ## Methods ### getPosition ```ts getPosition(): Vec3 ``` Get the world space position of a joint. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space position of a joint. ### getRotation ```ts getRotation(): Quat ``` Get the world space rotation of a joint. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): The world space rotation of a joint. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrLightEstimation.md # XrLightEstimation Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-light-estimation.js#L26 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. ## Accessors ### available ```ts get available(): boolean ``` True if estimated light information is available. **Example** ```ts if (app.xr.lightEstimation.available) { entity.light.intensity = app.xr.lightEstimation.intensity; } ``` ### color ```ts get color(): Color | null ``` Color of what is estimated to be the most prominent directional light. Or null if data is not available. ### intensity ```ts get intensity(): number | null ``` Intensity of what is estimated to be the most prominent directional light. Or null if data is not available. ### rotation ```ts get rotation(): Quat | null ``` Rotation of what is estimated to be the most prominent directional light. Or null if data is not available. ### sphericalHarmonics ```ts get sphericalHarmonics(): Float32Array | null ``` Spherical harmonic coefficients of estimated ambient light. Or null if data is not available. ### supported ```ts get supported(): boolean ``` True if Light Estimation is supported. This information is available only during an active AR session. ## Methods ### end ```ts end(): void ``` End estimation of illumination data. ### start ```ts 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** ```ts app.xr.on('start', () => { if (app.xr.lightEstimation.supported) { app.xr.lightEstimation.start(); } }); ``` ## Events ### EVENT_AVAILABLE ```ts static EVENT_AVAILABLE: string = 'available' ``` Fired when light estimation data becomes available. **Example** ```ts app.xr.lightEstimation.on('available', () => { console.log('Light estimation is available'); }); ``` ### EVENT_ERROR ```ts 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** ```ts app.xr.lightEstimation.on('error', (error) => { console.error(error.message); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrManager.md # XrManager Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L69 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](https://api.playcanvas.com/engine/classes/AppBase.md) class automatically creates an instance of this class and makes it available as [AppBase#xr](https://api.playcanvas.com/engine/classes/AppBase.md#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. ## Properties ### anchors ```ts anchors: XrAnchors ``` Provides access to Anchors. ### domOverlay ```ts domOverlay: XrDomOverlay ``` Provides access to DOM overlay capabilities. ### hitTest ```ts hitTest: XrHitTest ``` Provides the ability to perform hit tests on the representation of real world geometry of the underlying AR system. ### imageTracking ```ts imageTracking: XrImageTracking ``` Provides access to image tracking capabilities. ### input ```ts input: XrInput ``` Provides access to Input Sources. ### lightEstimation ```ts lightEstimation: XrLightEstimation ``` Provides access to light estimation capabilities. ### meshDetection ```ts meshDetection: XrMeshDetection ``` Provides access to mesh detection capabilities. ### planeDetection ```ts planeDetection: XrPlaneDetection ``` Provides access to plane detection capabilities. ### views ```ts views: XrViews ``` Provides access to views and their capabilities. ## Accessors ### active ```ts get active(): boolean ``` True if XR session is running. ### camera ```ts get camera(): Entity | null ``` Active camera for which XR session is running or null. ### fixedFoveation ```ts 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. ### framebufferScaleFactor ```ts get framebufferScaleFactor(): number ``` Framebuffer scale factor. This value is read-only and can only be set when starting a new XR session. ### frameRate ```ts get frameRate(): number | null ``` XR session frameRate or null if this information is not available. This value can change during an active XR session. ### graphicsBinding ```ts 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). ### session ```ts get session(): XRSession | null ``` Provides access to XRSession of WebXR. ### spaceType ```ts 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_*. ### supported ```ts get supported(): boolean ``` True if XR is supported. ### supportedFrameRates ```ts get supportedFrameRates(): number[] | null ``` List of supported frame rates, or null if this data is not available. ### type ```ts get type(): string | null ``` Returns type of currently running XR session or null if no session is running. Can be any of XRTYPE_*. ## Methods ### end ```ts end(callback?: XrErrorCallback): void ``` Attempts to end XR session and optionally fires callback when session is ended or failed to end. **Parameters** - `callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), optional): Optional callback function called once session is ended. The callback has one argument Error - it is null if successfully ended XR session. **Example** ```ts app.keyboard.on('keydown', (evt) => { if (evt.key === KEY_ESCAPE && app.xr.active) { app.xr.end(); } }); ``` ### initiateRoomCapture ```ts 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`](https://api.playcanvas.com/engine/types/XrRoomCaptureCallback.md)): Callback that will be fired once capture is complete or failed. **Example** ```ts this.app.xr.initiateRoomCapture((err) => { if (err) { // capture failed return; } // capture was successful }); ``` ### isAvailable ```ts isAvailable(type: string): boolean ``` Check if the specified type of session is available. **Parameters** - `type` (`string`): Session type. Can be one of the following: - [XRTYPE_INLINE](https://api.playcanvas.com/engine/variables/XRTYPE_INLINE.md): Inline - always available type of session. It has limited features availability and is rendered into HTML element. - [XRTYPE_VR](https://api.playcanvas.com/engine/variables/XRTYPE_VR.md): Immersive VR - session that provides exclusive access to VR device with best available tracking features. - [XRTYPE_AR](https://api.playcanvas.com/engine/variables/XRTYPE_AR.md): Immersive AR - session that provides exclusive access to VR/AR device that is intended to be blended with real-world environment. **Returns** `boolean`: True if the specified session type is available. **Example** ```ts if (app.xr.isAvailable(XRTYPE_VR)) { // VR is available } ``` ### start ```ts start(camera: CameraComponent, type: string, spaceType: string, options?: object): void ``` Attempts to start XR session for provided [CameraComponent](https://api.playcanvas.com/engine/classes/CameraComponent.md) 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`](https://api.playcanvas.com/engine/classes/CameraComponent.md)): It will be used to render XR session and manipulated based on pose tracking. - `type` (`string`): Session type. Can be one of the following: - [XRTYPE_INLINE](https://api.playcanvas.com/engine/variables/XRTYPE_INLINE.md): Inline - always available type of session. It has limited features availability and is rendered into HTML element. - [XRTYPE_VR](https://api.playcanvas.com/engine/variables/XRTYPE_VR.md): Immersive VR - session that provides exclusive access to VR device with best available tracking features. - [XRTYPE_AR](https://api.playcanvas.com/engine/variables/XRTYPE_AR.md): Immersive AR - session that provides exclusive access to VR/AR device that is intended to be blended with real-world environment. - `spaceType` (`string`): Reference space type. Can be one of the following: - [XRSPACE_VIEWER](https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md): Viewer - always supported space with some basic tracking capabilities. - [XRSPACE_LOCAL](https://api.playcanvas.com/engine/variables/XRSPACE_LOCAL.md): Local - represents a tracking space with a native origin near the viewer at the time of creation. It is meant for seated or basic local XR sessions. - [XRSPACE_LOCALFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_LOCALFLOOR.md): 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. Floor level value might be estimated by the underlying platform. It is meant for seated or basic local XR sessions. - [XRSPACE_BOUNDEDFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_BOUNDEDFLOOR.md): 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. - [XRSPACE_UNBOUNDED](https://api.playcanvas.com/engine/variables/XRSPACE_UNBOUNDED.md): Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially long distances from their starting point. - `options` (`object`, optional): Object with additional options for XR session initialization. - `options.anchors` (`boolean`, optional): Set to true to attempt to enable [XrAnchors](https://api.playcanvas.com/engine/classes/XrAnchors.md). - `options.callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), 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](https://api.playcanvas.com/engine/classes/XrImageTracking.md). - `options.meshDetection` (`boolean`, optional): Set to true to attempt to enable [XrMeshDetection](https://api.playcanvas.com/engine/classes/XrMeshDetection.md). - `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](https://api.playcanvas.com/engine/classes/XrPlaneDetection.md). **Example** ```ts button.on('click', () => { app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR); }); ``` **Example** ```ts button.on('click', () => { app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { anchors: true, imageTracking: true, depthSensing: { } }); }); ``` ### updateTargetFrameRate ```ts 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. ### isDeviceSupported ```ts static isDeviceSupported(deviceType: string, type: string): Promise ``` Tests whether an immersive WebXR session of the given type can run on the specified graphics backend. Unlike [XrManager#isAvailable](https://api.playcanvas.com/engine/classes/XrManager.md#isavailable), this is a static method that can be called before a graphics device (or the [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md)) 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](https://api.playcanvas.com/engine/classes/XrManager.md#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](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md) or [DEVICETYPE_WEBGL2](https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md). - `type` (`string`): The session type. Can be: - [XRTYPE_VR](https://api.playcanvas.com/engine/variables/XRTYPE_VR.md): Immersive VR session. - [XRTYPE_AR](https://api.playcanvas.com/engine/variables/XRTYPE_AR.md): Immersive AR session. **Returns** `Promise`: Promise that resolves to true if a session of the given type is reported supported on the given backend, false otherwise. **Example** ```ts const supported = await XrManager.isDeviceSupported(DEVICETYPE_WEBGPU, XRTYPE_VR); if (supported) { // a WebGPU device can be created and used to offer VR } ``` ## Events ### EVENT_AVAILABLE ```ts 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: 1. `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. 2. `available:[type]` - Fired when availability of specific XR type is changed. The handler is passed a boolean representing the availability. **Example** ```ts app.xr.on('available', (type, available) => { console.log(`XR type ${type} is now ${available ? 'available' : 'unavailable'}`); }); ``` **Example** ```ts app.xr.on(`available:${XRTYPE_VR}`, (available) => { console.log(`XR type VR is now ${available ? 'available' : 'unavailable'}`); }); ``` ### EVENT_END ```ts static EVENT_END: string = 'end' ``` Fired when XR session is ended. While the handlers run, [XrManager#camera](https://api.playcanvas.com/engine/classes/XrManager.md#camera), [XrManager#type](https://api.playcanvas.com/engine/classes/XrManager.md#type) and [XrManager#spaceType](https://api.playcanvas.com/engine/classes/XrManager.md#spacetype) still describe the session that has ended, and they are reset once all handlers have run. **Example** ```ts app.xr.on('end', () => { // XR session has ended }); ``` ### EVENT_ERROR ```ts 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object related to failure of session start or check of session type support. **Example** ```ts app.xr.on('error', (error) => { console.error(error.message); }); ``` ### EVENT_START ```ts static EVENT_START: string = 'start' ``` Fired when XR session is started. **Example** ```ts app.xr.on('start', () => { // XR session has started }); ``` ### EVENT_UPDATE ```ts static EVENT_UPDATE: string = 'update' ``` Fired when XR session is updated, providing relevant XRFrame object. The handler is passed [XRFrame](https://developer.mozilla.org/en-US/docs/Web/API/XRFrame) object that can be used for interfacing directly with WebXR APIs. **Example** ```ts app.xr.on('update', (frame) => { console.log('XR frame updated'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrMesh.md # XrMesh Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-mesh.js#L15 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. ## Accessors ### indices ```ts get indices(): Uint32Array ``` Array of mesh indices. ### label ```ts 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 ### vertices ```ts get vertices(): Float32Array ``` Array of mesh vertices. This array contains 3 components per vertex (`x, y, z`). ## Methods ### getPosition ```ts getPosition(): Vec3 ``` Get the world space position of a mesh. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space position of a mesh. ### getRotation ```ts getRotation(): Quat ``` Get the world space rotation of a mesh. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): The world space rotation of a mesh. ## Events ### EVENT_CHANGE ```ts static EVENT_CHANGE: string = 'change' ``` Fired when [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) 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** ```ts mesh.on('change', () => { // mesh attributes have been changed }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when an [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) is removed. Its attributes, such as its vertices and label, keep their last values. **Example** ```ts mesh.once('remove', () => { // mesh is no longer available }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrMeshDetection.md # XrMeshDetection Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-mesh-detection.js#L28 Mesh Detection provides the ability to detect real world meshes based on the scanning and reconstruction by the underlying AR system. ```javascript // start session with plane detection enabled app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { meshDetection: true }); ``` ```javascript app.xr.meshDetection.on('add', (mesh) => { // new mesh been added }); ``` ## Accessors ### available ```ts get available(): boolean ``` True if Mesh Detection is available. This information is available only when session has started. ### meshes ```ts get meshes(): XrMesh[] ``` Array of [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) instances that contain transform, vertices and label information. ### supported ```ts get supported(): boolean ``` True if Mesh Detection is supported. ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired when new [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) is added to the list. The handler is passed the [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) instance that has been added. **Example** ```ts app.xr.meshDetection.on('add', (mesh) => { // a new XrMesh has been added }); ``` ### EVENT_AVAILABLE ```ts static EVENT_AVAILABLE: string = 'available' ``` Fired when mesh detection becomes available. **Example** ```ts app.xr.meshDetection.on('available', () => { console.log('Mesh detection is available'); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when a [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) is removed from the list. The handler is passed the [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.md) instance that has been removed. **Example** ```ts app.xr.meshDetection.on('remove', (mesh) => { // XrMesh has been removed }); ``` ### EVENT_UNAVAILABLE ```ts static EVENT_UNAVAILABLE: string = 'unavailable' ``` Fired when mesh detection becomes unavailable. **Example** ```ts app.xr.meshDetection.on('unavailable', () => { console.log('Mesh detection is unavailable'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrPlane.md # XrPlane Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-plane.js#L19 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](https://api.playcanvas.com/engine/classes/XrPlaneDetection.md) system. ## Accessors ### id ```ts get id(): number ``` Unique identifier of a plane. ### label ```ts 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](https://github.com/immersive-web/semantic-labels). **Example** ```ts if (plane.label === 'floor') { console.log('This plane represents the floor.'); } else if (plane.label === 'wall') { console.log('This plane represents a wall.'); } ``` ### orientation ```ts 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** ```ts 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.'); } ``` ### points ```ts 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** ```ts // 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); } ``` ## Methods ### getPosition ```ts getPosition(): Vec3 ``` Get the world space position of a plane. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space position of a plane. ### getRotation ```ts getRotation(): Quat ``` Get the world space rotation of a plane. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): The world space rotation of a plane. ## Events ### EVENT_CHANGE ```ts static EVENT_CHANGE: string = 'change' ``` Fired when [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) attributes such as: orientation and/or points have been changed. Position and rotation can change at any time without triggering a `change` event. **Example** ```ts plane.on('change', () -> { // plane has been changed }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when an [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) is removed. Its attributes, such as its points and label, keep their last values. **Example** ```ts plane.once('remove', () => { // plane is not available anymore }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrPlaneDetection.md # XrPlaneDetection Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-plane-detection.js#L28 Plane Detection provides the ability to detect real world surfaces based on estimations of the underlying AR system. ```javascript // start session with plane detection enabled app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR, { planeDetection: true }); ``` ```javascript app.xr.planeDetection.on('add', (plane) => { // new plane been added }); ``` ## Accessors ### available ```ts get available(): boolean ``` True if Plane Detection is available. This information is available only when the session has started. ### planes ```ts get planes(): XrPlane[] ``` Array of [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) instances that contain individual plane information. ### supported ```ts get supported(): boolean ``` True if Plane Detection is supported. ## Events ### EVENT_ADD ```ts static EVENT_ADD: string = 'add' ``` Fired when new [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) is added to the list. The handler is passed the [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) instance that has been added. **Example** ```ts app.xr.planeDetection.on('add', (plane) => { // new plane is added }); ``` ### EVENT_AVAILABLE ```ts static EVENT_AVAILABLE: string = 'available' ``` Fired when plane detection becomes available. **Example** ```ts app.xr.planeDetection.on('available', () => { console.log('Plane detection is available'); }); ``` ### EVENT_REMOVE ```ts static EVENT_REMOVE: string = 'remove' ``` Fired when a [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) is removed from the list. The handler is passed the [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.md) instance that has been removed. **Example** ```ts app.xr.planeDetection.on('remove', (plane) => { // new plane is removed }); ``` ### EVENT_UNAVAILABLE ```ts static EVENT_UNAVAILABLE: string = 'unavailable' ``` Fired when plane detection becomes unavailable. **Example** ```ts app.xr.planeDetection.on('unavailable', () => { console.log('Plane detection is unavailable'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrTrackedImage.md # XrTrackedImage Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-tracked-image.js#L12 The tracked image interface that is created by the Image Tracking system and is provided as a list from [XrImageTracking#images](https://api.playcanvas.com/engine/classes/XrImageTracking.md#images). It contains information about the tracking state as well as the position and rotation of the tracked image. ## Accessors ### emulated ```ts 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. ### image ```ts get image(): Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData ``` Image that is used for tracking. ### trackable ```ts get trackable(): boolean ``` True if image is trackable. A too small resolution or invalid images can be untrackable by the underlying AR system. ### tracking ```ts get tracking(): boolean ``` True if image is in tracking state and being tracked in real world by the underlying AR system. ### width ```ts get width(): number set width(value: number) ``` Get the width (in meters) of image in real world. ## Methods ### getPosition ```ts getPosition(): Vec3 ``` Get the world position of the tracked image. **Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): Position in world space. **Example** ```ts // update entity position to match tracked image position entity.setPosition(trackedImage.getPosition()); ``` ### getRotation ```ts getRotation(): Quat ``` Get the world rotation of the tracked image. **Returns** [`Quat`](https://api.playcanvas.com/engine/classes/Quat.md): Rotation in world space. **Example** ```ts // update entity rotation to match tracked image rotation entity.setRotation(trackedImage.getRotation()); ``` ## Events ### EVENT_TRACKED ```ts static EVENT_TRACKED: string = 'tracked' ``` Fired when image becomes actively tracked. **Example** ```ts trackedImage.on('tracked', () => { console.log('Image is now tracked'); }); ``` ### EVENT_UNTRACKED ```ts static EVENT_UNTRACKED: string = 'untracked' ``` Fired when image is no longer actively tracked. **Example** ```ts trackedImage.on('untracked', () => { console.log('Image is no longer tracked'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrView.md # XrView Class · extends [`RenderView`](https://api.playcanvas.com/engine/classes/RenderView.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-view.js#L18 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. ## Accessors ### depthUvMatrix ```ts 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](https://api.playcanvas.com/engine/classes/XrView.md#event_depthresize). **Example** ```ts material.setParameter('matrix_depth_uv', view.depthUvMatrix.data); ``` ### depthValueToMeters ```ts get depthValueToMeters(): number ``` Multiply this coefficient number by raw depth value to get depth in meters. **Example** ```ts material.setParameter('depth_to_meters', view.depthValueToMeters); ``` ### eye ```ts get eye(): string ``` An eye with which this view is associated. Can be any of: - [XREYE_NONE](https://api.playcanvas.com/engine/variables/XREYE_NONE.md): None - indicates a monoscopic view (likely mobile phone screen). - [XREYE_LEFT](https://api.playcanvas.com/engine/variables/XREYE_LEFT.md): Left - indicates left eye view. - [XREYE_RIGHT](https://api.playcanvas.com/engine/variables/XREYE_RIGHT.md): Right - indicates a right eye view. ### textureColor ```ts 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. ### textureDepth ```ts 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH.md), or [PIXELFORMAT_R32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) based on [XrViews#depthPixelFormat](https://api.playcanvas.com/engine/classes/XrViews.md#depthpixelformat). It is UV transformed based on the underlying AR system which can be normalized using [depthUvMatrix](https://api.playcanvas.com/engine/classes/XrView.md#depthuvmatrix). Equals to null if camera depth is not supported. **Example** ```ts // 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** ```ts // 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); } ``` ## Methods ### getDepth ```ts 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** ```ts const depth = view.getDepth(u, v); if (depth !== null) { // depth in meters } ``` ## Events ### EVENT_DEPTHRESIZE ```ts static EVENT_DEPTHRESIZE: string = 'depth:resize' ``` Fired when the depth sensing texture has been resized. The [depthUvMatrix](https://api.playcanvas.com/engine/classes/XrView.md#depthuvmatrix) needs to be updated for relevant shaders. The handler is passed the new width and height of the depth texture in pixels. **Example** ```ts view.on('depth:resize', () => { material.setParameter('matrix_depth_uv', view.depthUvMatrix); }); ``` ## Inherited from [RenderView](https://api.playcanvas.com/engine/classes/RenderView.md) - `get viewport(): Vec4` - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/classes/XrViews.md # XrViews Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-views.js#L17 Provides access to list of [XrView](https://api.playcanvas.com/engine/classes/XrView.md)s and information about their capabilities, such as support and availability of view's camera color texture, depth texture and other parameters. ## Accessors ### availableColor ```ts get availableColor(): boolean ``` Check if Camera Color is available. This information becomes available only after session has started. ### availableDepth ```ts get availableDepth(): boolean ``` Check if Camera Depth is available. This information becomes available only after session has started. ### depthGpuOptimized ```ts get depthGpuOptimized(): boolean ``` Whether the depth sensing is GPU optimized. ### depthPixelFormat ```ts get depthPixelFormat(): 2 | 15 | null ``` The depth sensing pixel format. Can be: - `PIXELFORMAT_LA8` - [PIXELFORMAT_R32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md) ### list ```ts get list(): XrView[] ``` An array of [XrView](https://api.playcanvas.com/engine/classes/XrView.md)s 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. ### supportedColor ```ts get supportedColor(): boolean ``` Check if Camera Color is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions. ### supportedDepth ```ts get supportedDepth(): boolean ``` Check if Camera Depth is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions. ## Methods ### get ```ts get(eye: string): XrView | null ``` Get an [XrView](https://api.playcanvas.com/engine/classes/XrView.md) by its associated eye constant. **Parameters** - `eye` (`string`): An XREYE_* view is associated with. Can be 'none' for monoscope views. **Returns** [`XrView`](https://api.playcanvas.com/engine/classes/XrView.md) `| null`: View or null if view of such eye is not available. ## Events ### EVENT_ADD ```ts 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](https://api.playcanvas.com/engine/classes/XrView.md) that has been added. **Example** ```ts xr.views.on('add', (view) => { console.log('View added'); }); ``` ### EVENT_REMOVE ```ts 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](https://api.playcanvas.com/engine/classes/XrView.md) that has been removed. **Example** ```ts xr.views.on('remove', (view) => { console.log('View removed'); }); ``` ## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) - `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler` - `hasEvent(name: string): boolean` - `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler` - `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle` - `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/AnimCurvePath.md # AnimCurvePath Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-curve.js#L5 ## Properties ### component ```ts component: string ``` The name of the component that owns the property, or `graph` for a transform on the entity itself. ### entityPath ```ts entityPath: string[] ``` The names of the entities from the animation root down to the target entity. ### propertyPath ```ts propertyPath: string[] ``` The property name segments, for example `['localPosition']` or `['weight.Smile']`. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ArcShapeArgs.md # ArcShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/arc-shape.js#L13 ## Properties ### ringRadius ```ts ringRadius?: number ``` The ring radius. ### sectorAngle ```ts sectorAngle?: number ``` The sector angle. ### tubeRadius ```ts tubeRadius?: number ``` The tube radius. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ArrowShapeArgs.md # ArrowShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/arrow-shape.js#L18 ## Properties ### arrowLength ```ts arrowLength?: number ``` The length of the arrow head ### arrowThickness ```ts arrowThickness?: number ``` The thickness of the arrow head ### gap ```ts gap?: number ``` The gap between the arrow base and the center ### lineLength ```ts lineLength?: number ``` The length of the line ### lineThickness ```ts lineThickness?: number ``` The thickness of the line ### tolerance ```ts tolerance?: number ``` The tolerance for intersection tests -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/AssetMap.md # AssetMap Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L65 ## Properties ### animation ```ts animation: Animation | AnimTrack ``` An animation: an [AnimTrack](https://api.playcanvas.com/engine/classes/AnimTrack.md) when loaded from a glTF or GLB file, or a legacy [Animation](https://api.playcanvas.com/engine/classes/Animation.md) when loaded from JSON. ### animclip ```ts animclip: AnimTrack ``` An animation clip. ### animstategraph ```ts animstategraph: AnimStateGraph ``` An animation state graph. ### audio ```ts audio: Sound ``` A sound. ### binary ```ts binary: ArrayBuffer ``` The raw contents of the file. ### bundle ```ts bundle: Bundle ``` A bundle: an archive whose files back other assets. ### container ```ts container: ContainerResource ``` The renders, materials, textures, animations and gsplats of a glTF or GLB file. ### css ```ts css: string ``` The CSS text. ### cubemap ```ts cubemap: Texture | null ``` The cube map, or null when the asset provides only prefiltered levels. [Asset#resources](https://api.playcanvas.com/engine/classes/Asset.md#resources) holds the cube map followed by its six prefiltered levels, with null for each level the asset does not provide. ### folder ```ts folder: null ``` Folders hold no resource. ### font ```ts font: Font | CanvasFont ``` A [Font](https://api.playcanvas.com/engine/classes/Font.md) loaded from a font file. ### gsplat ```ts gsplat: GSplatResourceBase | GSplatOctreeResource ``` A Gaussian splat resource, or the octree resource of a level-of-detail splat scene. ### hierarchy ```ts hierarchy: Entity ``` The root entity of an instantiated scene hierarchy. ### html ```ts html: string ``` The HTML text. ### json ```ts json: unknown ``` The parsed JSON data. ### material ```ts material: Material ``` A material, a [StandardMaterial](https://api.playcanvas.com/engine/classes/StandardMaterial.md) unless a custom parser creates another kind. ### model ```ts model: Model ``` A model. ### render ```ts render: Render ``` The meshes of one glTF mesh, created when a container asset loads. ### scene ```ts scene: Scene ``` A scene. ### scenesettings ```ts scenesettings: any ``` The settings block of a scene file. ### script ```ts script: Record ``` The script classes declared by a script file, keyed by class name. ### shader ```ts shader: string ``` The shader source text. ### sprite ```ts sprite: Sprite ``` A sprite. ### template ```ts template: Template ``` A template. ### text ```ts text: string ``` The text of the file. ### texture ```ts texture: Texture ``` A texture. ### textureatlas ```ts textureatlas: TextureAtlas ``` A texture atlas. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/AttributeDescription.md # AttributeDescription Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-format.js#L71 ## Properties ### asInt ```ts 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 ```ts components: number ``` The number of components of the vertex attribute. Can be 1, 2, 3 or 4. ### normalize ```ts 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 ```ts semantic: string ``` The meaning of the vertex element. This is used to link the vertex data to a shader input. Can be: - [SEMANTIC_POSITION](https://api.playcanvas.com/engine/variables/SEMANTIC_POSITION.md) - [SEMANTIC_NORMAL](https://api.playcanvas.com/engine/variables/SEMANTIC_NORMAL.md) - [SEMANTIC_TANGENT](https://api.playcanvas.com/engine/variables/SEMANTIC_TANGENT.md) - [SEMANTIC_BLENDWEIGHT](https://api.playcanvas.com/engine/variables/SEMANTIC_BLENDWEIGHT.md) - [SEMANTIC_BLENDINDICES](https://api.playcanvas.com/engine/variables/SEMANTIC_BLENDINDICES.md) - [SEMANTIC_COLOR](https://api.playcanvas.com/engine/variables/SEMANTIC_COLOR.md) - [SEMANTIC_TEXCOORD0](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD0.md) - [SEMANTIC_TEXCOORD1](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD1.md) - [SEMANTIC_TEXCOORD2](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD2.md) - [SEMANTIC_TEXCOORD3](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD3.md) - [SEMANTIC_TEXCOORD4](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD4.md) - [SEMANTIC_TEXCOORD5](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD5.md) - [SEMANTIC_TEXCOORD6](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD6.md) - [SEMANTIC_TEXCOORD7](https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD7.md) If vertex data has a meaning other that one of those listed above, use the user-defined semantics: [SEMANTIC_ATTR0](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR0.md) to [SEMANTIC_ATTR15](https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR15.md). ### type ```ts type: number ``` The data type of the attribute. Can be: - [TYPE_INT8](https://api.playcanvas.com/engine/variables/TYPE_INT8.md) - [TYPE_UINT8](https://api.playcanvas.com/engine/variables/TYPE_UINT8.md) - [TYPE_INT16](https://api.playcanvas.com/engine/variables/TYPE_INT16.md) - [TYPE_UINT16](https://api.playcanvas.com/engine/variables/TYPE_UINT16.md) - [TYPE_INT32](https://api.playcanvas.com/engine/variables/TYPE_INT32.md) - [TYPE_UINT32](https://api.playcanvas.com/engine/variables/TYPE_UINT32.md) - [TYPE_FLOAT16](https://api.playcanvas.com/engine/variables/TYPE_FLOAT16.md) - [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md) -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/AttributeSchema.md # AttributeSchema Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-attributes.js#L160 ## Properties ### array ```ts array?: boolean ``` True if this attribute is an array of `type` ### type ```ts type: "string" | "number" | "boolean" | "rgb" | "curve" | "json" | "vec2" | "vec3" | "vec4" | "entity" | "asset" | "rgba" ``` The Attribute type -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Bloom.md # Bloom Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L82 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. ## Properties ### blurLevel ```ts 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 ```ts intensity: number ``` The intensity of the bloom effect, 0-0.1 range. Defaults to 0, making it disabled. ### threshold ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/BoxLineShapeArgs.md # BoxLineShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/boxline-shape.js#L18 ## Properties ### boxSize ```ts boxSize?: number ``` The size of the box ### gap ```ts gap?: number ``` The gap between the box and the line ### lineLength ```ts lineLength?: number ``` The length of the line ### lineThickness ```ts lineThickness?: number ``` The thickness of the line ### tolerance ```ts tolerance?: number ``` The tolerance for intersection tests -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/BoxShapeArgs.md # BoxShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/box-shape.js#L10 ## Properties ### size ```ts size?: number ``` The size of the box. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ChunkValidation.md # ChunkValidation Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunk-map.js#L5 ## Properties ### callback ```ts callback?: (arg0: string, arg1: string) => void ``` Validation callback receiving chunk name and code. ### defaultCodeGLSL ```ts defaultCodeGLSL?: string ``` Default GLSL code. If matches, no warning. ### defaultCodeWGSL ```ts defaultCodeWGSL?: string ``` Default WGSL code. If matches, no warning. ### message ```ts message?: string ``` Deprecation message to display. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ColorEnhance.md # ColorEnhance Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L170 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. ## Properties ### dehaze ```ts 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 ```ts enabled: boolean ``` Whether color enhancement is enabled. Defaults to false. ### highlights ```ts 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 ```ts 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 ```ts 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 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ColorLUT.md # ColorLUT Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L112 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. ## Properties ### blend ```ts 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 ```ts intensity: number ``` The strength of the primary LUT, blended against the original color, 0-1 range. Defaults to 1. ### intensity2 ```ts 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 ```ts 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 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Dof.md # Dof Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L203 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. ## Properties ### blurRadius ```ts blurRadius: number ``` The radius of the blur effect, typically 2-10 range. Defaults to 3. ### blurRingPoints ```ts blurRingPoints: number ``` The number of points in each ring of the blur effect, typically 3-8 range. Defaults to 5. ### blurRings ```ts blurRings: number ``` The number of rings in the blur effect, typically 3-8 range. Defaults to 4. ### enabled ```ts enabled: boolean ``` Whether DoF is enabled. Defaults to false. ### focusDistance ```ts focusDistance: number ``` The distance at which the focus is set. Defaults to 100. ### focusRange ```ts focusRange: number ``` The range around the focus distance where the focus is sharp. Defaults to 10. ### highQuality ```ts 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 ```ts nearBlur: boolean ``` Whether the near blur is enabled. Defaults to false. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Fringing.md # Fringing Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L162 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. ## Properties ### intensity ```ts intensity: number ``` The intensity of the fringing effect, 0-100 range. Defaults to 0, making it disabled. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/GizmoTheme.md # GizmoTheme Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/transform-gizmo.js#L28 ## Properties ### disabled ```ts disabled: Color ``` The disabled color. ### guideBase ```ts guideBase: { x: Color; y: Color; z: Color } ``` The guide line colors. **Properties** - `x` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `y` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `z` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) ### guideOcclusion ```ts guideOcclusion: number ``` The guide occlusion value. Defaults to 0.8. ### shapeBase ```ts shapeBase: { f: Color; x: Color; xyz: Color; y: Color; z: Color } ``` The axis colors. **Properties** - `f` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `x` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `xyz` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `y` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `z` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) ### shapeHover ```ts shapeHover: { f: Color; x: Color; xyz: Color; y: Color; z: Color } ``` The hover colors. **Properties** - `f` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `x` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `xyz` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `y` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) - `z` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md)) -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Grading.md # Grading Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L100 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. ## Properties ### brightness ```ts brightness: number ``` The brightness of the grading effect, 0-3 range. Defaults to 1. ### contrast ```ts contrast: number ``` The contrast of the grading effect, 0.5-1.5 range. Defaults to 1. ### enabled ```ts enabled: boolean ``` Whether grading is enabled. Defaults to false. ### saturation ```ts saturation: number ``` The saturation of the grading effect, 0-2 range. Defaults to 1. ### tint ```ts tint: Color ``` The tint color of the grading effect. Defaults to white. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/GSplatProcessorBinding.md # GSplatProcessorBinding Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/gsplat/gsplat-processor.js#L23 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. ## Properties ### component ```ts component?: GSplatComponent ``` Component for instance textures. If provided, resource is automatically resolved from the component. ### resource ```ts resource?: GSplatResourceBase ``` Resource to read/write from. ### streams ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/GSplatStreamDescriptor.md # GSplatStreamDescriptor Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-format.js#L31 ## Properties ### format ```ts 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](https://api.playcanvas.com/engine/classes/Texture.md) for details on renderable formats and device capabilities. ### name ```ts name: string ``` The name of the stream (used as texture uniform name). ### storage ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/GSplatVaryingDescriptor.md # GSplatVaryingDescriptor Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-varyings.js#L24 ## Properties ### components ```ts components: number ``` The number of components, 1 to 4. ### name ```ts name: string ``` The varying name. Must be a valid shader identifier. ### type ```ts type: number ``` The component data type: [TYPE_FLOAT32](https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md), [TYPE_INT32](https://api.playcanvas.com/engine/variables/TYPE_INT32.md) or [TYPE_UINT32](https://api.playcanvas.com/engine/variables/TYPE_UINT32.md). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/MiniStatsGraphOptions.md # MiniStatsGraphOptions Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L66 ## Properties ### decimalPlaces ```ts decimalPlaces?: number ``` Number of decimal places (defaults to none). ### multiplier ```ts multiplier?: number ``` Multiplier applied to sampled values, for example to convert bytes to megabytes. ### name ```ts name: string ``` Display name. ### stats ```ts stats: string[] ``` Path to data inside Application.stats. ### unitsName ```ts unitsName?: string ``` Units (defaults to ""). ### watermark ```ts watermark?: number ``` Watermark - shown as a line on the graph, useful for displaying a budget. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/MiniStatsOptions.md # MiniStatsOptions Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L78 ## Properties ### cpu ```ts cpu: MiniStatsProcessorOptions ``` CPU graph options. ### cpuTimingMinSize ```ts cpuTimingMinSize?: number ``` Minimum size index at which to show CPU sub-timing graphs (script, anim, physics, render). Defaults to 1. ### gpu ```ts gpu: MiniStatsProcessorOptions ``` GPU graph options. ### gpuTimingMinSize ```ts gpuTimingMinSize?: number ``` Minimum size index at which to show GPU pass timing graphs. Defaults to 1. ### resourcesCollapsed ```ts resourcesCollapsed?: boolean ``` Initially collapse the Resources section. ### resourcesEnabled ```ts resourcesEnabled?: boolean ``` Show tracked resource counts in detailed views. ### sizes ```ts sizes: MiniStatsSizeOptions[] ``` Sizes of area to render individual graphs in and spacing between individual graphs. ### startSizeIndex ```ts startSizeIndex: number ``` Index into sizes array for initial setting. ### stats ```ts 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 ```ts 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 ```ts vramTimingMinSize?: number ``` Minimum size index at which to show VRAM subcategory graphs. Defaults to 1. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/MiniStatsProcessorOptions.md # MiniStatsProcessorOptions Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L59 ## Properties ### enabled ```ts enabled: boolean ``` Whether to show the graph. ### watermark ```ts watermark: number ``` Watermark - shown as a line on the graph, useful for displaying a budget. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/MiniStatsSizeOptions.md # MiniStatsSizeOptions Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L48 ## Properties ### detailed ```ts detailed?: boolean ``` Show category headers and sub-counters. Defaults to true for sizes after the first, or when graphs are enabled. ### graphs ```ts graphs: boolean ``` Whether to show graphs. ### height ```ts height: number ``` Height of the graph area. ### peak ```ts peak?: boolean ``` Show a peak column in the detailed view. Defaults to the graphs setting. ### spacing ```ts spacing: number ``` Spacing between graphs. ### width ```ts width: number ``` Width of the graph area. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ParserContext.md # ParserContext Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L22 ## Properties ### app ```ts app: AppBase ``` The running [AppBase](https://api.playcanvas.com/engine/classes/AppBase.md). ### asset ```ts asset: Asset | undefined ``` The asset being loaded, if any. ### basename ```ts basename: string ``` The lower-cased file name (for example `'lod-meta.json'`), or an empty string. ### ext ```ts ext: string ``` The lower-cased file extension without a leading dot (for example `'json'`), or an empty string if there is none. ### url ```ts url: string | null ``` The original resource URL with any query string removed, or null. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/PlaneShapeArgs.md # PlaneShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/plane-shape.js#L14 ## Properties ### gap ```ts gap?: number ``` The gap between the plane and the center ### size ```ts size?: number ``` The size of the plane -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/PlyElement.md # PlyElement Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L26 ## Properties ### count ```ts count: number ``` Given count. ### name ```ts name: string ``` E.g. 'vertex'. ### properties ```ts properties: PlyProperty[] ``` The properties. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/PlyProperty.md # PlyProperty Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L18 ## Properties ### byteSize ```ts byteSize: number ``` BYTES_PER_ELEMENT of given data type. ### name ```ts name: string ``` E.g. 'x', 'y', 'z', 'f_dc_0' etc. ### storage ```ts storage: DataType ``` Data type, e.g. instance of Float32Array. ### type ```ts type: string ``` E.g. 'float'. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Rendering.md # Rendering Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L18 Properties related to scene rendering, encompassing settings that control the rendering resolution, pixel format, multi-sampling for anti-aliasing, tone-mapping and similar. ## Properties ### renderFormats ```ts 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md) is used, but this automatically disables bloom effect, which requires HDR format. The list can contain the following formats: [PIXELFORMAT_111110F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md), [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md), [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md) and [PIXELFORMAT_RGBA8](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md). 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](https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md), [PIXELFORMAT_RGBA16F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md), [PIXELFORMAT_RGBA32F](https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md)]. ### renderTargetScale ```ts 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 ```ts samples: number ``` The number of samples of the [RenderTarget](https://api.playcanvas.com/engine/classes/RenderTarget.md) 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 ```ts sceneColorMap: boolean ``` Whether rendering generates a scene color map. Defaults to false. ### sceneDepthMap ```ts sceneDepthMap: boolean ``` Whether rendering generates a scene depth map. Defaults to false. ### sharpness ```ts 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 ```ts stencil: boolean ``` Whether the render buffer has a stencil buffer. Defaults to false. ### toneMapping ```ts toneMapping: number ``` The tone mapping. Can be: - [TONEMAP_LINEAR](https://api.playcanvas.com/engine/variables/TONEMAP_LINEAR.md) - [TONEMAP_FILMIC](https://api.playcanvas.com/engine/variables/TONEMAP_FILMIC.md) - [TONEMAP_HEJL](https://api.playcanvas.com/engine/variables/TONEMAP_HEJL.md) - [TONEMAP_ACES](https://api.playcanvas.com/engine/variables/TONEMAP_ACES.md) - [TONEMAP_ACES2](https://api.playcanvas.com/engine/variables/TONEMAP_ACES2.md) - [TONEMAP_NEUTRAL](https://api.playcanvas.com/engine/variables/TONEMAP_NEUTRAL.md) Defaults to [TONEMAP_LINEAR](https://api.playcanvas.com/engine/variables/TONEMAP_LINEAR.md). -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ResourceParser.md # ResourceParser Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L39 ## Properties ### canParse ```ts 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 ```ts handler?: ResourceHandler ``` Assigned by the owning handler on registration; available in `load`/`open` (for example `this.handler.fetch(...)`). ### load ```ts load: (url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset) => void ``` Fetches (typically via `this.handler.fetch`) and produces the resource, then invokes the callback. ### open ```ts open?: (url: string, data: any, asset?: Asset) => any ``` Optional. Called by the default [ResourceHandler#open](https://api.playcanvas.com/engine/classes/ResourceHandler.md#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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ScriptInitializationArgs.md # ScriptInitializationArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script.js#L278 ## Properties ### app ```ts app: AppBase ``` The AppBase that is running the script. ### enabled ```ts enabled?: boolean ``` True if the script instance is in running state. ### entity ```ts entity: Entity ``` The Entity that the script is attached to. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ShaderDesc.md # ShaderDesc Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/shader-material.js#L12 Defines the vertex and fragment shader source for [ShaderMaterial](https://api.playcanvas.com/engine/classes/ShaderMaterial.md), 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. ## Properties ### attributes ```ts 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 ```ts fragmentGLSL?: string ``` The fragment shader code in GLSL. ### fragmentOutputTypes ```ts 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 ```ts fragmentWGSL?: string ``` The fragment shader code in WGSL. ### uniqueName ```ts 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 ```ts vertexGLSL?: string ``` The vertex shader code in GLSL. ### vertexWGSL ```ts vertexWGSL?: string ``` The vertex shader code in WGSL. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/ShapeArgs.md # ShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/shape.js#L24 ## Properties ### axis ```ts axis?: string ``` The axis of the shape (e.g., 'x', 'y', 'z'). ### cull ```ts cull?: number ``` The culling mode of the shape. ### defaultColor ```ts defaultColor?: Color ``` The default color of the shape. ### depth ```ts depth?: number ``` The depth of the shape. -1 = interpolated depth. ### disabled ```ts disabled?: boolean ``` Whether the shape is disabled. ### disabledColor ```ts disabledColor?: Color ``` The disabled color of the shape. ### hoverColor ```ts hoverColor?: Color ``` The hover color of the shape. ### layers ```ts layers?: number[] ``` The layers the shape belongs to. ### position ```ts position?: Vec3 ``` The position of the shape. ### rotation ```ts rotation?: Vec3 ``` The rotation of the shape. ### scale ```ts scale?: Vec3 ``` The scale of the shape. ### visible ```ts visible?: boolean ``` Whether the shape is visible. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/SphereShapeArgs.md # SphereShapeArgs Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/sphere-shape.js#L10 ## Properties ### radius ```ts radius?: number ``` The radius of the sphere. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Ssao.md # Ssao Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L58 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. ## Properties ### blurEnabled ```ts blurEnabled: boolean ``` Whether the SSAO effect is blurred. Defaults to true. ### intensity ```ts intensity: number ``` The intensity of the SSAO effect, 0-1 range. Defaults to 0.5. ### minAngle ```ts minAngle: number ``` The minimum angle of the SSAO effect, 1-90 range. Defaults to 10. ### power ```ts power: number ``` The power of the SSAO effect, 0.1-10 range. Defaults to 6. ### radius ```ts radius: number ``` The radius of the SSAO effect, 0-100 range. Defaults to 30. ### randomize ```ts randomize: boolean ``` Whether the SSAO sampling is randomized. Useful when used instead of blur effect together with TAA. Defaults to false. ### samples ```ts samples: number ``` The number of samples of the SSAO effect, 1-64 range. Defaults to 12. ### scale ```ts scale: number ``` The scale of the SSAO effect, 0.5-1 range. Defaults to 1. ### type ```ts type: string ``` The type of the SSAO determines how it is applied in the rendering process. Defaults to [SSAOTYPE_NONE](https://api.playcanvas.com/engine/variables/SSAOTYPE_NONE.md). Can be: - [SSAOTYPE_NONE](https://api.playcanvas.com/engine/variables/SSAOTYPE_NONE.md) - [SSAOTYPE_LIGHTING](https://api.playcanvas.com/engine/variables/SSAOTYPE_LIGHTING.md) - [SSAOTYPE_COMBINE](https://api.playcanvas.com/engine/variables/SSAOTYPE_COMBINE.md) -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Taa.md # Taa Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L192 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. ## Properties ### enabled ```ts enabled: boolean ``` Whether TAA is enabled. Defaults to false. ### jitter ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/TransformFeedbackStream.md # TransformFeedbackStream Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/transform-feedback.js#L16 ## Properties ### input ```ts input?: VertexBuffer ``` A buffer read by the shader as a vertex stream. ### output ```ts output?: VertexBuffer ``` A buffer written by transform feedback. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/Vignette.md # Vignette Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L139 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. ## Properties ### color ```ts color: Color ``` The color of the vignette effect. Defaults to black. ### curvature ```ts 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 ```ts 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 ```ts intensity: number ``` The intensity of the vignette effect, 0-1 range. Defaults to 0, making it disabled. ### outer ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/interfaces/VolumetricFog.md # VolumetricFog Interface · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L222 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`. ## Properties ### ambientColor ```ts ambientColor: Color ``` The color of the ambient in-scattered light, which keeps the fog in shadowed areas visible. Defaults to white. ### ambientIntensity ```ts ambientIntensity: number ``` The intensity of the ambient in-scattered light. Defaults to 0.02. ### anisotropy ```ts 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 ```ts density: number ``` The fog density at the base height. Defaults to 0.01. ### enabled ```ts enabled: boolean ``` Whether the volumetric fog is enabled. Defaults to false. ### extinction ```ts 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 ```ts 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 ```ts 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 ```ts intensity: number ``` The intensity of the light scattering. Defaults to 1. ### light ```ts 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 ```ts localIntensity: number ``` The intensity of the light scattering of the local lights. Defaults to 1. ### localOmniLights ```ts 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](https://api.playcanvas.com/engine/classes/LightComponent.md#volumetricscattering). Defaults to false. ### localSpotLights ```ts 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 ```ts localSteps: number ``` The number of raymarching steps taken inside the volume of each local light, 2-64 range. Defaults to 12. ### maxDistance ```ts maxDistance: number ``` The maximum world space distance the fog is raymarched to. Defaults to 300. ### scale ```ts scale: number ``` The resolution scale of the fog texture relative to the scene render target, 0.25-1 range. Defaults to 0.5. ### steps ```ts steps: number ``` The number of raymarching steps, 4-128 range. Higher values improve the quality at a higher performance cost. Defaults to 24. ### tint ```ts tint: Color ``` The albedo of the fog. Defaults to white. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/AssetReadyCallback.md # AssetReadyCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L126 Callback used by [Asset#ready](https://api.playcanvas.com/engine/classes/Asset.md#ready) and called when an asset is ready. ```ts type AssetReadyCallback = (asset: Asset) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/AssetResource.md # AssetResource Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L121 ```ts type AssetResource = K extends AssetType ? AssetMap[K] : unknown ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/AssetType.md # AssetType Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L112 ```ts type AssetType = keyof AssetMap & string ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/BundlesFilterCallback.md # BundlesFilterCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L36 Callback used by [ResourceLoader#load](https://api.playcanvas.com/engine/classes/ResourceLoader.md#load) and called when an asset is choosing a bundle to load from. Return a single bundle to ensure asset is loaded from it. ```ts type BundlesFilterCallback = (bundles: Asset[]) => Asset ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/CalculateMatrixCallback.md # CalculateMatrixCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/component.js#L27 Callback used by [CameraComponent#calculateTransform](https://api.playcanvas.com/engine/classes/CameraComponent.md#calculatetransform) and [CameraComponent#calculateProjection](https://api.playcanvas.com/engine/classes/CameraComponent.md#calculateprojection). ```ts type CalculateMatrixCallback = (transformMatrix: Mat4, view: number) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/CalculateSortDistanceCallback.md # CalculateSortDistanceCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh-instance.js#L190 Callback used by [Layer](https://api.playcanvas.com/engine/classes/Layer.md) to calculate the "sort distance" for a [MeshInstance](https://api.playcanvas.com/engine/classes/MeshInstance.md), which determines its place in the render order. ```ts type CalculateSortDistanceCallback = (meshInstance: MeshInstance, cameraPosition: Vec3, cameraForward: Vec3) => number ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ChangeSceneCallback.md # ChangeSceneCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L27 Callback used by [SceneRegistry#changeScene](https://api.playcanvas.com/engine/classes/SceneRegistry.md#changescene). ```ts type ChangeSceneCallback = (err: string | null, entity?: Entity) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ComponentMap.md # ComponentMap Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L52 ```ts type ComponentMap = { [K in keyof Entity as NonNullable extends Component ? K : never]: NonNullable } ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ComponentName.md # ComponentName Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L65 ```ts type ComponentName = keyof ComponentMap & string ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ComponentOptions.md # ComponentOptions Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L77 ```ts type ComponentOptions = { [P in keyof MergedComponentOptions]: MergedComponentOptions[P] } ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ConfigureAppCallback.md # ConfigureAppCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L69 Callback used by [AppBase#configure](https://api.playcanvas.com/engine/classes/AppBase.md#configure) when configuration file is loaded and parsed (or an error occurs). ```ts type ConfigureAppCallback = Object ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/CreateScreenCallback.md # CreateScreenCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L8 Callback used by [script.createLoadingScreen](https://api.playcanvas.com/engine/functions/script.createLoadingScreen.md). ```ts type CreateScreenCallback = (app: AppBase) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/DataType.md # DataType Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L14 ```ts type DataType = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/FilterAssetCallback.md # FilterAssetCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L18 Callback used by [AssetRegistry#filter](https://api.playcanvas.com/engine/classes/AssetRegistry.md#filter) to filter assets. ```ts type FilterAssetCallback = (asset: Asset) => boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/FindNodeCallback.md # FindNodeCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L72 Callback used by [GraphNode#find](https://api.playcanvas.com/engine/classes/GraphNode.md#find) and [GraphNode#findOne](https://api.playcanvas.com/engine/classes/GraphNode.md#findone) to search through a graph node and all of its descendants. ```ts type FindNodeCallback = (node: GraphNode) => boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ForEachNodeCallback.md # ForEachNodeCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L81 Callback used by [GraphNode#forEach](https://api.playcanvas.com/engine/classes/GraphNode.md#foreach) to iterate through a graph node and all of its descendants. ```ts type ForEachNodeCallback = (node: GraphNode) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/GizmoAxis.md # GizmoAxis Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L24 ```ts type GizmoAxis = "x" | "y" | "z" | "yz" | "xz" | "xy" | "xyz" | "f" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/GizmoDragMode.md # GizmoDragMode Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L35 ```ts type GizmoDragMode = "show" | "hide" | "selected" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/GizmoSpace.md # GizmoSpace Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L8 ```ts type GizmoSpace = "local" | "world" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/HandleEventCallback.md # HandleEventCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handler.js#L4 Callback used by [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md) functions. Note the callback is limited to 8 arguments. ```ts type HandleEventCallback = (arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/HttpResponseCallback.md # HttpResponseCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/net/http.js#L13 Callback used by [Http#get](https://api.playcanvas.com/engine/classes/Http.md#get), [Http#post](https://api.playcanvas.com/engine/classes/Http.md#post), [Http#put](https://api.playcanvas.com/engine/classes/Http.md#put), [Http#del](https://api.playcanvas.com/engine/classes/Http.md#del), and [Http#request](https://api.playcanvas.com/engine/classes/Http.md#request). ```ts type HttpResponseCallback = (err: number | string | Error | null, response?: any) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LoadAssetCallback.md # LoadAssetCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L26 Callback used by [AssetRegistry#loadFromUrl](https://api.playcanvas.com/engine/classes/AssetRegistry.md#loadfromurl) and called when an asset is loaded (or an error occurs). ```ts type LoadAssetCallback = (err: string | null, asset?: Asset) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LoadHierarchyCallback.md # LoadHierarchyCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L12 Callback used by [SceneRegistry#loadSceneHierarchy](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenehierarchy). ```ts type LoadHierarchyCallback = (err: string | null, entity?: Entity) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LoadSceneCallback.md # LoadSceneCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L35 Callback used by [SceneRegistry#loadScene](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscene). ```ts type LoadSceneCallback = (err: string | null, entity?: Entity) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LoadSceneDataCallback.md # LoadSceneDataCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L43 Callback used by [SceneRegistry#loadSceneData](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenedata). ```ts type LoadSceneDataCallback = (err: string | null, sceneItem?: SceneRegistryItem) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LoadSettingsCallback.md # LoadSettingsCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L20 Callback used by [SceneRegistry#loadSceneSettings](https://api.playcanvas.com/engine/classes/SceneRegistry.md#loadscenesettings). ```ts type LoadSettingsCallback = (err: string | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/LockMouseCallback.md # LockMouseCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse.js#L6 Callback used by [Mouse#enablePointerLock](https://api.playcanvas.com/engine/classes/Mouse.md#enablepointerlock) and [Mouse#disablePointerLock](https://api.playcanvas.com/engine/classes/Mouse.md#disablepointerlock). ```ts type LockMouseCallback = () => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ModuleErrorCallback.md # ModuleErrorCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L113 Callback used by [WasmModule.setConfig](https://api.playcanvas.com/engine/classes/WasmModule.md#setconfig). ```ts type ModuleErrorCallback = (error: string) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ModuleInstanceCallback.md # ModuleInstanceCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L120 Callback used by [WasmModule.getInstance](https://api.playcanvas.com/engine/classes/WasmModule.md#getinstance). ```ts type ModuleInstanceCallback = (moduleInstance: any) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/NumericArray.md # NumericArray Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh.js#L30 ```ts type NumericArray = number[] | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/PreloadAppCallback.md # PreloadAppCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L77 Callback used by [AppBase#preload](https://api.playcanvas.com/engine/classes/AppBase.md#preload) when all assets (marked as 'preload') are loaded. ```ts type PreloadAppCallback = Object ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md # ResourceHandlerCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L12 Callback used by [ResourceHandler#load](https://api.playcanvas.com/engine/classes/ResourceHandler.md#load) when a resource is loaded (or an error occurs). ```ts type ResourceHandlerCallback = (err: string | null, response?: any) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/ResourceLoaderCallback.md # ResourceLoaderCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/loader.js#L14 Callback used by [ResourceLoader#load](https://api.playcanvas.com/engine/classes/ResourceLoader.md#load) when a resource is loaded (or an error occurs). ```ts type ResourceLoaderCallback = (err: string | null, resource?: any) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/UpdateShaderCallback.md # UpdateShaderCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material.js#L157 Callback used by [StandardMaterial#onUpdateShader](https://api.playcanvas.com/engine/classes/StandardMaterial.md#onupdateshader). ```ts type UpdateShaderCallback = (options: StandardMaterialOptions) => StandardMaterialOptions ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrAnchorCreateCallback.md # XrAnchorCreateCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchors.js#L13 Callback used by [XrAnchors#create](https://api.playcanvas.com/engine/classes/XrAnchors.md#create). ```ts type XrAnchorCreateCallback = (err: Error | null, anchor: XrAnchor | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrAnchorForgetCallback.md # XrAnchorForgetCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L19 Callback used by [XrAnchor#forget](https://api.playcanvas.com/engine/classes/XrAnchor.md#forget). ```ts type XrAnchorForgetCallback = (err: Error | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrAnchorPersistCallback.md # XrAnchorPersistCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L10 Callback used by [XrAnchor#persist](https://api.playcanvas.com/engine/classes/XrAnchor.md#persist). ```ts type XrAnchorPersistCallback = (err: Error | null, uuid: string | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrErrorCallback.md # XrErrorCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L38 Callback used by [XrManager#start](https://api.playcanvas.com/engine/classes/XrManager.md#start) and [XrManager#end](https://api.playcanvas.com/engine/classes/XrManager.md#end). ```ts type XrErrorCallback = (err: Error | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrHitTestStartCallback.md # XrHitTestStartCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test.js#L13 Callback used by [XrHitTest#start](https://api.playcanvas.com/engine/classes/XrHitTest.md#start) and [XrInputSource#hitTestStart](https://api.playcanvas.com/engine/classes/XrInputSource.md#hitteststart). ```ts type XrHitTestStartCallback = (err: Error | null, hitTestSource: XrHitTestSource | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/types/XrRoomCaptureCallback.md # XrRoomCaptureCallback Type alias · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L45 Callback used by [XrManager#initiateRoomCapture](https://api.playcanvas.com/engine/classes/XrManager.md#initiateroomcapture). ```ts type XrRoomCaptureCallback = (err: Error | null) => void ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/basisInitialize.md # basisInitialize Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/basis.js#L268 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/dracoDecode.md # dracoDecode Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/draco-decoder.js#L266 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/dracoInitialize.md # dracoInitialize Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/draco-decoder.js#L251 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/guid.create.md # guid.create Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/guid.js#L13 ```ts create(): string ``` Create an RFC4122 version 4 compliant GUID. **Returns** `string`: A new GUID. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.extractPath.md # path.extractPath Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L180 ```ts 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** ```ts 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" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.getBasename.md # path.getBasename Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L116 ```ts 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](https://api.playcanvas.com/engine/functions/path.split.md). **Parameters** - `pathname` (`string`): The path to process. **Returns** `string`: The basename. **Example** ```ts path.getBasename("/path/to/file.txt"); // returns "file.txt" path.getBasename("/path/to/dir"); // returns "dir" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.getDirectory.md # path.getDirectory Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L127 ```ts getDirectory(pathname: string): string ``` Get the directory name from the path. This is everything up to the final instance of [path.delimiter](https://api.playcanvas.com/engine/variables/path.delimiter.md). **Parameters** - `pathname` (`string`): The path to get the directory from. **Returns** `string`: The directory part of the path. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.getExtension.md # path.getExtension Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L142 ```ts 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** ```ts 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" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.isRelativePath.md # path.isRelativePath Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L165 ```ts 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** ```ts 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 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.join.md # path.join Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L26 ```ts 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** ```ts const joinedPath = path.join('foo', 'bar'); console.log(joinedPath); // Prints 'foo/bar' ``` **Example** ```ts const joinedPath = path.join('alpha', 'beta', 'gamma'); console.log(joinedPath); // Prints 'alpha/beta/gamma' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.normalize.md # path.normalize Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L54 ```ts normalize(pathname: string): string ``` Normalize the path by removing '.' and '..' instances. **Parameters** - `pathname` (`string`): The path to normalize. **Returns** `string`: The normalized path. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/path.split.md # path.split Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L98 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/string.format.md # string.format Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L137 ```ts 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** ```ts const s = string.format("Hello {0}", "world"); console.log(s); // Prints "Hello world" ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/string.getCodePoint.md # string.getCodePoint Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L152 ```ts 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](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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/string.getCodePoints.md # string.getCodePoints Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L163 ```ts 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. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/functions/string.getSymbols.md # string.getSymbols Function · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L186 ```ts 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](https://mathiasbynens.be/notes/javascript-unicode) for more info. **Parameters** - `string` (`string`): The string to break into symbols. **Returns** `string[]`: The symbols in the string. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/path.delimiter.md # path.delimiter Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L12 The character that separates path segments. ```ts const delimiter: string = '/' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.android.md # platform.android Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L111 True if running on an Android device. ```ts const android: boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.browser.md # platform.browser Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L75 Convenience boolean indicating whether we're running in the browser. ```ts const browser: boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.desktop.md # platform.desktop Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L90 True if running on a desktop or laptop device. ```ts const desktop: boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.environment.md # platform.environment Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L57 String identifying the current runtime environment. Either 'browser', 'node' or 'worker'. ```ts const environment: "worker" | "browser" | "node" = environment ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.gamepads.md # platform.gamepads Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L133 True if the platform supports gamepads. ```ts const gamepads: boolean = gamepads ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.global.md # platform.global Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L65 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. ```ts const global: any ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.ios.md # platform.ios Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L104 True if running on an iOS device. ```ts const ios: boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.mobile.md # platform.mobile Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L97 True if running on a mobile or tablet device. ```ts const mobile: boolean ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.touch.md # platform.touch Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L140 True if the platform supports touch input. ```ts const touch: boolean = touch ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.workers.md # platform.workers Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L147 True if the platform supports Web Workers. ```ts const workers: boolean = workers ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/platform.xbox.md # platform.xbox Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L126 True if running on an Xbox device. ```ts const xbox: boolean = xbox ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/revision.md # revision Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/core.js#L10 The engine revision number. This is the Git hash of the last commit made to the branch from which the engine was built. ```ts const revision: "$_CURRENT_SDK_REVISION" = '$_CURRENT_SDK_REVISION' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/version.md # version Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/core.js#L4 The engine version number. This is in semantic versioning format (MAJOR.MINOR.PATCH). ```ts const version: "$_CURRENT_SDK_VERSION" = '$_CURRENT_SDK_VERSION' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/guid.md # guid Namespace · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/guid.js#L7 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. ## Members - [create](https://api.playcanvas.com/engine/functions/guid.create.md): Create an RFC4122 version 4 compliant GUID. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/path.md # path Namespace · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L6 File path API. ## Members - [delimiter](https://api.playcanvas.com/engine/variables/path.delimiter.md): The character that separates path segments. - [extractPath](https://api.playcanvas.com/engine/functions/path.extractPath.md): Return the path without file name. - [getBasename](https://api.playcanvas.com/engine/functions/path.getBasename.md): Return the basename of the path. - [getDirectory](https://api.playcanvas.com/engine/functions/path.getDirectory.md): Get the directory name from the path. - [getExtension](https://api.playcanvas.com/engine/functions/path.getExtension.md): Return the extension of the path. - [isRelativePath](https://api.playcanvas.com/engine/functions/path.isRelativePath.md): Check if a string s is relative path. - [join](https://api.playcanvas.com/engine/functions/path.join.md): Join two or more sections of file path together, inserting a delimiter if needed. - [normalize](https://api.playcanvas.com/engine/functions/path.normalize.md): Normalize the path by removing '.' and '..' instances. - [split](https://api.playcanvas.com/engine/functions/path.split.md): Split the pathname path into a pair [head, tail] where tail is the final part of the path after the last delimiter... -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/platform.md # platform Namespace · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L42 Global namespace that stores flags regarding platform environment and features support. **Example** ```ts if (platform.touch) { // touch is supported } ``` ## Members - [android](https://api.playcanvas.com/engine/variables/platform.android.md): True if running on an Android device. - [browser](https://api.playcanvas.com/engine/variables/platform.browser.md): Convenience boolean indicating whether we're running in the browser. - [desktop](https://api.playcanvas.com/engine/variables/platform.desktop.md): True if running on a desktop or laptop device. - [environment](https://api.playcanvas.com/engine/variables/platform.environment.md): String identifying the current runtime environment. - [gamepads](https://api.playcanvas.com/engine/variables/platform.gamepads.md): True if the platform supports gamepads. - [global](https://api.playcanvas.com/engine/variables/platform.global.md): The global object. - [ios](https://api.playcanvas.com/engine/variables/platform.ios.md): True if running on an iOS device. - [mobile](https://api.playcanvas.com/engine/variables/platform.mobile.md): True if running on a mobile or tablet device. - [touch](https://api.playcanvas.com/engine/variables/platform.touch.md): True if the platform supports touch input. - [workers](https://api.playcanvas.com/engine/variables/platform.workers.md): True if the platform supports Web Workers. - [xbox](https://api.playcanvas.com/engine/variables/platform.xbox.md): True if running on an Xbox device. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/modules/string.md # string Namespace · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L105 Extended String API. ## Members - [ASCII_LETTERS](https://api.playcanvas.com/engine/variables/string.ASCII_LETTERS.md): All ASCII letters. - [ASCII_LOWERCASE](https://api.playcanvas.com/engine/variables/string.ASCII_LOWERCASE.md): All lowercase letters. - [ASCII_UPPERCASE](https://api.playcanvas.com/engine/variables/string.ASCII_UPPERCASE.md): All uppercase letters. - [format](https://api.playcanvas.com/engine/functions/string.format.md): Return a string with {n} replaced with the n-th argument. - [getCodePoint](https://api.playcanvas.com/engine/functions/string.getCodePoint.md): Get the code point number for a character in a string. - [getCodePoints](https://api.playcanvas.com/engine/functions/string.getCodePoints.md): Gets an array of all code points in a string. - [getSymbols](https://api.playcanvas.com/engine/functions/string.getSymbols.md): Gets an array of all grapheme clusters (visible symbols) in a string. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/other-types.md # PlayCanvas Engine API: Other Types 78 interfaces and type aliases without a category, mostly the types of other symbols' parameters and results. - [AnimCurvePath](https://api.playcanvas.com/engine/interfaces/AnimCurvePath.md) - [ArcShapeArgs](https://api.playcanvas.com/engine/interfaces/ArcShapeArgs.md) - [ArrowShapeArgs](https://api.playcanvas.com/engine/interfaces/ArrowShapeArgs.md) - [AssetMap](https://api.playcanvas.com/engine/interfaces/AssetMap.md) - [AttributeDescription](https://api.playcanvas.com/engine/interfaces/AttributeDescription.md) - [AttributeSchema](https://api.playcanvas.com/engine/interfaces/AttributeSchema.md) - [Bloom](https://api.playcanvas.com/engine/interfaces/Bloom.md): Properties related to the HDR bloom effect, a postprocessing technique that simulates the natural glow of bright... - [BoxLineShapeArgs](https://api.playcanvas.com/engine/interfaces/BoxLineShapeArgs.md) - [BoxShapeArgs](https://api.playcanvas.com/engine/interfaces/BoxShapeArgs.md) - [ChunkValidation](https://api.playcanvas.com/engine/interfaces/ChunkValidation.md) - [ColorEnhance](https://api.playcanvas.com/engine/interfaces/ColorEnhance.md): Properties related to the color enhancement effect, a postprocessing technique that provides HDR-aware adjustments... - [ColorLUT](https://api.playcanvas.com/engine/interfaces/ColorLUT.md): Properties related to the color lookup table (LUT) effect, a postprocessing technique used to apply a color... - [Dof](https://api.playcanvas.com/engine/interfaces/Dof.md): Properties related to Depth of Field (DOF), a technique used to simulate the optical effect where objects at certain... - [Fringing](https://api.playcanvas.com/engine/interfaces/Fringing.md): Properties related to the fringing effect, a chromatic aberration phenomenon where the red, green, and blue color... - [GizmoTheme](https://api.playcanvas.com/engine/interfaces/GizmoTheme.md) - [Grading](https://api.playcanvas.com/engine/interfaces/Grading.md): Properties related to the color grading effect, a postprocessing technique used to adjust and the visual tone of an... - [GSplatProcessorBinding](https://api.playcanvas.com/engine/interfaces/GSplatProcessorBinding.md): Configuration object specifying a data binding for GSplatProcessor. - [GSplatStreamDescriptor](https://api.playcanvas.com/engine/interfaces/GSplatStreamDescriptor.md) - [GSplatVaryingDescriptor](https://api.playcanvas.com/engine/interfaces/GSplatVaryingDescriptor.md) - [MiniStatsGraphOptions](https://api.playcanvas.com/engine/interfaces/MiniStatsGraphOptions.md) - [MiniStatsOptions](https://api.playcanvas.com/engine/interfaces/MiniStatsOptions.md) - [MiniStatsProcessorOptions](https://api.playcanvas.com/engine/interfaces/MiniStatsProcessorOptions.md) - [MiniStatsSizeOptions](https://api.playcanvas.com/engine/interfaces/MiniStatsSizeOptions.md) - [ParserContext](https://api.playcanvas.com/engine/interfaces/ParserContext.md) - [PlaneShapeArgs](https://api.playcanvas.com/engine/interfaces/PlaneShapeArgs.md) - [PlyElement](https://api.playcanvas.com/engine/interfaces/PlyElement.md) - [PlyProperty](https://api.playcanvas.com/engine/interfaces/PlyProperty.md) - [Rendering](https://api.playcanvas.com/engine/interfaces/Rendering.md): Properties related to scene rendering, encompassing settings that control the rendering resolution, pixel format,... - [ResourceParser](https://api.playcanvas.com/engine/interfaces/ResourceParser.md) - [ScriptInitializationArgs](https://api.playcanvas.com/engine/interfaces/ScriptInitializationArgs.md) - [ShaderDesc](https://api.playcanvas.com/engine/interfaces/ShaderDesc.md): Defines the vertex and fragment shader source for ShaderMaterial, supporting both GLSL and WGSL formats. - [ShapeArgs](https://api.playcanvas.com/engine/interfaces/ShapeArgs.md) - [SphereShapeArgs](https://api.playcanvas.com/engine/interfaces/SphereShapeArgs.md) - [Ssao](https://api.playcanvas.com/engine/interfaces/Ssao.md): Properties related to the Screen Space Ambient Occlusion (SSAO) effect, a postprocessing technique that approximates... - [Taa](https://api.playcanvas.com/engine/interfaces/Taa.md): Properties related to temporal anti-aliasing (TAA), which is a technique used to reduce aliasing in the rendered... - [TransformFeedbackStream](https://api.playcanvas.com/engine/interfaces/TransformFeedbackStream.md) - [Vignette](https://api.playcanvas.com/engine/interfaces/Vignette.md): Properties related to the vignette effect, a postprocessing technique that darkens the image edges, creating a... - [VolumetricFog](https://api.playcanvas.com/engine/interfaces/VolumetricFog.md): Properties related to volumetric fog, a raymarched height fog lit by a directional light. - [AssetReadyCallback](https://api.playcanvas.com/engine/types/AssetReadyCallback.md): Callback used by Asset#ready and called when an asset is ready. - [AssetResource](https://api.playcanvas.com/engine/types/AssetResource.md) - [AssetType](https://api.playcanvas.com/engine/types/AssetType.md) - [BundlesFilterCallback](https://api.playcanvas.com/engine/types/BundlesFilterCallback.md): Callback used by ResourceLoader#load and called when an asset is choosing a bundle to load from. - [CalculateMatrixCallback](https://api.playcanvas.com/engine/types/CalculateMatrixCallback.md): Callback used by CameraComponent#calculateTransform and CameraComponent#calculateProjection. - [CalculateSortDistanceCallback](https://api.playcanvas.com/engine/types/CalculateSortDistanceCallback.md): Callback used by Layer to calculate the "sort distance" for a MeshInstance, which determines its place in the render... - [ChangeSceneCallback](https://api.playcanvas.com/engine/types/ChangeSceneCallback.md): Callback used by SceneRegistry#changeScene. - [ComponentMap](https://api.playcanvas.com/engine/types/ComponentMap.md) - [ComponentName](https://api.playcanvas.com/engine/types/ComponentName.md) - [ComponentOptions](https://api.playcanvas.com/engine/types/ComponentOptions.md) - [ConfigureAppCallback](https://api.playcanvas.com/engine/types/ConfigureAppCallback.md): Callback used by AppBase#configure when configuration file is loaded and parsed (or an error occurs). - [CreateScreenCallback](https://api.playcanvas.com/engine/types/CreateScreenCallback.md): Callback used by script.createLoadingScreen. - [DataType](https://api.playcanvas.com/engine/types/DataType.md) - [FilterAssetCallback](https://api.playcanvas.com/engine/types/FilterAssetCallback.md): Callback used by AssetRegistry#filter to filter assets. - [FindNodeCallback](https://api.playcanvas.com/engine/types/FindNodeCallback.md): Callback used by GraphNode#find and GraphNode#findOne to search through a graph node and all of its descendants. - [ForEachNodeCallback](https://api.playcanvas.com/engine/types/ForEachNodeCallback.md): Callback used by GraphNode#forEach to iterate through a graph node and all of its descendants. - [GizmoAxis](https://api.playcanvas.com/engine/types/GizmoAxis.md) - [GizmoDragMode](https://api.playcanvas.com/engine/types/GizmoDragMode.md) - [GizmoSpace](https://api.playcanvas.com/engine/types/GizmoSpace.md) - [HandleEventCallback](https://api.playcanvas.com/engine/types/HandleEventCallback.md): Callback used by EventHandler functions. - [HttpResponseCallback](https://api.playcanvas.com/engine/types/HttpResponseCallback.md): Callback used by Http#get, Http#post, Http#put, Http#del, and Http#request. - [LoadAssetCallback](https://api.playcanvas.com/engine/types/LoadAssetCallback.md): Callback used by AssetRegistry#loadFromUrl and called when an asset is loaded (or an error occurs). - [LoadHierarchyCallback](https://api.playcanvas.com/engine/types/LoadHierarchyCallback.md): Callback used by SceneRegistry#loadSceneHierarchy. - [LoadSceneCallback](https://api.playcanvas.com/engine/types/LoadSceneCallback.md): Callback used by SceneRegistry#loadScene. - [LoadSceneDataCallback](https://api.playcanvas.com/engine/types/LoadSceneDataCallback.md): Callback used by SceneRegistry#loadSceneData. - [LoadSettingsCallback](https://api.playcanvas.com/engine/types/LoadSettingsCallback.md): Callback used by SceneRegistry#loadSceneSettings. - [LockMouseCallback](https://api.playcanvas.com/engine/types/LockMouseCallback.md): Callback used by Mouse#enablePointerLock and Mouse#disablePointerLock. - [ModuleErrorCallback](https://api.playcanvas.com/engine/types/ModuleErrorCallback.md): Callback used by WasmModule.setConfig. - [ModuleInstanceCallback](https://api.playcanvas.com/engine/types/ModuleInstanceCallback.md): Callback used by WasmModule.getInstance. - [NumericArray](https://api.playcanvas.com/engine/types/NumericArray.md) - [PreloadAppCallback](https://api.playcanvas.com/engine/types/PreloadAppCallback.md): Callback used by AppBase#preload when all assets (marked as 'preload') are loaded. - [ResourceHandlerCallback](https://api.playcanvas.com/engine/types/ResourceHandlerCallback.md): Callback used by ResourceHandler#load when a resource is loaded (or an error occurs). - [ResourceLoaderCallback](https://api.playcanvas.com/engine/types/ResourceLoaderCallback.md): Callback used by ResourceLoader#load when a resource is loaded (or an error occurs). - [UpdateShaderCallback](https://api.playcanvas.com/engine/types/UpdateShaderCallback.md): Callback used by StandardMaterial#onUpdateShader. - [XrAnchorCreateCallback](https://api.playcanvas.com/engine/types/XrAnchorCreateCallback.md): Callback used by XrAnchors#create. - [XrAnchorForgetCallback](https://api.playcanvas.com/engine/types/XrAnchorForgetCallback.md): Callback used by XrAnchor#forget. - [XrAnchorPersistCallback](https://api.playcanvas.com/engine/types/XrAnchorPersistCallback.md): Callback used by XrAnchor#persist. - [XrErrorCallback](https://api.playcanvas.com/engine/types/XrErrorCallback.md): Callback used by XrManager#start and XrManager#end. - [XrHitTestStartCallback](https://api.playcanvas.com/engine/types/XrHitTestStartCallback.md): Callback used by XrHitTest#start and XrInputSource#hitTestStart. - [XrRoomCaptureCallback](https://api.playcanvas.com/engine/types/XrRoomCaptureCallback.md): Callback used by XrManager#initiateRoomCapture. -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/constants.md # Engine API Reference: Constants 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/.md`. ## Animation - `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` = 0 ## Asset - `ASSET_*`: `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' ## Debug - `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' ## Graphics - `ADDRESS_*`: `ADDRESS_CLAMP_TO_EDGE` = 1, `ADDRESS_MIRRORED_REPEAT` = 2, `ADDRESS_REPEAT` = 0 - `ASPECT_*`: `ASPECT_AUTO` = 0, `ASPECT_MANUAL` = 1 - `BAKE_*`: `BAKE_COLOR` = 0, `BAKE_COLORDIR` = 1 - `BLEND_*`: `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` = 0 - `BLENDEQUATION_*`: `BLENDEQUATION_ADD` = 0, `BLENDEQUATION_MAX` = 4, `BLENDEQUATION_MIN` = 3, `BLENDEQUATION_REVERSE_SUBTRACT` = 2, `BLENDEQUATION_SUBTRACT` = 1 - `BLENDMODE_*`: `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` = 0 - `BLUR_*`: `BLUR_BOX` = 0, `BLUR_GAUSSIAN` = 1 - `BUFFER_*`: `BUFFER_DYNAMIC` = 1, `BUFFER_GPUDYNAMIC` = 3, `BUFFER_STATIC` = 0, `BUFFER_STREAM` = 2 - `BUFFERUSAGE_*`: `BUFFERUSAGE_COPY_DST` = 0x0008, `BUFFERUSAGE_COPY_SRC` = 0x0004, `BUFFERUSAGE_INDEX` = 0x0010, `BUFFERUSAGE_READ` = 0x0001, `BUFFERUSAGE_UNIFORM` = 0x0040, `BUFFERUSAGE_VERTEX` = 0x0020, `BUFFERUSAGE_WRITE` = 0x0002 - `CLEARFLAG_*`: `CLEARFLAG_COLOR` = 1, `CLEARFLAG_DEPTH` = 2, `CLEARFLAG_STENCIL` = 4 - `CUBEFACE_*`: `CUBEFACE_NEGX` = 1, `CUBEFACE_NEGY` = 3, `CUBEFACE_NEGZ` = 5, `CUBEFACE_POSX` = 0, `CUBEFACE_POSY` = 2, `CUBEFACE_POSZ` = 4 - `CUBEPROJ_*`: `CUBEPROJ_BOX` = 1, `CUBEPROJ_NONE` = 0 - `CULLFACE_*`: `CULLFACE_BACK` = 1, `CULLFACE_FRONT` = 2, `CULLFACE_NONE` = 0 - `DEPTHRESOLVE_*`: `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` = 1 - `FILTER_*`: `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` = 2 - `FOG_*`: `FOG_EXP` = 'exp', `FOG_EXP2` = 'exp2', `FOG_LINEAR` = 'linear', `FOG_NONE` = 'none' - `FRESNEL_*`: `FRESNEL_NONE` = 0, `FRESNEL_SCHLICK` = 2 - `FRONTFACE_*`: `FRONTFACE_CCW` = 0, `FRONTFACE_CW` = 1 - `FUNC_*`: `FUNC_ALWAYS` = 7, `FUNC_EQUAL` = 2, `FUNC_GREATER` = 4, `FUNC_GREATEREQUAL` = 6, `FUNC_LESS` = 1, `FUNC_LESSEQUAL` = 3, `FUNC_NEVER` = 0, `FUNC_NOTEQUAL` = 5 - `GAMMA_*`: `GAMMA_NONE` = 0, `GAMMA_SRGB` = 1 - `GSPLAT_*`: `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` = 0 - `GSPLATDATA_*`: `GSPLATDATA_COMPACT` = 'compact', `GSPLATDATA_LARGE` = 'large' - `INDEXFORMAT_*`: `INDEXFORMAT_UINT16` = 1, `INDEXFORMAT_UINT32` = 2, `INDEXFORMAT_UINT8` = 0 - `LAYERID_*`: `LAYERID_DEPTH` = 1, `LAYERID_IMMEDIATE` = 3, `LAYERID_SKYBOX` = 2, `LAYERID_UI` = 4, `LAYERID_WORLD` = 0 - `LIGHTFALLOFF_*`: `LIGHTFALLOFF_INVERSESQUARED` = 1, `LIGHTFALLOFF_LINEAR` = 0 - `LIGHTSHAPE_*`: `LIGHTSHAPE_DISK` = 2, `LIGHTSHAPE_PUNCTUAL` = 0, `LIGHTSHAPE_RECT` = 1, `LIGHTSHAPE_SPHERE` = 3 - `LIGHTTYPE_*`: `LIGHTTYPE_DIRECTIONAL` = 0, `LIGHTTYPE_OMNI` = 1, `LIGHTTYPE_SPOT` = 2 - `ORIENTATION_*`: `ORIENTATION_HORIZONTAL` = 0, `ORIENTATION_VERTICAL` = 1 - `PARALLAX_*`: `PARALLAX_OCCLUSION` = 'occlusion', `PARALLAX_OFFSET` = 'offset' - `PARTICLEORIENTATION_*`: `PARTICLEORIENTATION_EMITTER` = 2, `PARTICLEORIENTATION_SCREEN` = 0, `PARTICLEORIENTATION_WORLD` = 1 - `PARTICLESORT_*`: `PARTICLESORT_DISTANCE` = 1, `PARTICLESORT_NEWER_FIRST` = 2, `PARTICLESORT_NONE` = 0, `PARTICLESORT_OLDER_FIRST` = 3 - `PIXELFORMAT_*`: `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` = 20 - `PRIMITIVE_*`: `PRIMITIVE_LINELOOP` = 2, `PRIMITIVE_LINES` = 1, `PRIMITIVE_LINESTRIP` = 3, `PRIMITIVE_POINTS` = 0, `PRIMITIVE_TRIANGLES` = 4, `PRIMITIVE_TRIFAN` = 6, `PRIMITIVE_TRISTRIP` = 5 - `PROJECTION_*`: `PROJECTION_ORTHOGRAPHIC` = 1, `PROJECTION_PERSPECTIVE` = 0 - `RENDERSTYLE_*`: `RENDERSTYLE_POINTS` = 2, `RENDERSTYLE_SOLID` = 0, `RENDERSTYLE_WIREFRAME` = 1 - `RENDERTARGET_*`: `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` = 1 - `SEMANTIC_*`: `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` = 0 - `SHADERLANGUAGE_*`: `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` = 1 - `SHADOW_*`: `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` = 3 - `SHADOWUPDATE_*`: `SHADOWUPDATE_NONE` = 0, `SHADOWUPDATE_REALTIME` = 2, `SHADOWUPDATE_THISFRAME` = 1 - `SKYTYPE_*`: `SKYTYPE_BOX` = 'box', `SKYTYPE_DOME` = 'dome', `SKYTYPE_INFINITE` = 'infinite' - `SORTMODE_*`: `SORTMODE_BACK2FRONT` = 3, `SORTMODE_FRONT2BACK` = 4, `SORTMODE_MANUAL` = 1, `SORTMODE_MATERIALMESH` = 2, `SORTMODE_NONE` = 0 - `SPECOCC_*`: `SPECOCC_AO` = 1, `SPECOCC_GLOSSDEPENDENT` = 2, `SPECOCC_NONE` = 0 - `SPRITE_*`: `SPRITE_RENDERMODE_SIMPLE` = 0, `SPRITE_RENDERMODE_SLICED` = 1, `SPRITE_RENDERMODE_TILED` = 2 - `SPRITETYPE_*`: `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` = 1 - `TEXTUREDIMENSION_*`: `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` = 2 - `TEXTUREPROJECTION_*`: `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` = 6 - `TRANSFORM_*`: `TRANSFORM_FEEDBACK_INTERLEAVED` = 0, `TRANSFORM_FEEDBACK_SEPARATE` = 1 - `TYPE_*`: `TYPE_FLOAT16` = 7, `TYPE_FLOAT32` = 6, `TYPE_INT16` = 2, `TYPE_INT32` = 4, `TYPE_INT8` = 0, `TYPE_UINT16` = 3, `TYPE_UINT32` = 5, `TYPE_UINT8` = 1 - `UNIFORMTYPE_*`: `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` = 5 - `VIEW_*`: `VIEW_CENTER` = 0, `VIEW_LEFT` = 1, `VIEW_RIGHT` = 2 - `WORKBUFFER_*`: `WORKBUFFER_UPDATE_ALWAYS` = 2, `WORKBUFFER_UPDATE_AUTO` = 0, `WORKBUFFER_UPDATE_ONCE` = 1 ## Input Devices - `KEY_*`: `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` = 90 - `MOUSEBUTTON_*`: `MOUSEBUTTON_LEFT` = 0, `MOUSEBUTTON_MIDDLE` = 1, `MOUSEBUTTON_NONE` = -1, `MOUSEBUTTON_RIGHT` = 2 - `PAD_*`: `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` = 16 - `XRPAD_*`: `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` = 0 ## Math - `CURVE_*`: `CURVE_LINEAR` = 0, `CURVE_SMOOTHSTEP` = 1, `CURVE_SPLINE` = 4, `CURVE_STEP` = 5 - `math.DEG_TO_RAD` - `math.RAD_TO_DEG` ## Physics - `BODYTYPE_*`: `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' ## Sound - `DISTANCE_*`: `DISTANCE_EXPONENTIAL` = 'exponential', `DISTANCE_INVERSE` = 'inverse', `DISTANCE_LINEAR` = 'linear' ## User Interface - `BUTTON_*`: `BUTTON_TRANSITION_MODE_SPRITE_CHANGE` = 1, `BUTTON_TRANSITION_MODE_TINT` = 0 - `ELEMENTTYPE_*`: `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` = 1 - `SCALEMODE_*`: `SCALEMODE_BLEND` = 'blend', `SCALEMODE_NONE` = 'none' - `SCROLL_*`: `SCROLL_MODE_BOUNCE` = 1, `SCROLL_MODE_CLAMP` = 0, `SCROLL_MODE_INFINITE` = 2 - `SCROLLBAR_*`: `SCROLLBAR_VISIBILITY_SHOW_ALWAYS` = 0, `SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED` = 1 ## XR - `XRDEPTHSENSINGFORMAT_*`: `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' ## Other - `FILLMODE_*`: `FILLMODE_FILL_WINDOW` = 'FILL_WINDOW', `FILLMODE_KEEP_ASPECT` = 'KEEP_ASPECT', `FILLMODE_NONE` = 'NONE' - `LINECAP_*`: `LINECAP_BUTT` = 0, `LINECAP_ROUND` = 2, `LINECAP_SQUARE` = 1 - `LINEJOIN_*`: `LINEJOIN_BEVEL` = 1, `LINEJOIN_MITER` = 0, `LINEJOIN_ROUND` = 2 - `LINEWIDTH_*`: `LINEWIDTH_SCREEN` = 0, `LINEWIDTH_WORLD` = 1 - `RESOLUTION_*`: `RESOLUTION_AUTO` = 'AUTO', `RESOLUTION_FIXED` = 'FIXED' - `string.ASCII_*`: `string.ASCII_LETTERS` = ASCII_LETTERS, `string.ASCII_LOWERCASE` = ASCII_LOWERCASE, `string.ASCII_UPPERCASE` = ASCII_UPPERCASE -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/math.DEG_TO_RAD.md # math.DEG_TO_RAD Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L13 Conversion factor between degrees and radians. ```ts const DEG_TO_RAD: number ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/math.RAD_TO_DEG.md # math.RAD_TO_DEG Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L20 Conversion factor between radians and degrees. ```ts const RAD_TO_DEG: number ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/string.ASCII_LETTERS.md # string.ASCII_LETTERS Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L125 All ASCII letters. ```ts const ASCII_LETTERS: string = ASCII_LETTERS ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/string.ASCII_LOWERCASE.md # string.ASCII_LOWERCASE Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L111 All lowercase letters. ```ts const ASCII_LOWERCASE: string = ASCII_LOWERCASE ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/string.ASCII_UPPERCASE.md # string.ASCII_UPPERCASE Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L118 All uppercase letters. ```ts const ASCII_UPPERCASE: string = ASCII_UPPERCASE ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ADDRESS_CLAMP_TO_EDGE.md # ADDRESS_CLAMP_TO_EDGE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L13 Clamps texture coordinate to the range 0 to 1. ```ts const ADDRESS_CLAMP_TO_EDGE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ADDRESS_MIRRORED_REPEAT.md # ADDRESS_MIRRORED_REPEAT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L21 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. ```ts const ADDRESS_MIRRORED_REPEAT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ADDRESS_REPEAT.md # ADDRESS_REPEAT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L6 Ignores the integer part of texture coordinates, using only the fractional part. ```ts const ADDRESS_REPEAT: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_BLEND_1D.md # ANIM_BLEND_1D Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L112 ```ts const ANIM_BLEND_1D: string = '1D' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_BLEND_2D_CARTESIAN.md # ANIM_BLEND_2D_CARTESIAN Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L124 ```ts const ANIM_BLEND_2D_CARTESIAN: string = '2D_CARTESIAN' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_BLEND_2D_DIRECTIONAL.md # ANIM_BLEND_2D_DIRECTIONAL Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L118 ```ts const ANIM_BLEND_2D_DIRECTIONAL: string = '2D_DIRECTIONAL' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_BLEND_DIRECT.md # ANIM_BLEND_DIRECT Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L130 ```ts const ANIM_BLEND_DIRECT: string = 'DIRECT' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_EQUAL_TO.md # ANIM_EQUAL_TO Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L71 Used to set an anim state graph transition condition predicate as '==='. ```ts const ANIM_EQUAL_TO: "EQUAL_TO" = 'EQUAL_TO' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_GREATER_THAN.md # ANIM_GREATER_THAN Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L43 Used to set an anim state graph transition condition predicate as '>'. ```ts const ANIM_GREATER_THAN: "GREATER_THAN" = 'GREATER_THAN' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_GREATER_THAN_EQUAL_TO.md # ANIM_GREATER_THAN_EQUAL_TO Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L57 Used to set an anim state graph transition condition predicate as '>='. ```ts const ANIM_GREATER_THAN_EQUAL_TO: "GREATER_THAN_EQUAL_TO" = 'GREATER_THAN_EQUAL_TO' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_INTERRUPTION_NEXT.md # ANIM_INTERRUPTION_NEXT Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L20 Used to set the anim state graph transition interruption source as the next state only. ```ts const ANIM_INTERRUPTION_NEXT: "NEXT_STATE" = 'NEXT_STATE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_INTERRUPTION_NEXT_PREV.md # ANIM_INTERRUPTION_NEXT_PREV Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L36 Used to set the anim state graph transition interruption sources as the next state followed by the previous state. ```ts const ANIM_INTERRUPTION_NEXT_PREV: "NEXT_STATE_PREV_STATE" = 'NEXT_STATE_PREV_STATE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_INTERRUPTION_NONE.md # ANIM_INTERRUPTION_NONE Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L6 Used to set the anim state graph transition interruption source to no state. ```ts const ANIM_INTERRUPTION_NONE: "NONE" = 'NONE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_INTERRUPTION_PREV.md # ANIM_INTERRUPTION_PREV Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L13 Used to set the anim state graph transition interruption source as the previous state only. ```ts const ANIM_INTERRUPTION_PREV: "PREV_STATE" = 'PREV_STATE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_INTERRUPTION_PREV_NEXT.md # ANIM_INTERRUPTION_PREV_NEXT Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L28 Used to set the anim state graph transition interruption sources as the previous state followed by the next state. ```ts const ANIM_INTERRUPTION_PREV_NEXT: "PREV_STATE_NEXT_STATE" = 'PREV_STATE_NEXT_STATE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_LAYER_ADDITIVE.md # ANIM_LAYER_ADDITIVE Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L167 Used to indicate that a layers animations should blend additively with previous layers. ```ts const ANIM_LAYER_ADDITIVE: "ADDITIVE" = 'ADDITIVE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_LAYER_OVERWRITE.md # ANIM_LAYER_OVERWRITE Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L160 Used to indicate that a layers animations should overwrite all previous layers. ```ts const ANIM_LAYER_OVERWRITE: "OVERWRITE" = 'OVERWRITE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_LESS_THAN.md # ANIM_LESS_THAN Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L50 Used to set an anim state graph transition condition predicate as '<'. ```ts const ANIM_LESS_THAN: "LESS_THAN" = 'LESS_THAN' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_LESS_THAN_EQUAL_TO.md # ANIM_LESS_THAN_EQUAL_TO Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L64 Used to set an anim state graph transition condition predicate as '<='. ```ts const ANIM_LESS_THAN_EQUAL_TO: "LESS_THAN_EQUAL_TO" = 'LESS_THAN_EQUAL_TO' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_NOT_EQUAL_TO.md # ANIM_NOT_EQUAL_TO Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L78 Used to set an anim state graph transition condition predicate as '!=='. ```ts const ANIM_NOT_EQUAL_TO: "NOT_EQUAL_TO" = 'NOT_EQUAL_TO' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_PARAMETER_BOOLEAN.md # ANIM_PARAMETER_BOOLEAN Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L99 Used to set an anim state graph parameter as type boolean. ```ts const ANIM_PARAMETER_BOOLEAN: "BOOLEAN" = 'BOOLEAN' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_PARAMETER_FLOAT.md # ANIM_PARAMETER_FLOAT Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L92 Used to set an anim state graph parameter as type float. ```ts const ANIM_PARAMETER_FLOAT: "FLOAT" = 'FLOAT' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_PARAMETER_INTEGER.md # ANIM_PARAMETER_INTEGER Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L85 Used to set an anim state graph parameter as type integer. ```ts const ANIM_PARAMETER_INTEGER: "INTEGER" = 'INTEGER' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_PARAMETER_TRIGGER.md # ANIM_PARAMETER_TRIGGER Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L106 Used to set an anim state graph parameter as type trigger. ```ts const ANIM_PARAMETER_TRIGGER: "TRIGGER" = 'TRIGGER' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_STATE_ANY.md # ANIM_STATE_ANY Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L151 Used to indicate any state in an anim state graph layer. ```ts const ANIM_STATE_ANY: "ANY" = 'ANY' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_STATE_END.md # ANIM_STATE_END Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L144 The ending state in an anim state graph layer. ```ts const ANIM_STATE_END: "END" = 'END' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ANIM_STATE_START.md # ANIM_STATE_START Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L137 The starting state in an anim state graph layer. ```ts const ANIM_STATE_START: "START" = 'START' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASPECT_AUTO.md # ASPECT_AUTO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1047 Automatically set aspect ratio to current render target's width divided by height. ```ts const ASPECT_AUTO: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASPECT_MANUAL.md # ASPECT_MANUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1054 Use the manual aspect ratio value. ```ts const ASPECT_MANUAL: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_ANIMATION.md # ASSET_ANIMATION Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L29 Asset type name for animation. ```ts const ASSET_ANIMATION: "animation" = 'animation' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_AUDIO.md # ASSET_AUDIO Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L36 Asset type name for audio. ```ts const ASSET_AUDIO: "audio" = 'audio' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_CONTAINER.md # ASSET_CONTAINER Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L129 Asset type name for a container. ```ts const ASSET_CONTAINER: "container" = 'container' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_CSS.md # ASSET_CSS Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L108 Asset type name for CSS. ```ts const ASSET_CSS: "css" = 'css' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_CUBEMAP.md # ASSET_CUBEMAP Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L94 Asset type name for cubemap. ```ts const ASSET_CUBEMAP: "cubemap" = 'cubemap' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_HTML.md # ASSET_HTML Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L115 Asset type name for HTML. ```ts const ASSET_HTML: "html" = 'html' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_IMAGE.md # ASSET_IMAGE Variable · category: Asset · deprecated Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L45 Asset type name for image. **Deprecated**: No resource handler is registered for `'image'` assets. Use [ASSET_TEXTURE](https://api.playcanvas.com/engine/variables/ASSET_TEXTURE.md) instead. ```ts const ASSET_IMAGE: "image" = 'image' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_JSON.md # ASSET_JSON Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L52 Asset type name for json. ```ts const ASSET_JSON: "json" = 'json' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_MATERIAL.md # ASSET_MATERIAL Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L66 Asset type name for material. ```ts const ASSET_MATERIAL: "material" = 'material' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_MODEL.md # ASSET_MODEL Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L59 Asset type name for model. ```ts const ASSET_MODEL: "model" = 'model' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_SCRIPT.md # ASSET_SCRIPT Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L122 Asset type name for script. ```ts const ASSET_SCRIPT: "script" = 'script' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_SHADER.md # ASSET_SHADER Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L101 Asset type name for shader. ```ts const ASSET_SHADER: "shader" = 'shader' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_TEXT.md # ASSET_TEXT Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L73 Asset type name for text. ```ts const ASSET_TEXT: "text" = 'text' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_TEXTURE.md # ASSET_TEXTURE Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L80 Asset type name for texture. ```ts const ASSET_TEXTURE: "texture" = 'texture' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ASSET_TEXTUREATLAS.md # ASSET_TEXTUREATLAS Variable · category: Asset Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L87 Asset type name for textureatlas. ```ts const ASSET_TEXTUREATLAS: "textureatlas" = 'textureatlas' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BAKE_COLOR.md # BAKE_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L966 Single color lightmap. ```ts const BAKE_COLOR: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BAKE_COLORDIR.md # BAKE_COLORDIR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L973 Single color lightmap + dominant light direction (used for bump/specular). ```ts const BAKE_COLORDIR: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_ADDITIVE.md # BLEND_ADDITIVE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L17 Add the color of the source fragment to the destination fragment and write the result to the frame buffer. ```ts const BLEND_ADDITIVE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_ADDITIVEALPHA.md # BLEND_ADDITIVEALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L56 Same as [BLEND_ADDITIVE](https://api.playcanvas.com/engine/variables/BLEND_ADDITIVE.md) except the source RGB is multiplied by the source alpha. ```ts const BLEND_ADDITIVEALPHA: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_MAX.md # BLEND_MAX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L84 Maximum color. ```ts const BLEND_MAX: 10 = 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_MIN.md # BLEND_MIN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L77 Minimum color. ```ts const BLEND_MIN: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_MULTIPLICATIVE.md # BLEND_MULTIPLICATIVE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L49 Multiply the color of the source fragment by the color of the destination fragment and write the result to the frame buffer. ```ts const BLEND_MULTIPLICATIVE: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_MULTIPLICATIVE2X.md # BLEND_MULTIPLICATIVE2X Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L63 Multiplies colors and doubles the result. ```ts const BLEND_MULTIPLICATIVE2X: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_NONE.md # BLEND_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L33 Disable blending. ```ts const BLEND_NONE: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_NORMAL.md # BLEND_NORMAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L26 Enable simple translucency for materials such as glass. This is equivalent to enabling a source blend mode of [BLENDMODE_SRC_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_ALPHA.md) and a destination blend mode of [BLENDMODE_ONE_MINUS_SRC_ALPHA](https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC_ALPHA.md). ```ts const BLEND_NORMAL: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_PREMULTIPLIED.md # BLEND_PREMULTIPLIED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L41 Similar to [BLEND_NORMAL](https://api.playcanvas.com/engine/variables/BLEND_NORMAL.md) expect the source fragment is assumed to have already been multiplied by the source alpha value. ```ts const BLEND_PREMULTIPLIED: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_SCREEN.md # BLEND_SCREEN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L70 Softer version of additive. ```ts const BLEND_SCREEN: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLEND_SUBTRACTIVE.md # BLEND_SUBTRACTIVE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L9 Subtract the color of the source fragment from the destination fragment and write the result to the frame buffer. ```ts const BLEND_SUBTRACTIVE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDEQUATION_ADD.md # BLENDEQUATION_ADD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L151 Add the results of the source and destination fragment multiplies. ```ts const BLENDEQUATION_ADD: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDEQUATION_MAX.md # BLENDEQUATION_MAX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L179 Use the largest value. ```ts const BLENDEQUATION_MAX: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDEQUATION_MIN.md # BLENDEQUATION_MIN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L172 Use the smallest value. ```ts const BLENDEQUATION_MIN: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDEQUATION_REVERSE_SUBTRACT.md # BLENDEQUATION_REVERSE_SUBTRACT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L165 Reverse and subtract the results of the source and destination fragment multiplies. ```ts const BLENDEQUATION_REVERSE_SUBTRACT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDEQUATION_SUBTRACT.md # BLENDEQUATION_SUBTRACT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L158 Subtract the results of the source and destination fragment multiplies. ```ts const BLENDEQUATION_SUBTRACT: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_CONSTANT.md # BLENDMODE_CONSTANT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L105 Multiplies all fragment components by a constant. ```ts const BLENDMODE_CONSTANT: 11 = 11 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_DST_ALPHA.md # BLENDMODE_DST_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L91 Multiply all fragment components by the alpha value of the destination fragment. ```ts const BLENDMODE_DST_ALPHA: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_DST_COLOR.md # BLENDMODE_DST_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L56 Multiply all fragment components by the components of the destination fragment. ```ts const BLENDMODE_DST_COLOR: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE.md # BLENDMODE_ONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L35 Multiply all fragment components by one. ```ts const BLENDMODE_ONE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_CONSTANT.md # BLENDMODE_ONE_MINUS_CONSTANT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L112 Multiplies all fragment components by 1 minus a constant. ```ts const BLENDMODE_ONE_MINUS_CONSTANT: 12 = 12 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_DST_ALPHA.md # BLENDMODE_ONE_MINUS_DST_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L98 Multiply all fragment components by one minus the alpha value of the destination fragment. ```ts const BLENDMODE_ONE_MINUS_DST_ALPHA: 10 = 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_DST_COLOR.md # BLENDMODE_ONE_MINUS_DST_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L63 Multiply all fragment components by one minus the components of the destination fragment. ```ts const BLENDMODE_ONE_MINUS_DST_COLOR: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC_ALPHA.md # BLENDMODE_ONE_MINUS_SRC_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L84 Multiply all fragment components by one minus the alpha value of the source fragment. ```ts const BLENDMODE_ONE_MINUS_SRC_ALPHA: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC_COLOR.md # BLENDMODE_ONE_MINUS_SRC_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L49 Multiply all fragment components by one minus the components of the source fragment. ```ts const BLENDMODE_ONE_MINUS_SRC_COLOR: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC1_ALPHA.md # BLENDMODE_ONE_MINUS_SRC1_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L144 Multiply all fragment components by one minus the alpha value of the secondary source fragment. This can only be used when [GraphicsDevice#supportsDualSourceBlending](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsdualsourceblending) is true. ```ts const BLENDMODE_ONE_MINUS_SRC1_ALPHA: 16 = 16 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ONE_MINUS_SRC1_COLOR.md # BLENDMODE_ONE_MINUS_SRC1_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L128 Multiply all fragment components by one minus the components of the secondary source fragment. This can only be used when [GraphicsDevice#supportsDualSourceBlending](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsdualsourceblending) is true. ```ts const BLENDMODE_ONE_MINUS_SRC1_COLOR: 14 = 14 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_ALPHA.md # BLENDMODE_SRC_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L70 Multiply all fragment components by the alpha value of the source fragment. ```ts const BLENDMODE_SRC_ALPHA: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_ALPHA_SATURATE.md # BLENDMODE_SRC_ALPHA_SATURATE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L77 Multiply all fragment components by the alpha value of the source fragment. ```ts const BLENDMODE_SRC_ALPHA_SATURATE: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_SRC_COLOR.md # BLENDMODE_SRC_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L42 Multiply all fragment components by the components of the source fragment. ```ts const BLENDMODE_SRC_COLOR: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_SRC1_ALPHA.md # BLENDMODE_SRC1_ALPHA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L136 Multiply all fragment components by the alpha value of the secondary source fragment. This can only be used when [GraphicsDevice#supportsDualSourceBlending](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsdualsourceblending) is true. ```ts const BLENDMODE_SRC1_ALPHA: 15 = 15 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_SRC1_COLOR.md # BLENDMODE_SRC1_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L120 Multiply all fragment components by the components of the secondary source fragment. This can only be used when [GraphicsDevice#supportsDualSourceBlending](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#supportsdualsourceblending) is true. ```ts const BLENDMODE_SRC1_COLOR: 13 = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLENDMODE_ZERO.md # BLENDMODE_ZERO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L28 Multiply all fragment components by zero. ```ts const BLENDMODE_ZERO: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLUR_BOX.md # BLUR_BOX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L451 Box filter. ```ts const BLUR_BOX: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BLUR_GAUSSIAN.md # BLUR_GAUSSIAN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L458 Gaussian filter. May look smoother than box, but requires more samples. ```ts const BLUR_GAUSSIAN: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BODYTYPE_DYNAMIC.md # BODYTYPE_DYNAMIC Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L13 Rigid body is simulated according to applied forces. ```ts const BODYTYPE_DYNAMIC: "dynamic" = 'dynamic' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BODYTYPE_KINEMATIC.md # BODYTYPE_KINEMATIC Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L21 Rigid body has infinite mass and does not respond to forces. It is moved by setting the position and rotation of its entity. ```ts const BODYTYPE_KINEMATIC: "kinematic" = 'kinematic' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BODYTYPE_STATIC.md # BODYTYPE_STATIC Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L6 Rigid body has infinite mass and cannot move. ```ts const BODYTYPE_STATIC: "static" = 'static' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFER_DYNAMIC.md # BUFFER_DYNAMIC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L269 The data store contents will be modified repeatedly and used many times. ```ts const BUFFER_DYNAMIC: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFER_GPUDYNAMIC.md # BUFFER_GPUDYNAMIC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L284 The data store contents will be modified repeatedly on the GPU and used many times. Optimal for transform feedback usage. ```ts const BUFFER_GPUDYNAMIC: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFER_STATIC.md # BUFFER_STATIC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L262 The data store contents will be modified once and used many times. ```ts const BUFFER_STATIC: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFER_STREAM.md # BUFFER_STREAM Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L276 The data store contents will be modified once and used at most a few times. ```ts const BUFFER_STREAM: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_COPY_DST.md # BUFFERUSAGE_COPY_DST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L211 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to ensure its compatibility when used as a destination of a copy operation, or as a target of a write operation. ```ts const BUFFERUSAGE_COPY_DST: 8 = 0x0008 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_COPY_SRC.md # BUFFERUSAGE_COPY_SRC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L203 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to ensure its compatibility when used as a source of a copy operation. ```ts const BUFFERUSAGE_COPY_SRC: 4 = 0x0004 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_INDEX.md # BUFFERUSAGE_INDEX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L219 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to ensure its compatibility when used as an index buffer. ```ts const BUFFERUSAGE_INDEX: 16 = 0x0010 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_READ.md # BUFFERUSAGE_READ Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L187 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to make it available for read access by CPU. ```ts const BUFFERUSAGE_READ: 1 = 0x0001 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_UNIFORM.md # BUFFERUSAGE_UNIFORM Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L235 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to ensure its compatibility when used as an uniform buffer. ```ts const BUFFERUSAGE_UNIFORM: 64 = 0x0040 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_VERTEX.md # BUFFERUSAGE_VERTEX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L227 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to ensure its compatibility when used as a vertex buffer. ```ts const BUFFERUSAGE_VERTEX: 32 = 0x0020 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUFFERUSAGE_WRITE.md # BUFFERUSAGE_WRITE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L195 A flag utilized during the construction of a [StorageBuffer](https://api.playcanvas.com/engine/classes/StorageBuffer.md) to make it available for write access by CPU. ```ts const BUFFERUSAGE_WRITE: 2 = 0x0002 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUTTON_TRANSITION_MODE_SPRITE_CHANGE.md # BUTTON_TRANSITION_MODE_SPRITE_CHANGE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/constants.js#L13 Specifies different sprites for the hover, pressed and inactive states. ```ts const BUTTON_TRANSITION_MODE_SPRITE_CHANGE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/BUTTON_TRANSITION_MODE_TINT.md # BUTTON_TRANSITION_MODE_TINT Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/constants.js#L6 Specifies different color tints for the hover, pressed and inactive states. ```ts const BUTTON_TRANSITION_MODE_TINT: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CLEARFLAG_COLOR.md # CLEARFLAG_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L305 Clear the color buffer. ```ts const CLEARFLAG_COLOR: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CLEARFLAG_DEPTH.md # CLEARFLAG_DEPTH Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L312 Clear the depth buffer. ```ts const CLEARFLAG_DEPTH: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CLEARFLAG_STENCIL.md # CLEARFLAG_STENCIL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L319 Clear the stencil buffer. ```ts const CLEARFLAG_STENCIL: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_NEGX.md # CUBEFACE_NEGX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L333 The negative X face of a cubemap. ```ts const CUBEFACE_NEGX: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_NEGY.md # CUBEFACE_NEGY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L347 The negative Y face of a cubemap. ```ts const CUBEFACE_NEGY: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_NEGZ.md # CUBEFACE_NEGZ Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L361 The negative Z face of a cubemap. ```ts const CUBEFACE_NEGZ: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_POSX.md # CUBEFACE_POSX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L326 The positive X face of a cubemap. ```ts const CUBEFACE_POSX: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_POSY.md # CUBEFACE_POSY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L340 The positive Y face of a cubemap. ```ts const CUBEFACE_POSY: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEFACE_POSZ.md # CUBEFACE_POSZ Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L354 The positive Z face of a cubemap. ```ts const CUBEFACE_POSZ: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEPROJ_BOX.md # CUBEPROJ_BOX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L574 The cube map is box-projected based on a world space axis-aligned bounding box. ```ts const CUBEPROJ_BOX: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CUBEPROJ_NONE.md # CUBEPROJ_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L567 The cube map is treated as if it is infinitely far away. ```ts const CUBEPROJ_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CULLFACE_BACK.md # CULLFACE_BACK Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L430 Triangles facing away from the view direction are culled. ```ts const CULLFACE_BACK: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CULLFACE_FRONT.md # CULLFACE_FRONT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L437 Triangles facing the view direction are culled. ```ts const CULLFACE_FRONT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CULLFACE_NONE.md # CULLFACE_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L423 No triangles are culled. ```ts const CULLFACE_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CURVE_LINEAR.md # CURVE_LINEAR Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L6 A linear interpolation scheme. ```ts const CURVE_LINEAR: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CURVE_SMOOTHSTEP.md # CURVE_SMOOTHSTEP Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L13 A smooth step interpolation scheme. ```ts const CURVE_SMOOTHSTEP: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CURVE_SPLINE.md # CURVE_SPLINE Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L20 Cardinal spline interpolation scheme. For a Catmull-Rom spline, specify a curve tension of 0.5. ```ts const CURVE_SPLINE: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/CURVE_STEP.md # CURVE_STEP Variable · category: Math Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L27 A stepped interpolator that does not perform any blending. ```ts const CURVE_STEP: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_MAX.md # DEPTHRESOLVE_MAX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L416 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](https://api.playcanvas.com/engine/classes/RenderTarget.md#depthresolvemode). ```ts const DEPTHRESOLVE_MAX: "max" = 'max' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_MIN.md # DEPTHRESOLVE_MIN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L407 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](https://api.playcanvas.com/engine/classes/RenderTarget.md#depthresolvemode). ```ts const DEPTHRESOLVE_MIN: "min" = 'min' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEPTHRESOLVE_SAMPLE0.md # DEPTHRESOLVE_SAMPLE0 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L397 The depth value of the multisampled depth buffer is resolved by taking its sample at index 0. See [RenderTarget#depthResolveMode](https://api.playcanvas.com/engine/classes/RenderTarget.md#depthresolvemode). ```ts const DEPTHRESOLVE_SAMPLE0: "sample0" = 'sample0' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_ADD.md # DETAILMODE_ADD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L594 Add together the primary and secondary colors. ```ts const DETAILMODE_ADD: "add" = 'add' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_MAX.md # DETAILMODE_MAX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L622 Select whichever of the primary and secondary colors is lighter, component-wise. ```ts const DETAILMODE_MAX: "max" = 'max' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_MIN.md # DETAILMODE_MIN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L615 Select whichever of the primary and secondary colors is darker, component-wise. ```ts const DETAILMODE_MIN: "min" = 'min' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_MUL.md # DETAILMODE_MUL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L587 Multiply together the primary and secondary colors. ```ts const DETAILMODE_MUL: "mul" = 'mul' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_OVERLAY.md # DETAILMODE_OVERLAY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L608 Multiplies or screens the colors, depending on the primary color. ```ts const DETAILMODE_OVERLAY: "overlay" = 'overlay' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DETAILMODE_SCREEN.md # DETAILMODE_SCREEN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L601 Softer version of [DETAILMODE_ADD](https://api.playcanvas.com/engine/variables/DETAILMODE_ADD.md). ```ts const DETAILMODE_SCREEN: "screen" = 'screen' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEVICETYPE_NULL.md # DEVICETYPE_NULL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2309 A Null device type. ```ts const DEVICETYPE_NULL: "null" = 'null' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2.md # DEVICETYPE_WEBGL2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2276 A WebGL 2 device type. ```ts const DEVICETYPE_WEBGL2: "webgl2" = 'webgl2' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGL2_BARE.md # DEVICETYPE_WEBGL2_BARE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2286 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). ```ts const DEVICETYPE_WEBGL2_BARE: "webgl2:bare" = 'webgl2:bare' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU.md # DEVICETYPE_WEBGPU Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2293 A WebGPU device type. ```ts const DEVICETYPE_WEBGPU: "webgpu" = 'webgpu' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DEVICETYPE_WEBGPU_BARE.md # DEVICETYPE_WEBGPU_BARE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2302 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). ```ts const DEVICETYPE_WEBGPU_BARE: "webgpu:bare" = 'webgpu:bare' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_HDR.md # DISPLAYFORMAT_HDR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2360 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](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR.md). Use [GraphicsDevice.isHdr](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#ishdr) to see if the HDR format is used. When it is, it's recommended to use [TONEMAP_NONE](https://api.playcanvas.com/engine/variables/TONEMAP_NONE.md) for the tonemapping mode, to avoid it clipping the high dynamic range. ```ts const DISPLAYFORMAT_HDR: "hdr" = 'hdr' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR.md # DISPLAYFORMAT_LDR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2339 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. ```ts const DISPLAYFORMAT_LDR: "ldr" = 'ldr' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR_SRGB.md # DISPLAYFORMAT_LDR_SRGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2349 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](https://api.playcanvas.com/engine/variables/DISPLAYFORMAT_LDR.md). ```ts const DISPLAYFORMAT_LDR_SRGB: "ldr_srgb" = 'ldr_srgb' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISTANCE_EXPONENTIAL.md # DISTANCE_EXPONENTIAL Variable · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L20 Exponential distance model. ```ts const DISTANCE_EXPONENTIAL: "exponential" = 'exponential' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISTANCE_INVERSE.md # DISTANCE_INVERSE Variable · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L13 Inverse distance model. ```ts const DISTANCE_INVERSE: "inverse" = 'inverse' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DISTANCE_LINEAR.md # DISTANCE_LINEAR Variable · category: Sound Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L6 Linear distance model. ```ts const DISTANCE_LINEAR: "linear" = 'linear' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_BAYER16.md # DITHER_BAYER16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1126 Opacity is dithered using a Bayer 16 matrix. ```ts const DITHER_BAYER16: "bayer16" = 'bayer16' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_BAYER2.md # DITHER_BAYER2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1105 Opacity is dithered using a Bayer 2 matrix. ```ts const DITHER_BAYER2: "bayer2" = 'bayer2' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_BAYER4.md # DITHER_BAYER4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1112 Opacity is dithered using a Bayer 4 matrix. ```ts const DITHER_BAYER4: "bayer4" = 'bayer4' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_BAYER8.md # DITHER_BAYER8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1119 Opacity is dithered using a Bayer 8 matrix. ```ts const DITHER_BAYER8: "bayer8" = 'bayer8' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_BLUENOISE.md # DITHER_BLUENOISE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1133 Opacity is dithered using a blue noise. ```ts const DITHER_BLUENOISE: "bluenoise" = 'bluenoise' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_IGNNOISE.md # DITHER_IGNNOISE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1140 Opacity is dithered using an interleaved gradient noise. ```ts const DITHER_IGNNOISE: "ignnoise" = 'ignnoise' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/DITHER_NONE.md # DITHER_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1098 Opacity dithering is disabled. ```ts const DITHER_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ELEMENTTYPE_GROUP.md # ELEMENTTYPE_GROUP Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L6 A [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) that contains child [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md)s. ```ts const ELEMENTTYPE_GROUP: "group" = 'group' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ELEMENTTYPE_IMAGE.md # ELEMENTTYPE_IMAGE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L13 A [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) that displays an image. ```ts const ELEMENTTYPE_IMAGE: "image" = 'image' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ELEMENTTYPE_TEXT.md # ELEMENTTYPE_TEXT Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L20 A [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.md) that displays text. ```ts const ELEMENTTYPE_TEXT: "text" = 'text' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/EMITTERSHAPE_BOX.md # EMITTERSHAPE_BOX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L496 Box shape parameterized by emitterExtents. Initial velocity is directed towards local Z axis. ```ts const EMITTERSHAPE_BOX: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/EMITTERSHAPE_SPHERE.md # EMITTERSHAPE_SPHERE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L504 Sphere shape parameterized by emitterRadius. Initial velocity is directed outwards from the center. ```ts const EMITTERSHAPE_SPHERE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILLMODE_FILL_WINDOW.md # FILLMODE_FILL_WINDOW Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L9 When resizing the window the size of the canvas will change to fill the window exactly. ```ts const FILLMODE_FILL_WINDOW: "FILL_WINDOW" = 'FILL_WINDOW' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILLMODE_KEEP_ASPECT.md # FILLMODE_KEEP_ASPECT Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L15 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. ```ts const FILLMODE_KEEP_ASPECT: "KEEP_ASPECT" = 'KEEP_ASPECT' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILLMODE_NONE.md # FILLMODE_NONE Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L4 When resizing the window the size of the canvas will not change. ```ts const FILLMODE_NONE: "NONE" = 'NONE' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_LINEAR.md # FILTER_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L474 Bilinear filtering. ```ts const FILTER_LINEAR: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_LINEAR_MIPMAP_LINEAR.md # FILTER_LINEAR_MIPMAP_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L502 Linearly interpolate both the mipmap levels and between texels. ```ts const FILTER_LINEAR_MIPMAP_LINEAR: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_LINEAR_MIPMAP_NEAREST.md # FILTER_LINEAR_MIPMAP_NEAREST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L495 Use the nearest neighbor after linearly interpolating between mipmap levels. ```ts const FILTER_LINEAR_MIPMAP_NEAREST: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_NEAREST.md # FILTER_NEAREST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L467 Point sample filtering. ```ts const FILTER_NEAREST: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_NEAREST_MIPMAP_LINEAR.md # FILTER_NEAREST_MIPMAP_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L488 Linearly interpolate in the nearest mipmap level. ```ts const FILTER_NEAREST_MIPMAP_LINEAR: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FILTER_NEAREST_MIPMAP_NEAREST.md # FILTER_NEAREST_MIPMAP_NEAREST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L481 Use the nearest neighbor in the nearest mipmap level. ```ts const FILTER_NEAREST_MIPMAP_NEAREST: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITMODE_CONTAIN.md # FITMODE_CONTAIN Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L34 Fit the content within the Element's bounding box while preserving its Aspect Ratio. ```ts const FITMODE_CONTAIN: "contain" = 'contain' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITMODE_COVER.md # FITMODE_COVER Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L41 Fit the content to cover the entire Element's bounding box while preserving its Aspect Ratio. ```ts const FITMODE_COVER: "cover" = 'cover' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITMODE_STRETCH.md # FITMODE_STRETCH Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L27 Fit the content exactly to Element's bounding box. ```ts const FITMODE_STRETCH: "stretch" = 'stretch' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITTING_BOTH.md # FITTING_BOTH Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L27 Apply both STRETCH and SHRINK fitting logic where applicable. ```ts const FITTING_BOTH: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITTING_NONE.md # FITTING_NONE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L6 Disable all fitting logic. ```ts const FITTING_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITTING_SHRINK.md # FITTING_SHRINK Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L20 Shrink child elements to fit the parent container. ```ts const FITTING_SHRINK: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FITTING_STRETCH.md # FITTING_STRETCH Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L13 Stretch child elements to fit the parent container. ```ts const FITTING_STRETCH: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FOG_EXP.md # FOG_EXP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L119 Fog rises according to an exponential curve controlled by a density value. ```ts const FOG_EXP: "exp" = 'exp' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FOG_EXP2.md # FOG_EXP2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L126 Fog rises according to an exponential curve controlled by a density value. ```ts const FOG_EXP2: "exp2" = 'exp2' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FOG_LINEAR.md # FOG_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L112 Fog rises linearly from zero to 1 between a start and end depth. ```ts const FOG_LINEAR: "linear" = 'linear' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FOG_NONE.md # FOG_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L105 No fog is applied to the scene. ```ts const FOG_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FRESNEL_NONE.md # FRESNEL_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L133 No Fresnel. ```ts const FRESNEL_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FRESNEL_SCHLICK.md # FRESNEL_SCHLICK Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L140 Schlick's approximation of Fresnel. ```ts const FRESNEL_SCHLICK: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FRONTFACE_CCW.md # FRONTFACE_CCW Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L453 The counterclockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation. ```ts const FRONTFACE_CCW: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FRONTFACE_CW.md # FRONTFACE_CW Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L460 The clockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation. ```ts const FRONTFACE_CW: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_ALWAYS.md # FUNC_ALWAYS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L558 Always pass. ```ts const FUNC_ALWAYS: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_EQUAL.md # FUNC_EQUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L523 Pass if (ref & mask) == (stencil & mask). ```ts const FUNC_EQUAL: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_GREATER.md # FUNC_GREATER Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L537 Pass if (ref & mask) > (stencil & mask). ```ts const FUNC_GREATER: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_GREATEREQUAL.md # FUNC_GREATEREQUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L551 Pass if (ref & mask) >= (stencil & mask). ```ts const FUNC_GREATEREQUAL: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_LESS.md # FUNC_LESS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L516 Pass if (ref & mask) < (stencil & mask). ```ts const FUNC_LESS: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_LESSEQUAL.md # FUNC_LESSEQUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L530 Pass if (ref & mask) <= (stencil & mask). ```ts const FUNC_LESSEQUAL: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_NEVER.md # FUNC_NEVER Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L509 Never pass. ```ts const FUNC_NEVER: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/FUNC_NOTEQUAL.md # FUNC_NOTEQUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L544 Pass if (ref & mask) != (stencil & mask). ```ts const FUNC_NOTEQUAL: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GAMMA_NONE.md # GAMMA_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L629 No gamma correction. ```ts const GAMMA_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GAMMA_SRGB.md # GAMMA_SRGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L636 Apply sRGB gamma correction. ```ts const GAMMA_SRGB: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_BUDGET_LIMIT.md # GSPLAT_BUDGET_LIMIT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1337 The splat budget is a limit: the LOD distances of each GSplat decide the detail, and [GSplatParams#splatBudget](https://api.playcanvas.com/engine/classes/GSplatParams.md#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. ```ts const GSPLAT_BUDGET_LIMIT: "limit" = 'limit' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_BUDGET_TARGET.md # GSPLAT_BUDGET_TARGET Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1327 The splat budget is a target: LOD detail is raised until [GSplatParams#splatBudget](https://api.playcanvas.com/engine/classes/GSplatParams.md#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. ```ts const GSPLAT_BUDGET_TARGET: "target" = 'target' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_AABBS.md # GSPLAT_DEBUG_AABBS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1377 Debug rendering that draws world-space AABBs for each GSplat, colorized by LOD. ```ts const GSPLAT_DEBUG_AABBS: number = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_LOD.md # GSPLAT_DEBUG_LOD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1357 Debug rendering that colorizes Gaussian splats by their selected LOD level. ```ts const GSPLAT_DEBUG_LOD: number = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_NODE_AABBS.md # GSPLAT_DEBUG_NODE_AABBS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1386 Debug rendering that draws world-space AABBs for each octree node of streamed GSplats, colorized by the currently selected LOD. ```ts const GSPLAT_DEBUG_NODE_AABBS: number = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_NONE.md # GSPLAT_DEBUG_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1349 No debug rendering for Gaussian splats. Normal rendering mode. ```ts const GSPLAT_DEBUG_NONE: number = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_DEBUG_SH_UPDATE.md # GSPLAT_DEBUG_SH_UPDATE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1366 Debug rendering that assigns a random color per spherical harmonics update pass, visualizing when SH color updates occur. ```ts const GSPLAT_DEBUG_SH_UPDATE: number = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_RENDERER_AUTO.md # GSPLAT_RENDERER_AUTO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1298 Automatically selects the best rendering pipeline for the current platform. ```ts const GSPLAT_RENDERER_AUTO: number = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_RENDERER_RASTER_CPU_SORT.md # GSPLAT_RENDERER_RASTER_CPU_SORT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1306 Rasterization-based rendering with CPU-side sorting. ```ts const GSPLAT_RENDERER_RASTER_CPU_SORT: number = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_RENDERER_RASTER_GPU_SORT.md # GSPLAT_RENDERER_RASTER_GPU_SORT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1314 Rasterization-based rendering with GPU-side culling and sorting. WebGPU only. ```ts const GSPLAT_RENDERER_RASTER_GPU_SORT: number = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_STREAM_INSTANCE.md # GSPLAT_STREAM_INSTANCE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1272 Stream texture is stored per gsplat component instance. ```ts const GSPLAT_STREAM_INSTANCE: number = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLAT_STREAM_RESOURCE.md # GSPLAT_STREAM_RESOURCE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1264 Stream texture is stored at resource level, shared across all component instances. ```ts const GSPLAT_STREAM_RESOURCE: number = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLATDATA_COMPACT.md # GSPLATDATA_COMPACT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1290 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. ```ts const GSPLATDATA_COMPACT: string = 'compact' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/GSPLATDATA_LARGE.md # GSPLATDATA_LARGE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1281 Large work buffer data format with full precision. Uses RGBA16F color, float16 rotation and float16 scale. 32 bytes per splat. ```ts const GSPLATDATA_LARGE: string = 'large' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT16.md # INDEXFORMAT_UINT16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L572 16-bit unsigned vertex indices (0 to 65,535). ```ts const INDEXFORMAT_UINT16: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT32.md # INDEXFORMAT_UINT32 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L579 32-bit unsigned vertex indices (0 to 4,294,967,295). ```ts const INDEXFORMAT_UINT32: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INDEXFORMAT_UINT8.md # INDEXFORMAT_UINT8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L565 8-bit unsigned vertex indices (0 to 255). ```ts const INDEXFORMAT_UINT8: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INTERPOLATION_CUBIC.md # INTERPOLATION_CUBIC Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L20 A cubic spline interpolation scheme. ```ts const INTERPOLATION_CUBIC: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INTERPOLATION_LINEAR.md # INTERPOLATION_LINEAR Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L13 A linear interpolation scheme. ```ts const INTERPOLATION_LINEAR: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/INTERPOLATION_STEP.md # INTERPOLATION_STEP Variable · category: Animation Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L6 A stepped interpolation scheme. ```ts const INTERPOLATION_STEP: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/JOINTTYPE_6DOF.md # JOINTTYPE_6DOF Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L43 Generic 6 degrees of freedom joint. Each linear and angular axis can be independently locked, limited or free, with optional springs. ```ts const JOINTTYPE_6DOF: "6dof" = '6dof' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/JOINTTYPE_BALL.md # JOINTTYPE_BALL Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L16 Ball and socket joint. The bodies can rotate freely about the joint's anchor point. Optional limits constrain the swing (cone) and twist angles. ```ts const JOINTTYPE_BALL: "ball" = 'ball' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/JOINTTYPE_FIXED.md # JOINTTYPE_FIXED Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L7 Joint rigidly locks all degrees of freedom, welding the two bodies together. ```ts const JOINTTYPE_FIXED: "fixed" = 'fixed' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/JOINTTYPE_HINGE.md # JOINTTYPE_HINGE Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L25 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. ```ts const JOINTTYPE_HINGE: "hinge" = 'hinge' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/JOINTTYPE_SLIDER.md # JOINTTYPE_SLIDER Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L34 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. ```ts const JOINTTYPE_SLIDER: "slider" = 'slider' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_0.md # KEY_0 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L149 ```ts const KEY_0: number = 48 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_1.md # KEY_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L155 ```ts const KEY_1: number = 49 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_2.md # KEY_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L161 ```ts const KEY_2: number = 50 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_3.md # KEY_3 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L167 ```ts const KEY_3: number = 51 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_4.md # KEY_4 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L173 ```ts const KEY_4: number = 52 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_5.md # KEY_5 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L179 ```ts const KEY_5: number = 53 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_6.md # KEY_6 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L185 ```ts const KEY_6: number = 54 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_7.md # KEY_7 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L191 ```ts const KEY_7: number = 55 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_8.md # KEY_8 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L197 ```ts const KEY_8: number = 56 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_9.md # KEY_9 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L203 ```ts const KEY_9: number = 57 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_A.md # KEY_A Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L221 ```ts const KEY_A: number = 65 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_ADD.md # KEY_ADD Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L455 ```ts const KEY_ADD: number = 107 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_ALT.md # KEY_ALT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L53 ```ts const KEY_ALT: number = 18 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_B.md # KEY_B Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L227 ```ts const KEY_B: number = 66 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_BACK_SLASH.md # KEY_BACK_SLASH Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L581 ```ts const KEY_BACK_SLASH: number = 220 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_BACKSPACE.md # KEY_BACKSPACE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L17 ```ts const KEY_BACKSPACE: number = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_C.md # KEY_C Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L233 ```ts const KEY_C: number = 67 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_CAPS_LOCK.md # KEY_CAPS_LOCK Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L65 ```ts const KEY_CAPS_LOCK: number = 20 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_CLOSE_BRACKET.md # KEY_CLOSE_BRACKET Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L587 ```ts const KEY_CLOSE_BRACKET: number = 221 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_COMMA.md # KEY_COMMA Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L557 ```ts const KEY_COMMA: number = 188 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_CONTEXT_MENU.md # KEY_CONTEXT_MENU Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L383 ```ts const KEY_CONTEXT_MENU: number = 93 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_CONTROL.md # KEY_CONTROL Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L47 ```ts const KEY_CONTROL: number = 17 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_D.md # KEY_D Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L239 ```ts const KEY_D: number = 68 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_DECIMAL.md # KEY_DECIMAL Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L473 ```ts const KEY_DECIMAL: number = 110 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_DELETE.md # KEY_DELETE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L143 ```ts const KEY_DELETE: number = 46 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_DIVIDE.md # KEY_DIVIDE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L479 ```ts const KEY_DIVIDE: number = 111 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_DOWN.md # KEY_DOWN Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L125 ```ts const KEY_DOWN: number = 40 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_E.md # KEY_E Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L245 ```ts const KEY_E: number = 69 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_END.md # KEY_END Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L95 ```ts const KEY_END: number = 35 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_ENTER.md # KEY_ENTER Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L35 ```ts const KEY_ENTER: number = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_EQUAL.md # KEY_EQUAL Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L215 ```ts const KEY_EQUAL: number = 61 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_ESCAPE.md # KEY_ESCAPE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L71 ```ts const KEY_ESCAPE: number = 27 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F.md # KEY_F Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L251 ```ts const KEY_F: number = 70 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F1.md # KEY_F1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L485 ```ts const KEY_F1: number = 112 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F10.md # KEY_F10 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L539 ```ts const KEY_F10: number = 121 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F11.md # KEY_F11 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L545 ```ts const KEY_F11: number = 122 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F12.md # KEY_F12 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L551 ```ts const KEY_F12: number = 123 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F2.md # KEY_F2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L491 ```ts const KEY_F2: number = 113 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F3.md # KEY_F3 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L497 ```ts const KEY_F3: number = 114 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F4.md # KEY_F4 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L503 ```ts const KEY_F4: number = 115 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F5.md # KEY_F5 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L509 ```ts const KEY_F5: number = 116 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F6.md # KEY_F6 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L515 ```ts const KEY_F6: number = 117 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F7.md # KEY_F7 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L521 ```ts const KEY_F7: number = 118 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F8.md # KEY_F8 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L527 ```ts const KEY_F8: number = 119 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_F9.md # KEY_F9 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L533 ```ts const KEY_F9: number = 120 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_G.md # KEY_G Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L257 ```ts const KEY_G: number = 71 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_H.md # KEY_H Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L263 ```ts const KEY_H: number = 72 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_HOME.md # KEY_HOME Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L101 ```ts const KEY_HOME: number = 36 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_I.md # KEY_I Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L269 ```ts const KEY_I: number = 73 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_INSERT.md # KEY_INSERT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L137 ```ts const KEY_INSERT: number = 45 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_J.md # KEY_J Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L275 ```ts const KEY_J: number = 74 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_K.md # KEY_K Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L281 ```ts const KEY_K: number = 75 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_L.md # KEY_L Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L287 ```ts const KEY_L: number = 76 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_LEFT.md # KEY_LEFT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L107 ```ts const KEY_LEFT: number = 37 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_M.md # KEY_M Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L293 ```ts const KEY_M: number = 77 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_META.md # KEY_META Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L593 ```ts const KEY_META: number = 224 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_MULTIPLY.md # KEY_MULTIPLY Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L449 ```ts const KEY_MULTIPLY: number = 106 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_N.md # KEY_N Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L299 ```ts const KEY_N: number = 78 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_0.md # KEY_NUMPAD_0 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L389 ```ts const KEY_NUMPAD_0: number = 96 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_1.md # KEY_NUMPAD_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L395 ```ts const KEY_NUMPAD_1: number = 97 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_2.md # KEY_NUMPAD_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L401 ```ts const KEY_NUMPAD_2: number = 98 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_3.md # KEY_NUMPAD_3 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L407 ```ts const KEY_NUMPAD_3: number = 99 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_4.md # KEY_NUMPAD_4 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L413 ```ts const KEY_NUMPAD_4: number = 100 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_5.md # KEY_NUMPAD_5 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L419 ```ts const KEY_NUMPAD_5: number = 101 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_6.md # KEY_NUMPAD_6 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L425 ```ts const KEY_NUMPAD_6: number = 102 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_7.md # KEY_NUMPAD_7 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L431 ```ts const KEY_NUMPAD_7: number = 103 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_8.md # KEY_NUMPAD_8 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L437 ```ts const KEY_NUMPAD_8: number = 104 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_NUMPAD_9.md # KEY_NUMPAD_9 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L443 ```ts const KEY_NUMPAD_9: number = 105 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_O.md # KEY_O Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L305 ```ts const KEY_O: number = 79 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_OPEN_BRACKET.md # KEY_OPEN_BRACKET Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L575 ```ts const KEY_OPEN_BRACKET: number = 219 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_P.md # KEY_P Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L311 ```ts const KEY_P: number = 80 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_PAGE_DOWN.md # KEY_PAGE_DOWN Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L89 ```ts const KEY_PAGE_DOWN: number = 34 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_PAGE_UP.md # KEY_PAGE_UP Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L83 ```ts const KEY_PAGE_UP: number = 33 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_PAUSE.md # KEY_PAUSE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L59 ```ts const KEY_PAUSE: number = 19 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_PERIOD.md # KEY_PERIOD Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L563 ```ts const KEY_PERIOD: number = 190 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_PRINT_SCREEN.md # KEY_PRINT_SCREEN Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L131 ```ts const KEY_PRINT_SCREEN: number = 44 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_Q.md # KEY_Q Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L317 ```ts const KEY_Q: number = 81 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_R.md # KEY_R Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L323 ```ts const KEY_R: number = 82 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_RETURN.md # KEY_RETURN Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L29 ```ts const KEY_RETURN: number = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_RIGHT.md # KEY_RIGHT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L119 ```ts const KEY_RIGHT: number = 39 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_S.md # KEY_S Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L329 ```ts const KEY_S: number = 83 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SEMICOLON.md # KEY_SEMICOLON Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L209 ```ts const KEY_SEMICOLON: number = 59 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SEPARATOR.md # KEY_SEPARATOR Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L461 ```ts const KEY_SEPARATOR: number = 108 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SHIFT.md # KEY_SHIFT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L41 ```ts const KEY_SHIFT: number = 16 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SLASH.md # KEY_SLASH Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L569 ```ts const KEY_SLASH: number = 191 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SPACE.md # KEY_SPACE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L77 ```ts const KEY_SPACE: number = 32 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_SUBTRACT.md # KEY_SUBTRACT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L467 ```ts const KEY_SUBTRACT: number = 109 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_T.md # KEY_T Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L335 ```ts const KEY_T: number = 84 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_TAB.md # KEY_TAB Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L23 ```ts const KEY_TAB: number = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_U.md # KEY_U Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L341 ```ts const KEY_U: number = 85 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_UP.md # KEY_UP Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L113 ```ts const KEY_UP: number = 38 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_V.md # KEY_V Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L347 ```ts const KEY_V: number = 86 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_W.md # KEY_W Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L353 ```ts const KEY_W: number = 87 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_WINDOWS.md # KEY_WINDOWS Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L377 ```ts const KEY_WINDOWS: number = 91 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_X.md # KEY_X Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L359 ```ts const KEY_X: number = 88 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_Y.md # KEY_Y Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L365 ```ts const KEY_Y: number = 89 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/KEY_Z.md # KEY_Z Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L371 ```ts const KEY_Z: number = 90 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LAYERID_DEPTH.md # LAYERID_DEPTH Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L166 The depth layer. ```ts const LAYERID_DEPTH: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LAYERID_IMMEDIATE.md # LAYERID_IMMEDIATE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L180 The immediate layer. ```ts const LAYERID_IMMEDIATE: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LAYERID_SKYBOX.md # LAYERID_SKYBOX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L173 The skybox layer. ```ts const LAYERID_SKYBOX: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LAYERID_UI.md # LAYERID_UI Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L187 The UI layer. ```ts const LAYERID_UI: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LAYERID_WORLD.md # LAYERID_WORLD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L159 The world layer. ```ts const LAYERID_WORLD: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTFALLOFF_INVERSESQUARED.md # LIGHTFALLOFF_INVERSESQUARED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L277 Inverse squared distance falloff model for light attenuation. ```ts const LIGHTFALLOFF_INVERSESQUARED: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTFALLOFF_LINEAR.md # LIGHTFALLOFF_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L270 Linear distance falloff model for light attenuation. ```ts const LIGHTFALLOFF_LINEAR: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTSHAPE_DISK.md # LIGHTSHAPE_DISK Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L249 Disk shape of light source. ```ts const LIGHTSHAPE_DISK: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTSHAPE_PUNCTUAL.md # LIGHTSHAPE_PUNCTUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L235 Infinitesimally small point light source shape. ```ts const LIGHTSHAPE_PUNCTUAL: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTSHAPE_RECT.md # LIGHTSHAPE_RECT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L242 Rectangle shape of light source. ```ts const LIGHTSHAPE_RECT: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTSHAPE_SPHERE.md # LIGHTSHAPE_SPHERE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L256 Sphere shape of light source. ```ts const LIGHTSHAPE_SPHERE: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTTYPE_DIRECTIONAL.md # LIGHTTYPE_DIRECTIONAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L194 Directional (global) light source. ```ts const LIGHTTYPE_DIRECTIONAL: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTTYPE_OMNI.md # LIGHTTYPE_OMNI Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L201 Omni-directional (local) light source. ```ts const LIGHTTYPE_OMNI: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LIGHTTYPE_SPOT.md # LIGHTTYPE_SPOT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L216 Spot (local) light source. ```ts const LIGHTTYPE_SPOT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINECAP_BUTT.md # LINECAP_BUTT Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L8 Butt line caps stop exactly at the first and last points. ```ts const LINECAP_BUTT: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINECAP_ROUND.md # LINECAP_ROUND Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L14 Round line caps extend past line and dash ends by half the line width. ```ts const LINECAP_ROUND: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINECAP_SQUARE.md # LINECAP_SQUARE Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L11 Square line caps extend past the first and last points by half the line width. ```ts const LINECAP_SQUARE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINEJOIN_BEVEL.md # LINEJOIN_BEVEL Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L20 Bevel joins connect segment edges directly. ```ts const LINEJOIN_BEVEL: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINEJOIN_MITER.md # LINEJOIN_MITER Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L17 Miter joins extend edges until they intersect. ```ts const LINEJOIN_MITER: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINEJOIN_ROUND.md # LINEJOIN_ROUND Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L23 Round joins connect segments using a circular edge. ```ts const LINEJOIN_ROUND: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINEWIDTH_SCREEN.md # LINEWIDTH_SCREEN Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L17 Line widths are measured in screen pixels. ```ts const LINEWIDTH_SCREEN: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/LINEWIDTH_WORLD.md # LINEWIDTH_WORLD Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L20 Line widths are measured in world units. ```ts const LINEWIDTH_WORLD: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOTION_FREE.md # MOTION_FREE Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L51 Specified degree of freedom has free movement. ```ts const MOTION_FREE: "free" = 'free' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOTION_LIMITED.md # MOTION_LIMITED Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L59 Specified degree of freedom has limited movement. ```ts const MOTION_LIMITED: "limited" = 'limited' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOTION_LOCKED.md # MOTION_LOCKED Variable · category: Physics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L67 Specified degree of freedom is locked and allows no movement. ```ts const MOTION_LOCKED: "locked" = 'locked' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOUSEBUTTON_LEFT.md # MOUSEBUTTON_LEFT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L607 The left mouse button. ```ts const MOUSEBUTTON_LEFT: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOUSEBUTTON_MIDDLE.md # MOUSEBUTTON_MIDDLE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L614 The middle mouse button. ```ts const MOUSEBUTTON_MIDDLE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOUSEBUTTON_NONE.md # MOUSEBUTTON_NONE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L600 No mouse buttons pressed. ```ts const MOUSEBUTTON_NONE: -1 = -1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/MOUSEBUTTON_RIGHT.md # MOUSEBUTTON_RIGHT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L621 The right mouse button. ```ts const MOUSEBUTTON_RIGHT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ORIENTATION_HORIZONTAL.md # ORIENTATION_HORIZONTAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1061 Horizontal orientation. ```ts const ORIENTATION_HORIZONTAL: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/ORIENTATION_VERTICAL.md # ORIENTATION_VERTICAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1068 Vertical orientation. ```ts const ORIENTATION_VERTICAL: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_1.md # PAD_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L628 Index for pad 1. ```ts const PAD_1: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_2.md # PAD_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L635 Index for pad 2. ```ts const PAD_2: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_3.md # PAD_3 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L642 Index for pad 3. ```ts const PAD_3: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_4.md # PAD_4 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L649 Index for pad 4. ```ts const PAD_4: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_DOWN.md # PAD_DOWN Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L747 Direction pad down. ```ts const PAD_DOWN: 13 = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_FACE_1.md # PAD_FACE_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L656 The first face button, from bottom going clockwise. ```ts const PAD_FACE_1: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_FACE_2.md # PAD_FACE_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L663 The second face button, from bottom going clockwise. ```ts const PAD_FACE_2: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_FACE_3.md # PAD_FACE_3 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L670 The third face button, from bottom going clockwise. ```ts const PAD_FACE_3: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_FACE_4.md # PAD_FACE_4 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L677 The fourth face button, from bottom going clockwise. ```ts const PAD_FACE_4: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_L_SHOULDER_1.md # PAD_L_SHOULDER_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L684 The first shoulder button on the left. ```ts const PAD_L_SHOULDER_1: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_L_SHOULDER_2.md # PAD_L_SHOULDER_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L698 The second shoulder button on the left. ```ts const PAD_L_SHOULDER_2: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_L_STICK_BUTTON.md # PAD_L_STICK_BUTTON Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L726 The button when depressing the left analogue stick. ```ts const PAD_L_STICK_BUTTON: 10 = 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_L_STICK_X.md # PAD_L_STICK_X Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L775 Horizontal axis on the left analogue stick. ```ts const PAD_L_STICK_X: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_L_STICK_Y.md # PAD_L_STICK_Y Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L782 Vertical axis on the left analogue stick. ```ts const PAD_L_STICK_Y: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_LEFT.md # PAD_LEFT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L754 Direction pad left. ```ts const PAD_LEFT: 14 = 14 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_R_SHOULDER_1.md # PAD_R_SHOULDER_1 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L691 The first shoulder button on the right. ```ts const PAD_R_SHOULDER_1: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_R_SHOULDER_2.md # PAD_R_SHOULDER_2 Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L705 The second shoulder button on the right. ```ts const PAD_R_SHOULDER_2: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_R_STICK_BUTTON.md # PAD_R_STICK_BUTTON Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L733 The button when depressing the right analogue stick. ```ts const PAD_R_STICK_BUTTON: 11 = 11 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_R_STICK_X.md # PAD_R_STICK_X Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L789 Horizontal axis on the right analogue stick. ```ts const PAD_R_STICK_X: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_R_STICK_Y.md # PAD_R_STICK_Y Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L796 Vertical axis on the right analogue stick. ```ts const PAD_R_STICK_Y: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_RIGHT.md # PAD_RIGHT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L761 Direction pad right. ```ts const PAD_RIGHT: 15 = 15 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_SELECT.md # PAD_SELECT Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L712 The select button. ```ts const PAD_SELECT: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_START.md # PAD_START Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L719 The start button. ```ts const PAD_START: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_UP.md # PAD_UP Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L740 Direction pad up. ```ts const PAD_UP: 12 = 12 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PAD_VENDOR.md # PAD_VENDOR Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L768 Vendor specific button. ```ts const PAD_VENDOR: 16 = 16 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARALLAX_OCCLUSION.md # PARALLAX_OCCLUSION Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1157 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](https://api.playcanvas.com/engine/variables/PARALLAX_OFFSET.md), but represents deeper displacement without smearing the texture. ```ts const PARALLAX_OCCLUSION: "occlusion" = 'occlusion' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARALLAX_OFFSET.md # PARALLAX_OFFSET Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1148 Parallax mapping computes the uv offset from a single tap of the height map. This is the cheapest option, and suits shallow surface detail. ```ts const PARALLAX_OFFSET: "offset" = 'offset' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLEORIENTATION_EMITTER.md # PARTICLEORIENTATION_EMITTER Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L525 Similar to previous, but the normal is affected by emitter(entity) transformation. ```ts const PARTICLEORIENTATION_EMITTER: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLEORIENTATION_SCREEN.md # PARTICLEORIENTATION_SCREEN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L511 Particles are facing camera. ```ts const PARTICLEORIENTATION_SCREEN: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLEORIENTATION_WORLD.md # PARTICLEORIENTATION_WORLD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L518 User defines world space normal (particleNormal) to set planes orientation. ```ts const PARTICLEORIENTATION_WORLD: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLESORT_DISTANCE.md # PARTICLESORT_DISTANCE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L472 Sorting based on distance to the camera. CPU only. ```ts const PARTICLESORT_DISTANCE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLESORT_NEWER_FIRST.md # PARTICLESORT_NEWER_FIRST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L479 Newer particles are drawn first. CPU only. ```ts const PARTICLESORT_NEWER_FIRST: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLESORT_NONE.md # PARTICLESORT_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L465 No sorting, particles are drawn in arbitrary order. Can be simulated on GPU. ```ts const PARTICLESORT_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PARTICLESORT_OLDER_FIRST.md # PARTICLESORT_OLDER_FIRST Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L486 Older particles are drawn first. CPU only. ```ts const PARTICLESORT_OLDER_FIRST: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_111110F.md # PIXELFORMAT_111110F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L709 A floating-point color-only format with 11 bits for red and green channels and 10 bits for the blue channel. ```ts const PIXELFORMAT_111110F: 18 = 18 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGB.md # PIXELFORMAT_ATC_RGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L786 ATC compressed format with no alpha channel. ```ts const PIXELFORMAT_ATC_RGB: 29 = 29 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ATC_RGBA.md # PIXELFORMAT_ATC_RGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L793 ATC compressed format with alpha channel. ```ts const PIXELFORMAT_ATC_RGBA: 30 = 30 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_BC6F.md # PIXELFORMAT_BC6F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1013 Compressed high dynamic range signed floating point format storing RGB values. ```ts const PIXELFORMAT_BC6F: 65 = 65 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_BC6UF.md # PIXELFORMAT_BC6UF Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1020 Compressed high dynamic range unsigned floating point format storing RGB values. ```ts const PIXELFORMAT_BC6UF: 66 = 66 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_BC7.md # PIXELFORMAT_BC7 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1027 Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA data. ```ts const PIXELFORMAT_BC7: 67 = 67 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_BC7_SRGBA.md # PIXELFORMAT_BC7_SRGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1035 Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of SRGB_ALPHA data. ```ts const PIXELFORMAT_BC7_SRGBA: 68 = 68 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH.md # PIXELFORMAT_DEPTH Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L694 A readable depth buffer format. ```ts const PIXELFORMAT_DEPTH: 16 = 16 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTH16.md # PIXELFORMAT_DEPTH16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1042 A 16-bit depth buffer format. ```ts const PIXELFORMAT_DEPTH16: 69 = 69 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DEPTHSTENCIL.md # PIXELFORMAT_DEPTHSTENCIL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L701 A readable depth/stencil buffer format. ```ts const PIXELFORMAT_DEPTHSTENCIL: 17 = 17 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT1.md # PIXELFORMAT_DXT1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L634 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. ```ts const PIXELFORMAT_DXT1: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT1_SRGB.md # PIXELFORMAT_DXT1_SRGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L963 Format equivalent to [PIXELFORMAT_DXT1](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT1.md) but sampled in linear color space. ```ts const PIXELFORMAT_DXT1_SRGB: 54 = 54 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT3.md # PIXELFORMAT_DXT3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L643 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. ```ts const PIXELFORMAT_DXT3: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT3_SRGBA.md # PIXELFORMAT_DXT3_SRGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L970 Format equivalent to [PIXELFORMAT_DXT3](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT3.md) but sampled in linear color space. ```ts const PIXELFORMAT_DXT3_SRGBA: 55 = 55 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT5.md # PIXELFORMAT_DXT5 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L652 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). ```ts const PIXELFORMAT_DXT5: 10 = 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT5_SRGBA.md # PIXELFORMAT_DXT5_SRGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L977 Format equivalent to [PIXELFORMAT_DXT5](https://api.playcanvas.com/engine/variables/PIXELFORMAT_DXT5.md) but sampled in linear color space. ```ts const PIXELFORMAT_DXT5_SRGBA: 56 = 56 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC1.md # PIXELFORMAT_ETC1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L730 ETC1 compressed format. ```ts const PIXELFORMAT_ETC1: 21 = 21 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_RGB.md # PIXELFORMAT_ETC2_RGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L737 ETC2 (RGB) compressed format. ```ts const PIXELFORMAT_ETC2_RGB: 22 = 22 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_RGBA.md # PIXELFORMAT_ETC2_RGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L744 ETC2 (RGBA) compressed format. ```ts const PIXELFORMAT_ETC2_RGBA: 23 = 23 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_SRGB.md # PIXELFORMAT_ETC2_SRGB Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L984 Format equivalent to [PIXELFORMAT_ETC2_RGB](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_RGB.md) but sampled in linear color space. ```ts const PIXELFORMAT_ETC2_SRGB: 61 = 61 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_SRGBA.md # PIXELFORMAT_ETC2_SRGBA Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L991 Format equivalent to [PIXELFORMAT_ETC2_RGBA](https://api.playcanvas.com/engine/variables/PIXELFORMAT_ETC2_RGBA.md) but sampled in linear color space. ```ts const PIXELFORMAT_ETC2_SRGBA: 62 = 62 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGB_1.md # PIXELFORMAT_PVRTC_2BPP_RGB_1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L751 PVRTC (2BPP RGB) compressed format. ```ts const PIXELFORMAT_PVRTC_2BPP_RGB_1: 24 = 24 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_2BPP_RGBA_1.md # PIXELFORMAT_PVRTC_2BPP_RGBA_1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L758 PVRTC (2BPP RGBA) compressed format. ```ts const PIXELFORMAT_PVRTC_2BPP_RGBA_1: 25 = 25 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGB_1.md # PIXELFORMAT_PVRTC_4BPP_RGB_1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L765 PVRTC (4BPP RGB) compressed format. ```ts const PIXELFORMAT_PVRTC_4BPP_RGB_1: 26 = 26 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_PVRTC_4BPP_RGBA_1.md # PIXELFORMAT_PVRTC_4BPP_RGBA_1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L772 PVRTC (4BPP RGBA) compressed format. ```ts const PIXELFORMAT_PVRTC_4BPP_RGBA_1: 27 = 27 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R16F.md # PIXELFORMAT_R16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L935 16-bit floating point R (16-bit float for red channel). ```ts const PIXELFORMAT_R16F: 50 = 50 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R16I.md # PIXELFORMAT_R16I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L823 16-bit signed integer single-channel (R) format. ```ts const PIXELFORMAT_R16I: 34 = 34 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R16U.md # PIXELFORMAT_R16U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L830 16-bit unsigned integer single-channel (R) format. ```ts const PIXELFORMAT_R16U: 35 = 35 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32F.md # PIXELFORMAT_R32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L687 32-bit floating point single channel format. ```ts const PIXELFORMAT_R32F: 15 = 15 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32I.md # PIXELFORMAT_R32I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L837 32-bit signed integer single-channel (R) format. ```ts const PIXELFORMAT_R32I: 36 = 36 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R32U.md # PIXELFORMAT_R32U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L844 32-bit unsigned integer single-channel (R) format. ```ts const PIXELFORMAT_R32U: 37 = 37 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8.md # PIXELFORMAT_R8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L949 8-bit per-channel (R) format. ```ts const PIXELFORMAT_R8: 52 = 52 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8I.md # PIXELFORMAT_R8I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L809 8-bit signed integer single-channel (R) format. ```ts const PIXELFORMAT_R8I: 32 = 32 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_R8U.md # PIXELFORMAT_R8U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L816 8-bit unsigned integer single-channel (R) format. ```ts const PIXELFORMAT_R8U: 33 = 33 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG16F.md # PIXELFORMAT_RG16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L942 16-bit floating point RG (16-bit float for each red and green channels). ```ts const PIXELFORMAT_RG16F: 51 = 51 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG16I.md # PIXELFORMAT_RG16I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L865 16-bit per-channel signed integer (RG) format. ```ts const PIXELFORMAT_RG16I: 40 = 40 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG16U.md # PIXELFORMAT_RG16U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L872 16-bit per-channel unsigned integer (RG) format. ```ts const PIXELFORMAT_RG16U: 41 = 41 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG32F.md # PIXELFORMAT_RG32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1049 32-bit floating point RG (32-bit float for each red and green channels). WebGPU only. ```ts const PIXELFORMAT_RG32F: 70 = 70 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG32I.md # PIXELFORMAT_RG32I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L879 32-bit per-channel signed integer (RG) format. ```ts const PIXELFORMAT_RG32I: 42 = 42 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG32U.md # PIXELFORMAT_RG32U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L886 32-bit per-channel unsigned integer (RG) format. ```ts const PIXELFORMAT_RG32U: 43 = 43 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8.md # PIXELFORMAT_RG8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L956 8-bit per-channel (RG) format. ```ts const PIXELFORMAT_RG8: 53 = 53 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8I.md # PIXELFORMAT_RG8I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L851 8-bit per-channel signed integer (RG) format. ```ts const PIXELFORMAT_RG8I: 38 = 38 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8S.md # PIXELFORMAT_RG8S Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1063 8-bit per-channel signed normalized (RG) format. ```ts const PIXELFORMAT_RG8S: 72 = 72 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RG8U.md # PIXELFORMAT_RG8U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L858 8-bit per-channel unsigned integer (RG) format. ```ts const PIXELFORMAT_RG8U: 39 = 39 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB10A2.md # PIXELFORMAT_RGB10A2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1077 10-bit RGB with 2-bit alpha unsigned normalized format. ```ts const PIXELFORMAT_RGB10A2: 74 = 74 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB10A2U.md # PIXELFORMAT_RGB10A2U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1084 10-bit RGB with 2-bit alpha unsigned integer format. ```ts const PIXELFORMAT_RGB10A2U: 75 = 75 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB16F.md # PIXELFORMAT_RGB16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L659 16-bit floating point RGB (16-bit float for each red, green and blue channels). ```ts const PIXELFORMAT_RGB16F: 11 = 11 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB32F.md # PIXELFORMAT_RGB32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L673 32-bit floating point RGB (32-bit float for each red, green and blue channels). ```ts const PIXELFORMAT_RGB32F: 13 = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB565.md # PIXELFORMAT_RGB565 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L598 16-bit RGB (5-bits for red channel, 6 for green and 5 for blue). ```ts const PIXELFORMAT_RGB565: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB8.md # PIXELFORMAT_RGB8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L619 24-bit RGB (8-bits for red channel, 8 for green and 8 for blue). ```ts const PIXELFORMAT_RGB8: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGB9E5.md # PIXELFORMAT_RGB9E5 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1056 32-bit RGB format with shared 5-bit exponent (9 bits each for RGB mantissa). HDR format. ```ts const PIXELFORMAT_RGB9E5: 71 = 71 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16F.md # PIXELFORMAT_RGBA16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L666 16-bit floating point RGBA (16-bit float for each red, green, blue and alpha channels). ```ts const PIXELFORMAT_RGBA16F: 12 = 12 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16I.md # PIXELFORMAT_RGBA16I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L907 16-bit per-channel signed integer (RGBA) format. ```ts const PIXELFORMAT_RGBA16I: 46 = 46 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA16U.md # PIXELFORMAT_RGBA16U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L914 16-bit per-channel unsigned integer (RGBA) format. ```ts const PIXELFORMAT_RGBA16U: 47 = 47 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32F.md # PIXELFORMAT_RGBA32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L680 32-bit floating point RGBA (32-bit float for each red, green, blue and alpha channels). ```ts const PIXELFORMAT_RGBA32F: 14 = 14 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32I.md # PIXELFORMAT_RGBA32I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L921 32-bit per-channel signed integer (RGBA) format. ```ts const PIXELFORMAT_RGBA32I: 48 = 48 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA32U.md # PIXELFORMAT_RGBA32U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L928 32-bit per-channel unsigned integer (RGBA) format. ```ts const PIXELFORMAT_RGBA32U: 49 = 49 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA4.md # PIXELFORMAT_RGBA4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L612 16-bit RGBA (4-bits for red channel, 4 for green, 4 for blue with 4-bit alpha). ```ts const PIXELFORMAT_RGBA4: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA5551.md # PIXELFORMAT_RGBA5551 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L605 16-bit RGBA (5-bits for red channel, 5 for green, 5 for blue with 1-bit alpha). ```ts const PIXELFORMAT_RGBA5551: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8.md # PIXELFORMAT_RGBA8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L626 32-bit RGBA (8-bits for red channel, 8 for green, 8 for blue with 8-bit alpha). ```ts const PIXELFORMAT_RGBA8: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8I.md # PIXELFORMAT_RGBA8I Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L893 8-bit per-channel signed integer (RGBA) format. ```ts const PIXELFORMAT_RGBA8I: 44 = 44 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8S.md # PIXELFORMAT_RGBA8S Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1070 8-bit per-channel signed normalized (RGBA) format. ```ts const PIXELFORMAT_RGBA8S: 73 = 73 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_RGBA8U.md # PIXELFORMAT_RGBA8U Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L900 8-bit per-channel unsigned integer (RGBA) format. ```ts const PIXELFORMAT_RGBA8U: 45 = 45 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_SRGB8.md # PIXELFORMAT_SRGB8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L716 Color-only sRGB format. ```ts const PIXELFORMAT_SRGB8: 19 = 19 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PIXELFORMAT_SRGBA8.md # PIXELFORMAT_SRGBA8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L723 Color sRGB format with additional alpha channel. ```ts const PIXELFORMAT_SRGBA8: 20 = 20 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_LINELOOP.md # PRIMITIVE_LINELOOP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1376 List of points that are linked sequentially by line segments, with a closing line segment between the last and first points. ```ts const PRIMITIVE_LINELOOP: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_LINES.md # PRIMITIVE_LINES Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1368 Discrete list of line segments. ```ts const PRIMITIVE_LINES: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_LINESTRIP.md # PRIMITIVE_LINESTRIP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1383 List of points that are linked sequentially by line segments. ```ts const PRIMITIVE_LINESTRIP: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_POINTS.md # PRIMITIVE_POINTS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1361 List of distinct points. ```ts const PRIMITIVE_POINTS: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIANGLES.md # PRIMITIVE_TRIANGLES Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1390 Discrete list of triangles. ```ts const PRIMITIVE_TRIANGLES: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_TRIFAN.md # PRIMITIVE_TRIFAN Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1404 Connected fan of triangles where the first vertex forms triangles with the following pairs of vertices. ```ts const PRIMITIVE_TRIFAN: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PRIMITIVE_TRISTRIP.md # PRIMITIVE_TRISTRIP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1397 Connected strip of triangles where a specified vertex forms a triangle using the previous two. ```ts const PRIMITIVE_TRISTRIP: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PROJECTION_ORTHOGRAPHIC.md # PROJECTION_ORTHOGRAPHIC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L539 An orthographic camera projection where the frustum shape is essentially a cuboid. ```ts const PROJECTION_ORTHOGRAPHIC: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/PROJECTION_PERSPECTIVE.md # PROJECTION_PERSPECTIVE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L532 A perspective camera projection where the frustum shape is essentially pyramidal. ```ts const PROJECTION_PERSPECTIVE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERSTYLE_POINTS.md # RENDERSTYLE_POINTS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L560 Render mesh instance as points. ```ts const RENDERSTYLE_POINTS: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERSTYLE_SOLID.md # RENDERSTYLE_SOLID Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L546 Render mesh instance as solid geometry. ```ts const RENDERSTYLE_SOLID: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERSTYLE_WIREFRAME.md # RENDERSTYLE_WIREFRAME Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L553 Render mesh instance as wireframe. ```ts const RENDERSTYLE_WIREFRAME: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_BOTTOM.md # RENDERTARGET_ORIGIN_BOTTOM Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L379 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](https://api.playcanvas.com/engine/classes/RenderTarget.md) constructor for guidance on which origin to use. ```ts const RENDERTARGET_ORIGIN_BOTTOM: "bottom" = 'bottom' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_NATIVE.md # RENDERTARGET_ORIGIN_NATIVE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L389 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](https://api.playcanvas.com/engine/classes/RenderTarget.md) constructor for guidance on which origin to use. ```ts const RENDERTARGET_ORIGIN_NATIVE: "native" = 'native' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RENDERTARGET_ORIGIN_TOP.md # RENDERTARGET_ORIGIN_TOP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L370 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](https://api.playcanvas.com/engine/classes/RenderTarget.md) constructor for guidance on which origin to use. ```ts const RENDERTARGET_ORIGIN_TOP: "top" = 'top' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RESOLUTION_AUTO.md # RESOLUTION_AUTO Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L21 When the canvas is resized the resolution of the canvas will change to match the size of the canvas. ```ts const RESOLUTION_AUTO: "AUTO" = 'AUTO' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/RESOLUTION_FIXED.md # RESOLUTION_FIXED Variable · category: Other Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L27 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. ```ts const RESOLUTION_FIXED: "FIXED" = 'FIXED' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SAMPLETYPE_DEPTH.md # SAMPLETYPE_DEPTH Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1803 A sampler type of a texture that contains depth data. Typically used for depth textures. ```ts const SAMPLETYPE_DEPTH: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SAMPLETYPE_FLOAT.md # SAMPLETYPE_FLOAT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1788 A sampler type of a texture that contains floating-point data. Typically stored for color textures, where data can be filtered. ```ts const SAMPLETYPE_FLOAT: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SAMPLETYPE_INT.md # SAMPLETYPE_INT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1810 A sampler type of a texture that contains signed integer data. ```ts const SAMPLETYPE_INT: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SAMPLETYPE_UINT.md # SAMPLETYPE_UINT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1817 A sampler type of a texture that contains unsigned integer data. ```ts const SAMPLETYPE_UINT: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SAMPLETYPE_UNFILTERABLE_FLOAT.md # SAMPLETYPE_UNFILTERABLE_FLOAT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1796 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. ```ts const SAMPLETYPE_UNFILTERABLE_FLOAT: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCALEMODE_BLEND.md # SCALEMODE_BLEND Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/constants.js#L14 Scale the [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md) when the application's resolution is different than the ScreenComponent's referenceResolution. ```ts const SCALEMODE_BLEND: "blend" = 'blend' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCALEMODE_NONE.md # SCALEMODE_NONE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/constants.js#L6 Always use the application's resolution as the resolution for the [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.md). ```ts const SCALEMODE_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCROLL_MODE_BOUNCE.md # SCROLL_MODE_BOUNCE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L13 Content scrolls past its bounds and then gently bounces back. ```ts const SCROLL_MODE_BOUNCE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCROLL_MODE_CLAMP.md # SCROLL_MODE_CLAMP Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L6 Content does not scroll any further than its bounds. ```ts const SCROLL_MODE_CLAMP: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCROLL_MODE_INFINITE.md # SCROLL_MODE_INFINITE Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L20 Content can scroll forever. ```ts const SCROLL_MODE_INFINITE: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCROLLBAR_VISIBILITY_SHOW_ALWAYS.md # SCROLLBAR_VISIBILITY_SHOW_ALWAYS Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L27 The scrollbar will be visible all the time. ```ts const SCROLLBAR_VISIBILITY_SHOW_ALWAYS: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED.md # SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED Variable · category: User Interface Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L34 The scrollbar will be visible only when content exceeds the size of the viewport. ```ts const SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR0.md # SEMANTIC_ATTR0 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1512 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR0: "ATTR0" = 'ATTR0' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR1.md # SEMANTIC_ATTR1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1519 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR1: "ATTR1" = 'ATTR1' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR10.md # SEMANTIC_ATTR10 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1582 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR10: "ATTR10" = 'ATTR10' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR11.md # SEMANTIC_ATTR11 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1589 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR11: "ATTR11" = 'ATTR11' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR12.md # SEMANTIC_ATTR12 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1596 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR12: "ATTR12" = 'ATTR12' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR13.md # SEMANTIC_ATTR13 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1603 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR13: "ATTR13" = 'ATTR13' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR14.md # SEMANTIC_ATTR14 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1610 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR14: "ATTR14" = 'ATTR14' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR15.md # SEMANTIC_ATTR15 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1617 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR15: "ATTR15" = 'ATTR15' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR2.md # SEMANTIC_ATTR2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1526 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR2: "ATTR2" = 'ATTR2' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR3.md # SEMANTIC_ATTR3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1533 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR3: "ATTR3" = 'ATTR3' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR4.md # SEMANTIC_ATTR4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1540 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR4: "ATTR4" = 'ATTR4' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR5.md # SEMANTIC_ATTR5 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1547 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR5: "ATTR5" = 'ATTR5' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR6.md # SEMANTIC_ATTR6 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1554 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR6: "ATTR6" = 'ATTR6' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR7.md # SEMANTIC_ATTR7 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1561 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR7: "ATTR7" = 'ATTR7' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR8.md # SEMANTIC_ATTR8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1568 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR8: "ATTR8" = 'ATTR8' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_ATTR9.md # SEMANTIC_ATTR9 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1575 Vertex attribute with a user defined semantic. ```ts const SEMANTIC_ATTR9: "ATTR9" = 'ATTR9' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_BLENDINDICES.md # SEMANTIC_BLENDINDICES Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1439 Vertex attribute to be treated as skin blend indices. ```ts const SEMANTIC_BLENDINDICES: "BLENDINDICES" = 'BLENDINDICES' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_BLENDWEIGHT.md # SEMANTIC_BLENDWEIGHT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1432 Vertex attribute to be treated as skin blend weights. ```ts const SEMANTIC_BLENDWEIGHT: "BLENDWEIGHT" = 'BLENDWEIGHT' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_COLOR.md # SEMANTIC_COLOR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1446 Vertex attribute to be treated as a color. ```ts const SEMANTIC_COLOR: "COLOR" = 'COLOR' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_NORMAL.md # SEMANTIC_NORMAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1418 Vertex attribute to be treated as a normal. ```ts const SEMANTIC_NORMAL: "NORMAL" = 'NORMAL' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_POSITION.md # SEMANTIC_POSITION Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1411 Vertex attribute to be treated as a position. ```ts const SEMANTIC_POSITION: "POSITION" = 'POSITION' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TANGENT.md # SEMANTIC_TANGENT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1425 Vertex attribute to be treated as a tangent. ```ts const SEMANTIC_TANGENT: "TANGENT" = 'TANGENT' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD0.md # SEMANTIC_TEXCOORD0 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1456 Vertex attribute to be treated as a texture coordinate (set 0). ```ts const SEMANTIC_TEXCOORD0: "TEXCOORD0" = 'TEXCOORD0' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD1.md # SEMANTIC_TEXCOORD1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1463 Vertex attribute to be treated as a texture coordinate (set 1). ```ts const SEMANTIC_TEXCOORD1: "TEXCOORD1" = 'TEXCOORD1' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD2.md # SEMANTIC_TEXCOORD2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1470 Vertex attribute to be treated as a texture coordinate (set 2). ```ts const SEMANTIC_TEXCOORD2: "TEXCOORD2" = 'TEXCOORD2' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD3.md # SEMANTIC_TEXCOORD3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1477 Vertex attribute to be treated as a texture coordinate (set 3). ```ts const SEMANTIC_TEXCOORD3: "TEXCOORD3" = 'TEXCOORD3' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD4.md # SEMANTIC_TEXCOORD4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1484 Vertex attribute to be treated as a texture coordinate (set 4). ```ts const SEMANTIC_TEXCOORD4: "TEXCOORD4" = 'TEXCOORD4' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD5.md # SEMANTIC_TEXCOORD5 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1491 Vertex attribute to be treated as a texture coordinate (set 5). ```ts const SEMANTIC_TEXCOORD5: "TEXCOORD5" = 'TEXCOORD5' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD6.md # SEMANTIC_TEXCOORD6 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1498 Vertex attribute to be treated as a texture coordinate (set 6). ```ts const SEMANTIC_TEXCOORD6: "TEXCOORD6" = 'TEXCOORD6' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SEMANTIC_TEXCOORD7.md # SEMANTIC_TEXCOORD7 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1505 Vertex attribute to be treated as a texture coordinate (set 7). ```ts const SEMANTIC_TEXCOORD7: "TEXCOORD7" = 'TEXCOORD7' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADER_FORWARD.md # SHADER_FORWARD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L840 Render shaded materials using forward rendering. ```ts const SHADER_FORWARD: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERLANGUAGE_GLSL.md # SHADERLANGUAGE_GLSL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1852 Shader source code uses GLSL language. ```ts const SHADERLANGUAGE_GLSL: "glsl" = 'glsl' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERLANGUAGE_WGSL.md # SHADERLANGUAGE_WGSL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1859 Shader source code uses WGSL language. ```ts const SHADERLANGUAGE_WGSL: "wgsl" = 'wgsl' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_ALBEDO.md # SHADERPASS_ALBEDO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L865 Shader used for debug rendering of albedo. ```ts const SHADERPASS_ALBEDO: "debug_albedo" = 'debug_albedo' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_AO.md # SHADERPASS_AO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L907 Shader used for debug rendering of ao. ```ts const SHADERPASS_AO: "debug_ao" = 'debug_ao' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_EMISSION.md # SHADERPASS_EMISSION Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L914 Shader used for debug rendering of emission. ```ts const SHADERPASS_EMISSION: "debug_emission" = 'debug_emission' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_FORWARD.md # SHADERPASS_FORWARD Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L858 Shader that performs forward rendering. ```ts const SHADERPASS_FORWARD: "forward" = 'forward' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_GLOSS.md # SHADERPASS_GLOSS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L893 Shader used for debug rendering of gloss. ```ts const SHADERPASS_GLOSS: "debug_gloss" = 'debug_gloss' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_LIGHTING.md # SHADERPASS_LIGHTING Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L921 Shader used for debug rendering of lighting. ```ts const SHADERPASS_LIGHTING: "debug_lighting" = 'debug_lighting' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_METALNESS.md # SHADERPASS_METALNESS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L900 Shader used for debug rendering of metalness. ```ts const SHADERPASS_METALNESS: "debug_metalness" = 'debug_metalness' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_OPACITY.md # SHADERPASS_OPACITY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L879 Shader used for debug rendering of opacity. ```ts const SHADERPASS_OPACITY: "debug_opacity" = 'debug_opacity' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_SPECULARITY.md # SHADERPASS_SPECULARITY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L886 Shader used for debug rendering of specularity. ```ts const SHADERPASS_SPECULARITY: "debug_specularity" = 'debug_specularity' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_UV0.md # SHADERPASS_UV0 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L928 Shader used for debug rendering of UV0 texture coordinates. ```ts const SHADERPASS_UV0: "debug_uv0" = 'debug_uv0' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERPASS_WORLDNORMAL.md # SHADERPASS_WORLDNORMAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L872 Shader used for debug rendering of world normal. ```ts const SHADERPASS_WORLDNORMAL: "debug_world_normal" = 'debug_world_normal' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERSTAGE_COMPUTE.md # SHADERSTAGE_COMPUTE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2330 The resource is visible to the compute shader. ```ts const SHADERSTAGE_COMPUTE: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERSTAGE_FRAGMENT.md # SHADERSTAGE_FRAGMENT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2323 The resource is visible to the fragment shader. ```ts const SHADERSTAGE_FRAGMENT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADERSTAGE_VERTEX.md # SHADERSTAGE_VERTEX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2316 The resource is visible to the vertex shader. ```ts const SHADERSTAGE_VERTEX: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_0.md # SHADOW_CASCADE_0 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L416 The flag that controls shadow rendering for the 0 cascade ```ts const SHADOW_CASCADE_0: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_1.md # SHADOW_CASCADE_1 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L423 The flag that controls shadow rendering for the 1 cascade ```ts const SHADOW_CASCADE_1: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_2.md # SHADOW_CASCADE_2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L430 The flag that controls shadow rendering for the 2 cascade ```ts const SHADOW_CASCADE_2: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_3.md # SHADOW_CASCADE_3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L437 The flag that controls shadow rendering for the 3 cascade ```ts const SHADOW_CASCADE_3: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_CASCADE_ALL.md # SHADOW_CASCADE_ALL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L444 The flag that controls shadow rendering for the all cascades ```ts const SHADOW_CASCADE_ALL: 255 = 255 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF1_16F.md # SHADOW_PCF1_16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L375 A shadow sampling technique using a 16-bit shadow map that performs a single depth comparison for sharp shadow edges. ```ts const SHADOW_PCF1_16F: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF1_32F.md # SHADOW_PCF1_32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L350 A shadow sampling technique using a 32-bit shadow map that performs a single depth comparison for sharp shadow edges. ```ts const SHADOW_PCF1_32F: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF3_16F.md # SHADOW_PCF3_16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L383 A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges. ```ts const SHADOW_PCF3_16F: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF3_32F.md # SHADOW_PCF3_32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L290 A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges. ```ts const SHADOW_PCF3_32F: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF5_16F.md # SHADOW_PCF5_16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L391 A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges. ```ts const SHADOW_PCF5_16F: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCF5_32F.md # SHADOW_PCF5_32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L336 A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 5x5 grid of texels for softened shadow edges. ```ts const SHADOW_PCF5_32F: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_PCSS_32F.md # SHADOW_PCSS_32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L367 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatrenderable) and [GraphicsDevice#textureFloatFilterable](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatfilterable) to be true, and falls back to [SHADOW_PCF3_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF3_32F.md) otherwise. ```ts const SHADOW_PCSS_32F: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_VSM_16F.md # SHADOW_VSM_16F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L306 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturehalffloatrenderable) is true. Falls back to [SHADOW_PCF3_32F](https://api.playcanvas.com/engine/variables/SHADOW_PCF3_32F.md), if not supported. ```ts const SHADOW_VSM_16F: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOW_VSM_32F.md # SHADOW_VSM_32F Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L322 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](https://api.playcanvas.com/engine/classes/GraphicsDevice.md#texturefloatrenderable) is true. Falls back to [SHADOW_VSM_16F](https://api.playcanvas.com/engine/variables/SHADOW_VSM_16F.md), if not supported. ```ts const SHADOW_VSM_32F: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOWUPDATE_NONE.md # SHADOWUPDATE_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L783 The shadow map is not to be updated. ```ts const SHADOWUPDATE_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOWUPDATE_REALTIME.md # SHADOWUPDATE_REALTIME Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L797 The shadow map is regenerated every frame. ```ts const SHADOWUPDATE_REALTIME: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SHADOWUPDATE_THISFRAME.md # SHADOWUPDATE_THISFRAME Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L790 The shadow map is regenerated this frame and not on subsequent frames. ```ts const SHADOWUPDATE_THISFRAME: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SKYTYPE_BOX.md # SKYTYPE_BOX Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1083 A sky texture is rendered using a box projection. This is generally suitable for interior environments. ```ts const SKYTYPE_BOX: "box" = 'box' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SKYTYPE_DOME.md # SKYTYPE_DOME Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1091 A sky texture is rendered using a dome projection. This is generally suitable for exterior environments. ```ts const SKYTYPE_DOME: "dome" = 'dome' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SKYTYPE_INFINITE.md # SKYTYPE_INFINITE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1075 A sky texture is rendered using an infinite projection. ```ts const SKYTYPE_INFINITE: "infinite" = 'infinite' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SORTMODE_BACK2FRONT.md # SORTMODE_BACK2FRONT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1024 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. ```ts const SORTMODE_BACK2FRONT: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SORTMODE_FRONT2BACK.md # SORTMODE_FRONT2BACK Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1032 Mesh instances are sorted front to back. Depending on GPU and the scene, this option may give better performance than [SORTMODE_MATERIALMESH](https://api.playcanvas.com/engine/variables/SORTMODE_MATERIALMESH.md) due to reduced overdraw. ```ts const SORTMODE_FRONT2BACK: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SORTMODE_MANUAL.md # SORTMODE_MANUAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1008 Mesh instances are sorted based on [MeshInstance#drawOrder](https://api.playcanvas.com/engine/classes/MeshInstance.md#draworder). ```ts const SORTMODE_MANUAL: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SORTMODE_MATERIALMESH.md # SORTMODE_MATERIALMESH Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1016 Mesh instances are sorted to minimize switching between materials and meshes to improve rendering performance. ```ts const SORTMODE_MATERIALMESH: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SORTMODE_NONE.md # SORTMODE_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1001 No sorting is applied. Mesh instances are rendered in the same order they were added to a layer. ```ts const SORTMODE_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPECOCC_AO.md # SPECOCC_AO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L716 Use AO directly to occlude specular. ```ts const SPECOCC_AO: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPECOCC_GLOSSDEPENDENT.md # SPECOCC_GLOSSDEPENDENT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L723 Modify AO based on material glossiness/view angle to occlude specular. ```ts const SPECOCC_GLOSSDEPENDENT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPECOCC_NONE.md # SPECOCC_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L709 No specular occlusion. ```ts const SPECOCC_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_SIMPLE.md # SPRITE_RENDERMODE_SIMPLE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L935 This mode renders a sprite as a simple quad. ```ts const SPRITE_RENDERMODE_SIMPLE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_SLICED.md # SPRITE_RENDERMODE_SLICED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L944 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. ```ts const SPRITE_RENDERMODE_SLICED: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPRITE_RENDERMODE_TILED.md # SPRITE_RENDERMODE_TILED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L953 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. ```ts const SPRITE_RENDERMODE_TILED: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPRITETYPE_ANIMATED.md # SPRITETYPE_ANIMATED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/constants.js#L13 A [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md) that renders sprite animations. ```ts const SPRITETYPE_ANIMATED: "animated" = 'animated' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SPRITETYPE_SIMPLE.md # SPRITETYPE_SIMPLE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/constants.js#L6 A [SpriteComponent](https://api.playcanvas.com/engine/classes/SpriteComponent.md) that displays a single frame from a sprite asset. ```ts const SPRITETYPE_SIMPLE: "simple" = 'simple' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SSAOTYPE_COMBINE.md # SSAOTYPE_COMBINE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L24 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. ```ts const SSAOTYPE_COMBINE: "combine" = 'combine' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SSAOTYPE_LIGHTING.md # SSAOTYPE_LIGHTING Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L15 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. ```ts const SSAOTYPE_LIGHTING: "lighting" = 'lighting' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/SSAOTYPE_NONE.md # SSAOTYPE_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L6 SSAO is disabled. ```ts const SSAOTYPE_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_DECREMENT.md # STENCILOP_DECREMENT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1661 Decrement the value. ```ts const STENCILOP_DECREMENT: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_DECREMENTWRAP.md # STENCILOP_DECREMENTWRAP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1668 Decrement the value but wrap it to a maximum representable value if the current value is 0. ```ts const STENCILOP_DECREMENTWRAP: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_INCREMENT.md # STENCILOP_INCREMENT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1647 Increment the value. ```ts const STENCILOP_INCREMENT: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_INCREMENTWRAP.md # STENCILOP_INCREMENTWRAP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1654 Increment the value but wrap it to zero when it's larger than a maximum representable value. ```ts const STENCILOP_INCREMENTWRAP: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_INVERT.md # STENCILOP_INVERT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1675 Invert the value bitwise. ```ts const STENCILOP_INVERT: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_KEEP.md # STENCILOP_KEEP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1626 Don't change the stencil buffer value. ```ts const STENCILOP_KEEP: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_REPLACE.md # STENCILOP_REPLACE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1640 Replace value with the reference value (see [StencilParameters](https://api.playcanvas.com/engine/classes/StencilParameters.md)). ```ts const STENCILOP_REPLACE: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/STENCILOP_ZERO.md # STENCILOP_ZERO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1633 Set value to zero. ```ts const STENCILOP_ZERO: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_1D.md # TEXTUREDIMENSION_1D Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1745 Texture data is stored in a 1-dimensional texture. ```ts const TEXTUREDIMENSION_1D: "1d" = '1d' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D.md # TEXTUREDIMENSION_2D Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1752 Texture data is stored in a 2-dimensional texture. ```ts const TEXTUREDIMENSION_2D: "2d" = '2d' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_2D_ARRAY.md # TEXTUREDIMENSION_2D_ARRAY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1759 Texture data is stored in an array of 2-dimensional textures. ```ts const TEXTUREDIMENSION_2D_ARRAY: "2d-array" = '2d-array' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_3D.md # TEXTUREDIMENSION_3D Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1780 Texture data is stored in a 3-dimensional texture. ```ts const TEXTUREDIMENSION_3D: "3d" = '3d' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_CUBE.md # TEXTUREDIMENSION_CUBE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1766 Texture data is stored in a cube texture. ```ts const TEXTUREDIMENSION_CUBE: "cube" = 'cube' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREDIMENSION_CUBE_ARRAY.md # TEXTUREDIMENSION_CUBE_ARRAY Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1773 Texture data is stored in an array of cube textures. ```ts const TEXTUREDIMENSION_CUBE_ARRAY: "cube-array" = 'cube-array' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURELOCK_NONE.md # TEXTURELOCK_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1682 The texture is not in a locked state. ```ts const TEXTURELOCK_NONE: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURELOCK_READ.md # TEXTURELOCK_READ Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1689 Read only. Any changes to the locked mip level's pixels will not update the texture. ```ts const TEXTURELOCK_READ: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURELOCK_WRITE.md # TEXTURELOCK_WRITE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1696 Write only. The contents of the specified mip level will be entirely replaced. ```ts const TEXTURELOCK_WRITE: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_CUBE.md # TEXTUREPROJECTION_CUBE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1831 Texture data is stored in cubemap projection format. ```ts const TEXTUREPROJECTION_CUBE: "cube" = 'cube' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_EQUIRECT.md # TEXTUREPROJECTION_EQUIRECT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1838 Texture data is stored in equirectangular projection format. ```ts const TEXTUREPROJECTION_EQUIRECT: "equirect" = 'equirect' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_NONE.md # TEXTUREPROJECTION_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1824 Texture data is not stored a specific projection format. ```ts const TEXTUREPROJECTION_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTUREPROJECTION_OCTAHEDRAL.md # TEXTUREPROJECTION_OCTAHEDRAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1845 Texture data is stored in octahedral projection format. ```ts const TEXTUREPROJECTION_OCTAHEDRAL: "octahedral" = 'octahedral' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURETYPE_DEFAULT.md # TEXTURETYPE_DEFAULT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1703 Texture is a default type. ```ts const TEXTURETYPE_DEFAULT: "default" = 'default' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBE.md # TEXTURETYPE_RGBE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1717 Texture stores high dynamic range data in RGBE format. ```ts const TEXTURETYPE_RGBE: "rgbe" = 'rgbe' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBM.md # TEXTURETYPE_RGBM Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1710 Texture stores high dynamic range data in RGBM format. ```ts const TEXTURETYPE_RGBM: "rgbm" = 'rgbm' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURETYPE_RGBP.md # TEXTURETYPE_RGBP Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1724 Texture stores high dynamic range data in RGBP encoding. ```ts const TEXTURETYPE_RGBP: "rgbp" = 'rgbp' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TEXTURETYPE_SWIZZLEGGGR.md # TEXTURETYPE_SWIZZLEGGGR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1733 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. ```ts const TEXTURETYPE_SWIZZLEGGGR: "swizzleGGGR" = 'swizzleGGGR' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_ACES.md # TONEMAP_ACES Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L670 ACES filmic tonemapping curve. ```ts const TONEMAP_ACES: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_ACES2.md # TONEMAP_ACES2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L677 ACES v2 filmic tonemapping curve. ```ts const TONEMAP_ACES2: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_FILMIC.md # TONEMAP_FILMIC Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L656 Filmic tonemapping curve. ```ts const TONEMAP_FILMIC: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_HEJL.md # TONEMAP_HEJL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L663 Hejl filmic tonemapping curve. ```ts const TONEMAP_HEJL: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_LINEAR.md # TONEMAP_LINEAR Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L649 Linear tonemapping. The colors are preserved, but the exposure is applied. ```ts const TONEMAP_LINEAR: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_NEUTRAL.md # TONEMAP_NEUTRAL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L684 Khronos PBR Neutral tonemapping curve. ```ts const TONEMAP_NEUTRAL: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TONEMAP_NONE.md # TONEMAP_NONE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L691 No tonemapping or exposure is applied. Used for HDR rendering. ```ts const TONEMAP_NONE: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_ASSETS.md # TRACEID_ASSETS Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L162 Logs all assets in the asset registry. ```ts const TRACEID_ASSETS: "Assets" = 'Assets' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_BINDGROUP_ALLOC.md # TRACEID_BINDGROUP_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L98 Logs the creation of bind groups. ```ts const TRACEID_BINDGROUP_ALLOC: "BindGroupAlloc" = 'BindGroupAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_BINDGROUPFORMAT_ALLOC.md # TRACEID_BINDGROUPFORMAT_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L113 Logs the creation of bind group formats. ```ts const TRACEID_BINDGROUPFORMAT_ALLOC: "BindGroupFormatAlloc" = 'BindGroupFormatAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_BUFFERS.md # TRACEID_BUFFERS Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L155 Logs GPU buffer memory tracked on the graphics device (vertex, index, storage). ```ts const TRACEID_BUFFERS: "Buffers" = 'Buffers' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_COMPUTEPIPELINE_ALLOC.md # TRACEID_COMPUTEPIPELINE_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L127 Logs the creation of compute pipelines. WebGPU only. ```ts const TRACEID_COMPUTEPIPELINE_ALLOC: "ComputePipelineAlloc" = 'ComputePipelineAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_ELEMENT.md # TRACEID_ELEMENT Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L141 Logs the internal debug information for Elements. ```ts const TRACEID_ELEMENT: "Element" = 'Element' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_GPU_TIMINGS.md # TRACEID_GPU_TIMINGS Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L183 Logs the GPU timings. ```ts const TRACEID_GPU_TIMINGS: "GpuTimings" = 'GpuTimings' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_MATERIAL_UPDATE.md # TRACEID_MATERIAL_UPDATE Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L106 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](https://api.playcanvas.com/engine/classes/Material.md#update). ```ts const TRACEID_MATERIAL_UPDATE: "MaterialUpdate" = 'MaterialUpdate' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_OCTREE_RESOURCES.md # TRACEID_OCTREE_RESOURCES Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L176 Logs the loaded GSplat resources for individual LOD levels of an octree. ```ts const TRACEID_OCTREE_RESOURCES: "OctreeResources" = 'OctreeResources' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_PIPELINELAYOUT_ALLOC.md # TRACEID_PIPELINELAYOUT_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L134 Logs the creation of pipeline layouts. WebGPU only. ```ts const TRACEID_PIPELINELAYOUT_ALLOC: "PipelineLayoutAlloc" = 'PipelineLayoutAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_ACTION.md # TRACEID_RENDER_ACTION Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L35 Logs render actions created by the layer composition. Only executes when the layer composition changes. ```ts const TRACEID_RENDER_ACTION: "RenderAction" = 'RenderAction' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_FRAME.md # TRACEID_RENDER_FRAME Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L6 Logs a frame number. ```ts const TRACEID_RENDER_FRAME: "RenderFrame" = 'RenderFrame' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_FRAME_TIME.md # TRACEID_RENDER_FRAME_TIME Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L13 Logs a frame time. ```ts const TRACEID_RENDER_FRAME_TIME: "RenderFrameTime" = 'RenderFrameTime' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_PASS.md # TRACEID_RENDER_PASS Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L20 Logs basic information about generated render passes. ```ts const TRACEID_RENDER_PASS: "RenderPass" = 'RenderPass' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_PASS_DETAIL.md # TRACEID_RENDER_PASS_DETAIL Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L27 Logs additional detail for render passes. ```ts const TRACEID_RENDER_PASS_DETAIL: "RenderPassDetail" = 'RenderPassDetail' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_QUEUE.md # TRACEID_RENDER_QUEUE Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L169 Logs the render queue commands. ```ts const TRACEID_RENDER_QUEUE: "RenderQueue" = 'RenderQueue' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDER_TARGET_ALLOC.md # TRACEID_RENDER_TARGET_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L42 Logs the allocation of render targets. ```ts const TRACEID_RENDER_TARGET_ALLOC: "RenderTargetAlloc" = 'RenderTargetAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_RENDERPIPELINE_ALLOC.md # TRACEID_RENDERPIPELINE_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L120 Logs the creation of render pipelines. WebGPU only. ```ts const TRACEID_RENDERPIPELINE_ALLOC: "RenderPipelineAlloc" = 'RenderPipelineAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_SHADER_ALLOC.md # TRACEID_SHADER_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L56 Logs the creation of shaders. ```ts const TRACEID_SHADER_ALLOC: "ShaderAlloc" = 'ShaderAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_SHADER_COMPILE.md # TRACEID_SHADER_COMPILE Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L63 Logs the compilation time of shaders. ```ts const TRACEID_SHADER_COMPILE: "ShaderCompile" = 'ShaderCompile' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_TEXTURE_ALLOC.md # TRACEID_TEXTURE_ALLOC Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L49 Logs the allocation of textures. ```ts const TRACEID_TEXTURE_ALLOC: "TextureAlloc" = 'TextureAlloc' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_TEXTURES.md # TRACEID_TEXTURES Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L148 Logs the vram use by all textures in memory. ```ts const TRACEID_TEXTURES: "Textures" = 'Textures' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_VRAM_IB.md # TRACEID_VRAM_IB Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L84 Logs the vram use by the index buffers. ```ts const TRACEID_VRAM_IB: "VRAM.Ib" = 'VRAM.Ib' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_VRAM_SB.md # TRACEID_VRAM_SB Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L91 Logs the vram use by the storage buffers. ```ts const TRACEID_VRAM_SB: "VRAM.Sb" = 'VRAM.Sb' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_VRAM_TEXTURE.md # TRACEID_VRAM_TEXTURE Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L70 Logs the vram use by the textures. ```ts const TRACEID_VRAM_TEXTURE: "VRAM.Texture" = 'VRAM.Texture' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRACEID_VRAM_VB.md # TRACEID_VRAM_VB Variable · category: Debug Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L77 Logs the vram use by the vertex buffers. ```ts const TRACEID_VRAM_VB: "VRAM.Vb" = 'VRAM.Vb' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_INTERLEAVED.md # TRANSFORM_FEEDBACK_INTERLEAVED Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L291 Captures all varyings into one interleaved transform feedback buffer. ```ts const TRANSFORM_FEEDBACK_INTERLEAVED: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TRANSFORM_FEEDBACK_SEPARATE.md # TRANSFORM_FEEDBACK_SEPARATE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L298 Captures each varying into its own transform feedback buffer. ```ts const TRANSFORM_FEEDBACK_SEPARATE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_FLOAT16.md # TYPE_FLOAT16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1915 16-bit floating point vertex element type. ```ts const TYPE_FLOAT16: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_FLOAT32.md # TYPE_FLOAT32 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1908 Floating point vertex element type. ```ts const TYPE_FLOAT32: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_INT16.md # TYPE_INT16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1880 Signed short vertex element type. ```ts const TYPE_INT16: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_INT32.md # TYPE_INT32 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1894 Signed integer vertex element type. ```ts const TYPE_INT32: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_INT8.md # TYPE_INT8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1866 Signed byte vertex element type. ```ts const TYPE_INT8: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_UINT16.md # TYPE_UINT16 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1887 Unsigned short vertex element type. ```ts const TYPE_UINT16: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_UINT32.md # TYPE_UINT32 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1901 Unsigned integer vertex element type. ```ts const TYPE_UINT32: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/TYPE_UINT8.md # TYPE_UINT8 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1873 Unsigned byte vertex element type. ```ts const TYPE_UINT8: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_BOOL.md # UNIFORMTYPE_BOOL Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1927 Boolean uniform type. ```ts const UNIFORMTYPE_BOOL: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_BVEC2.md # UNIFORMTYPE_BVEC2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1990 2 x Boolean uniform type. ```ts const UNIFORMTYPE_BVEC2: 9 = 9 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_BVEC3.md # UNIFORMTYPE_BVEC3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1997 3 x Boolean uniform type. ```ts const UNIFORMTYPE_BVEC3: 10 = 10 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_BVEC4.md # UNIFORMTYPE_BVEC4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2004 4 x Boolean uniform type. ```ts const UNIFORMTYPE_BVEC4: 11 = 11 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_FLOAT.md # UNIFORMTYPE_FLOAT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1941 Float uniform type. ```ts const UNIFORMTYPE_FLOAT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_INT.md # UNIFORMTYPE_INT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1934 Integer uniform type. ```ts const UNIFORMTYPE_INT: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_IVEC2.md # UNIFORMTYPE_IVEC2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1969 2 x Integer uniform type. ```ts const UNIFORMTYPE_IVEC2: 6 = 6 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_IVEC3.md # UNIFORMTYPE_IVEC3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1976 3 x Integer uniform type. ```ts const UNIFORMTYPE_IVEC3: 7 = 7 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_IVEC4.md # UNIFORMTYPE_IVEC4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1983 4 x Integer uniform type. ```ts const UNIFORMTYPE_IVEC4: 8 = 8 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_MAT2.md # UNIFORMTYPE_MAT2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2011 2 x 2 x Float uniform type. ```ts const UNIFORMTYPE_MAT2: 12 = 12 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_MAT3.md # UNIFORMTYPE_MAT3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2018 3 x 3 x Float uniform type. ```ts const UNIFORMTYPE_MAT3: 13 = 13 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_MAT4.md # UNIFORMTYPE_MAT4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2025 4 x 4 x Float uniform type. ```ts const UNIFORMTYPE_MAT4: 14 = 14 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_UINT.md # UNIFORMTYPE_UINT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2046 Unsigned integer uniform type. ```ts const UNIFORMTYPE_UINT: 26 = 26 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_UVEC2.md # UNIFORMTYPE_UVEC2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2053 2 x Unsigned integer uniform type. ```ts const UNIFORMTYPE_UVEC2: 27 = 27 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_UVEC3.md # UNIFORMTYPE_UVEC3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2060 3 x Unsigned integer uniform type. ```ts const UNIFORMTYPE_UVEC3: 28 = 28 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_UVEC4.md # UNIFORMTYPE_UVEC4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2067 4 x Unsigned integer uniform type. ```ts const UNIFORMTYPE_UVEC4: 29 = 29 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_VEC2.md # UNIFORMTYPE_VEC2 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1948 2 x Float uniform type. ```ts const UNIFORMTYPE_VEC2: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_VEC3.md # UNIFORMTYPE_VEC3 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1955 3 x Float uniform type. ```ts const UNIFORMTYPE_VEC3: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/UNIFORMTYPE_VEC4.md # UNIFORMTYPE_VEC4 Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1962 4 x Float uniform type. ```ts const UNIFORMTYPE_VEC4: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/VIEW_CENTER.md # VIEW_CENTER Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L980 Center of view. ```ts const VIEW_CENTER: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/VIEW_LEFT.md # VIEW_LEFT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L987 Left of view. Only used in stereo rendering. ```ts const VIEW_LEFT: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/VIEW_RIGHT.md # VIEW_RIGHT Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L994 Right of view. Only used in stereo rendering. ```ts const VIEW_RIGHT: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/WORKBUFFER_UPDATE_ALWAYS.md # WORKBUFFER_UPDATE_ALWAYS Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1256 Work buffer is updated every frame. Useful for custom shader code via [GSplatComponent#setWorkBufferModifier](https://api.playcanvas.com/engine/classes/GSplatComponent.md#setworkbuffermodifier) that depends on time or animated uniforms. ```ts const WORKBUFFER_UPDATE_ALWAYS: number = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/WORKBUFFER_UPDATE_AUTO.md # WORKBUFFER_UPDATE_AUTO Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1238 Work buffer is updated only when needed (transform, format, LOD changes, new gsplat etc). ```ts const WORKBUFFER_UPDATE_AUTO: number = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/WORKBUFFER_UPDATE_ONCE.md # WORKBUFFER_UPDATE_ONCE Variable · category: Graphics Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1247 Work buffer is updated once on the next frame, then automatically switches to [WORKBUFFER_UPDATE_AUTO](https://api.playcanvas.com/engine/variables/WORKBUFFER_UPDATE_AUTO.md). ```ts const WORKBUFFER_UPDATE_ONCE: number = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRDEPTHSENSINGFORMAT_F32.md # XRDEPTHSENSINGFORMAT_F32 Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L204 Float 32 - indicates that depth sensing preferred raw data format is Float (32 bit). ```ts const XRDEPTHSENSINGFORMAT_F32: "float32" = 'float32' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRDEPTHSENSINGFORMAT_L8A8.md # XRDEPTHSENSINGFORMAT_L8A8 Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L190 Luminance Alpha - indicates that depth sensing preferred raw data format is Luminance Alpha (8bit + 8bit). This format is guaranteed to be supported. ```ts const XRDEPTHSENSINGFORMAT_L8A8: "luminance-alpha" = 'luminance-alpha' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRDEPTHSENSINGFORMAT_R16U.md # XRDEPTHSENSINGFORMAT_R16U Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L197 Unsigned Short - indicates that depth sensing preferred raw data format is Unsigned Short (16 bit). ```ts const XRDEPTHSENSINGFORMAT_R16U: "unsigned-short" = 'unsigned-short' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRDEPTHSENSINGUSAGE_CPU.md # XRDEPTHSENSINGUSAGE_CPU Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L175 CPU - indicates that depth sensing preferred usage is CPU. This usage path is guaranteed to be supported. ```ts const XRDEPTHSENSINGUSAGE_CPU: "cpu-optimized" = 'cpu-optimized' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRDEPTHSENSINGUSAGE_GPU.md # XRDEPTHSENSINGUSAGE_GPU Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L182 GPU - indicates that depth sensing preferred usage is GPU. ```ts const XRDEPTHSENSINGUSAGE_GPU: "gpu-optimized" = 'gpu-optimized' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XREYE_LEFT.md # XREYE_LEFT Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L115 Left - view associated with left eye. ```ts const XREYE_LEFT: "left" = 'left' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XREYE_NONE.md # XREYE_NONE Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L108 None - view associated with a monoscopic screen, such as mobile phone screens. ```ts const XREYE_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XREYE_RIGHT.md # XREYE_RIGHT Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L122 Right - view associated with right eye. ```ts const XREYE_RIGHT: "right" = 'right' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRHAND_LEFT.md # XRHAND_LEFT Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L136 Left - indicates that input source is meant to be held in left hand. ```ts const XRHAND_LEFT: "left" = 'left' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRHAND_NONE.md # XRHAND_NONE Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L129 None - input source is not meant to be held in hands. ```ts const XRHAND_NONE: "none" = 'none' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRHAND_RIGHT.md # XRHAND_RIGHT Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L143 Right - indicates that input source is meant to be held in right hand. ```ts const XRHAND_RIGHT: "right" = 'right' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_A.md # XRPAD_A Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L859 The A button from XR pad. ```ts const XRPAD_A: 4 = 4 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_B.md # XRPAD_B Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L866 The B button from XR pad. ```ts const XRPAD_B: 5 = 5 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_SQUEEZE.md # XRPAD_SQUEEZE Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L845 The squeeze button from XR pad. ```ts const XRPAD_SQUEEZE: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_STICK_BUTTON.md # XRPAD_STICK_BUTTON Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L852 The button when pressing the XR pad's stick. ```ts const XRPAD_STICK_BUTTON: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_STICK_X.md # XRPAD_STICK_X Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L817 Horizontal axis on the stick of an XR pad. ```ts const XRPAD_STICK_X: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_STICK_Y.md # XRPAD_STICK_Y Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L824 Vertical axis on the stick of an XR pad. ```ts const XRPAD_STICK_Y: 3 = 3 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_TOUCHPAD_BUTTON.md # XRPAD_TOUCHPAD_BUTTON Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L831 The button when pressing the XR pad's touchpad. ```ts const XRPAD_TOUCHPAD_BUTTON: 2 = 2 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_TOUCHPAD_X.md # XRPAD_TOUCHPAD_X Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L803 Horizontal axis on the touchpad of an XR pad. ```ts const XRPAD_TOUCHPAD_X: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_TOUCHPAD_Y.md # XRPAD_TOUCHPAD_Y Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L810 Vertical axis on the touchpad of an XR pad. ```ts const XRPAD_TOUCHPAD_Y: 1 = 1 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRPAD_TRIGGER.md # XRPAD_TRIGGER Variable · category: Input Devices Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L838 The trigger button from XR pad. ```ts const XRPAD_TRIGGER: 0 = 0 ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRSPACE_BOUNDEDFLOOR.md # XRSPACE_BOUNDEDFLOOR Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L65 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. ```ts const XRSPACE_BOUNDEDFLOOR: "bounded-floor" = 'bounded-floor' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRSPACE_LOCAL.md # XRSPACE_LOCAL Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L42 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. ```ts const XRSPACE_LOCAL: "local" = 'local' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRSPACE_LOCALFLOOR.md # XRSPACE_LOCALFLOOR Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L55 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. ```ts const XRSPACE_LOCALFLOOR: "local-floor" = 'local-floor' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRSPACE_UNBOUNDED.md # XRSPACE_UNBOUNDED Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L75 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. ```ts const XRSPACE_UNBOUNDED: "unbounded" = 'unbounded' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md # XRSPACE_VIEWER Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L30 Viewer - always supported space with some basic tracking capabilities. ```ts const XRSPACE_VIEWER: "viewer" = 'viewer' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTARGETRAY_GAZE.md # XRTARGETRAY_GAZE Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L84 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. ```ts const XRTARGETRAY_GAZE: "gaze" = 'gaze' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTARGETRAY_POINTER.md # XRTARGETRAY_POINTER Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L101 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. ```ts const XRTARGETRAY_POINTER: "tracked-pointer" = 'tracked-pointer' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTARGETRAY_SCREEN.md # XRTARGETRAY_SCREEN Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L92 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. ```ts const XRTARGETRAY_SCREEN: "screen" = 'screen' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTRACKABLE_MESH.md # XRTRACKABLE_MESH Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L167 Mesh - indicates that the hit test results will be computed based on the meshes detected by the underlying Augmented Reality system. ```ts const XRTRACKABLE_MESH: "mesh" = 'mesh' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTRACKABLE_PLANE.md # XRTRACKABLE_PLANE Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L159 Plane - indicates that the hit test results will be computed based on the planes detected by the underlying Augmented Reality system. ```ts const XRTRACKABLE_PLANE: "plane" = 'plane' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTRACKABLE_POINT.md # XRTRACKABLE_POINT Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L151 Point - indicates that the hit test results will be computed based on the feature points detected by the underlying Augmented Reality system. ```ts const XRTRACKABLE_POINT: "point" = 'point' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTYPE_AR.md # XRTYPE_AR Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L23 Immersive AR - session that provides exclusive access to VR/AR device that is intended to be blended with real-world environment. ```ts const XRTYPE_AR: "immersive-ar" = 'immersive-ar' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTYPE_INLINE.md # XRTYPE_INLINE Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L7 Inline - always available type of session. It has limited features availability and is rendered into HTML element. ```ts const XRTYPE_INLINE: "inline" = 'inline' ``` -------------------------------------------------------------------------------- URL: https://api.playcanvas.com/engine/variables/XRTYPE_VR.md # XRTYPE_VR Variable · category: XR Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L15 Immersive VR - session that provides exclusive access to VR device with best available tracking features. ```ts const XRTYPE_VR: "immersive-vr" = 'immersive-vr' ``` --------------------------------------------------------------------------------