UNPKG

playcanvas

Version:

PlayCanvas WebGL game engine

1,302 lines (1,247 loc) 782 kB
/** * Used to set the anim state graph transition interruption source to no state. */ export const ANIM_INTERRUPTION_NONE: string; /** * Used to set the anim state graph transition interruption source as the previous state only. */ export const ANIM_INTERRUPTION_PREV: string; /** * Used to set the anim state graph transition interruption source as the next state only. */ export const ANIM_INTERRUPTION_NEXT: string; /** * Used to set the anim state graph transition interruption sources as the previous state followed by the next state. */ export const ANIM_INTERRUPTION_PREV_NEXT: string; /** * Used to set the anim state graph transition interruption sources as the next state followed by the previous state. */ export const ANIM_INTERRUPTION_NEXT_PREV: string; /** * Used to set an anim state graph transition condition predicate as '>'. */ export const ANIM_GREATER_THAN: string; /** * Used to set an anim state graph transition condition predicate as '<'. */ export const ANIM_LESS_THAN: string; /** * Used to set an anim state graph transition condition predicate as '>='. */ export const ANIM_GREATER_THAN_EQUAL_TO: string; /** * Used to set an anim state graph transition condition predicate as '<='. */ export const ANIM_LESS_THAN_EQUAL_TO: string; /** * Used to set an anim state graph transition condition predicate as '==='. */ export const ANIM_EQUAL_TO: string; /** * Used to set an anim state graph transition condition predicate as '!=='. */ export const ANIM_NOT_EQUAL_TO: string; /** * Used to set an anim state graph parameter as type integer. */ export const ANIM_PARAMETER_INTEGER: string; /** * Used to set an anim state graph parameter as type float. */ export const ANIM_PARAMETER_FLOAT: string; /** * Used to set an anim state graph parameter as type boolean. */ export const ANIM_PARAMETER_BOOLEAN: string; /** * Used to set an anim state graph parameter as type trigger. */ export const ANIM_PARAMETER_TRIGGER: string; export const ANIM_BLEND_1D: string; export const ANIM_BLEND_2D_DIRECTIONAL: string; export const ANIM_BLEND_2D_CARTESIAN: string; export const ANIM_BLEND_DIRECT: string; /** * The starting state in an anim state graph layer. */ export const ANIM_STATE_START: string; /** * The ending state in an anim state graph layer. */ export const ANIM_STATE_END: string; /** * Used to indicate any state in an anim state graph layer. */ export const ANIM_STATE_ANY: string; /** * Creates an AnimStateGraph asset resource from a blob of JSON data that represents an anim state graph. */ export class AnimStateGraph { } /** * Create a new animation node. */ export class Node { } /** * An animation is a sequence of keyframe arrays which map to the nodes of a skeletal hierarchy. It controls how the nodes of the hierarchy are transformed over time. * @property name - Human-readable name of the animation. * @property duration - Duration of the animation in seconds. */ export class Animation { /** * Gets a {@link Node} by name. * @param name - The name of the {@link Node}. * @returns The {@link Node} with the specified name. */ getNode(name: string): Node; /** * A read-only property to get array of animation nodes. */ readonly nodes: Node[]; /** * Adds a node to the internal nodes array. * @param node - The node to add. */ addNode(node: Node): void; /** * Human-readable name of the animation. */ name: string; /** * Duration of the animation in seconds. */ duration: number; } /** * Represents a skeleton used to play animations. * @property looping - Determines whether skeleton is looping its animation. * @param graph - The root {@link GraphNode} of the skeleton. */ export class Skeleton { constructor(graph: GraphNode); /** * Animation currently assigned to skeleton. */ animation: Animation; /** * Current time of currently active animation in seconds. This value is between zero and the duration of the animation. */ currentTime: number; /** * Read-only property that returns number of nodes of a skeleton. */ readonly numNodes: number; /** * 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). * @param delta - The time in seconds to progress the skeleton's animation. */ addTime(delta: number): void; /** * Blends two skeletons together. * @param skel1 - Skeleton holding the first pose to be blended. * @param skel2 - Skeleton holding the second pose to be blended. * @param alpha - 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. */ blend(skel1: Skeleton, skel2: Skeleton, alpha: number): 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. * @param graph - The root node of the graph that the skeleton is to drive. */ setGraph(graph: GraphNode): 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. */ updateGraph(): void; /** * Determines whether skeleton is looping its animation. */ looping: boolean; } /** * An object that manages the case where an object holds a reference to an asset and needs to be notified when * changes occur in the asset. e.g. notifications include load, add and remove events. * @example * var reference = new pc.AssetReference('textureAsset', this, this.app.assets, { * load: this.onTextureAssetLoad, * add: this.onTextureAssetAdd, * remove: this.onTextureAssetRemove * }, this); * reference.id = this.textureAsset.id; * @property id - Get or set the asset id which this references. One of either id or url must be set to initialize an asset reference. * @property url - Get or set the asset url which this references. One of either id or url must be called to initialize an asset reference. * @param propertyName - The name of the property that the asset is stored under, passed into callbacks to enable updating. * @param parent - The parent object that contains the asset reference, passed into callbacks to enable updating. Currently an asset, but could be component or other. * @param registry - The asset registry that stores all assets. * @param callbacks - A set of functions called when the asset state changes: load, add, remove. * @param [callbacks.load] - The function called when the asset loads load(propertyName, parent, asset). * @param [callbacks.add] - The function called when the asset is added to the registry add(propertyName, parent, asset). * @param [callbacks.remove] - The function called when the asset is remove from the registry remove(propertyName, parent, asset). * @param [callbacks.unload] - The function called when the asset is unloaded unload(propertyName, parent, asset). * @param [scope] - The scope to call the callbacks in */ export class AssetReference { constructor(propertyName: string, parent: Asset | any, registry: AssetRegistry, callbacks: { load?: any; add?: any; remove?: any; unload?: any; }, scope?: any); /** * Get or set the asset id which this references. One of either id or url must be set to initialize an asset reference. */ id: number; /** * Get or set the asset url which this references. One of either id or url must be called to initialize an asset reference. */ url: string; } /** * Create an instance of an AssetRegistry. * Note: PlayCanvas scripts are provided with an AssetRegistry instance as 'app.assets'. * @property prefix - A URL prefix that will be added to all asset loading requests. * @param loader - The ResourceLoader used to load the asset files. */ export class AssetRegistry extends EventHandler { constructor(loader: ResourceLoader); /** * Create a filtered list of assets from the registry. * @param filters - Properties to filter on, currently supports: 'preload: true|false'. * @returns The filtered list of assets. */ list(filters: any): Asset[]; /** * Add an asset to the registry. * @example * var asset = new pc.Asset("My Asset", "texture", { * url: "../path/to/image.jpg" * }); * app.assets.add(asset); * @param asset - The asset to add. */ add(asset: Asset): void; /** * Remove an asset from the registry. * @example * var asset = app.assets.get(100); * app.assets.remove(asset); * @param asset - The asset to remove. * @returns True if the asset was successfully removed and false otherwise. */ remove(asset: Asset): boolean; /** * Retrieve an asset from the registry by its id field. * @example * var asset = app.assets.get(100); * @param id - The id of the asset to get. * @returns The asset. */ get(id: number): Asset; /** * Retrieve an asset from the registry by it's file's URL field. * @example * var asset = app.assets.getByUrl("../path/to/image.jpg"); * @param url - The url of the asset to get. * @returns The asset. */ getByUrl(url: string): Asset; /** * Load the asset's file from a remote source. Listen for "load" events on the asset to find out when it is loaded. * @example * // load some assets * var assetsToLoad = [ * app.assets.find("My Asset"), * app.assets.find("Another Asset") * ]; * var count = 0; * assetsToLoad.forEach(function (assetToLoad) { * assetToLoad.ready(function (asset) { * count++; * if (count === assetsToLoad.length) { * // done * } * }); * app.assets.load(assetToLoad); * }); * @param asset - The asset to load. */ load(asset: Asset): 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. * @example * app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) { * var texture = asset.resource; * }); * @param url - The url to load. * @param type - The type of asset to load. * @param callback - Function called when asset is loaded, passed (err, asset), where err is null if no errors were encountered. */ loadFromUrl(url: string, type: string, callback: callbacks.LoadAsset): 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. * @example * var file = magicallyAttainAFile(); * app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) { * var texture = asset.resource; * }); * @param url - The url to load. * @param filename - The filename of the asset to load. * @param type - The type of asset to load. * @param callback - Function called when asset is loaded, passed (err, asset), where err is null if no errors were encountered. */ loadFromUrlAndFilename(url: string, filename: string, type: string, callback: callbacks.LoadAsset): void; /** * Return all Assets with the specified name and type found in the registry. * @example * var assets = app.assets.findAll("myTextureAsset", "texture"); * console.log("Found " + assets.length + " assets called " + name); * @param name - The name of the Assets to find. * @param [type] - The type of the Assets to find. * @returns A list of all Assets found. */ findAll(name: string, type?: string): 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. * @example * var assets = app.assets.findByTag("level-1"); * // returns all assets that tagged by `level-1` * @example * var assets = app.assets.findByTag("level-1", "level-2"); * // returns all assets that tagged by `level-1` OR `level-2` * @example * var assets = app.assets.findByTag(["level-1", "monster"]); * // returns all assets that tagged by `level-1` AND `monster` * @example * var 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`) * @param query - Name of a tag or array of tags. * @returns A list of all Assets matched query. */ findByTag(...query: any[]): Asset[]; /** * Return all Assets that satisfy filter callback. * @example * var assets = app.assets.filter(function (asset) { * return asset.name.indexOf('monster') !== -1; * }); * console.log("Found " + assets.length + " assets, where names contains 'monster'"); * @param callback - The callback function that is used to filter assets, return `true` to include asset to result list. * @returns A list of all Assets found. */ filter(callback: callbacks.FilterAsset): Asset[]; /** * Return the first Asset with the specified name and type found in the registry. * @example * var asset = app.assets.find("myTextureAsset", "texture"); * @param name - The name of the Asset to find. * @param [type] - The type of the Asset to find. * @returns A single Asset or null if no Asset is found. */ find(name: string, type?: string): Asset; /** * A URL prefix that will be added to all asset loading requests. */ prefix: string; } /** * Create a new Asset record. Generally, Assets are created in the loading process and you won't need to create them by hand. * @example * var file = { * filename: "filename.txt", * url: "/example/filename.txt" * }; * @example * var asset = new pc.Asset("a texture", "texture", { * url: "http://example.com/my/assets/here/texture.png" * }); * @property name - The name of the asset * @property id - The asset id * @property type - The type of the asset. One of ["animation", "audio", "binary", "container", "cubemap", "css", "font", "json", "html", "material", "model", "script", "shader", "sprite", "template", "text", "texture"] * @property tags - Interface for tagging. Allows to find assets by tags using {@link AssetRegistry#findByTag} method. * @property file - The file details or null if no file * @property [file.url] - The URL of the resource file that contains the asset data * @property [file.filename] - The filename of the resource file or null if no filename was set (e.g from using {@link AssetRegistry#loadFromUrl}) * @property [file.size] - The size of the resource file or null if no size was set (e.g from using {@link AssetRegistry#loadFromUrl}) * @property [file.hash] - The MD5 hash of the resource file data and the Asset data field or null if hash was set (e.g from using {@link AssetRegistry#loadFromUrl}) * @property [file.contents] - Optional file contents. This is faster than wrapping the data * in a (base64 encoded) blob. Currently only used by container assets. * @property [data] - Optional JSON data that contains either the complete resource data. (e.g. in the case of a material) or additional data (e.g. in the case of a model it contains mappings from mesh to material) * @property [options] - Optional JSON data that contains the asset handler options. * @property resource - A reference to the resource when the asset is loaded. e.g. a {@link Texture} or a {@link Model} * @property resources - A reference to the resources of the asset when it's loaded. An asset can hold more runtime resources than one e.g. cubemaps * @property preload - If true the asset will be loaded during the preload phase of application set up. * @property loaded - True if the resource is loaded. e.g. if asset.resource is not null * @property loading - True if the resource is currently being loaded * @property registry - The asset registry that this Asset belongs to * @param name - A non-unique but human-readable name which can be later used to retrieve the asset. * @param type - Type of asset. One of ["animation", "audio", "binary", "container", cubemap", "css", "font", "json", "html", "material", "model", "script", "shader", "sprite", "template", text", "texture"] * @param [file] - 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. * @param [data] - JSON object 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) * @param [options] - The asset handler options. For container options see {@link ContainerHandler} * @param [options.crossOrigin] - For use with texture resources. For browser-supported image formats only, enable cross origin. */ export class Asset extends EventHandler { constructor(name: string, type: string, file?: any, data?: any, options?: { crossOrigin?: boolean; }); /** * Return the URL required to fetch the file for this asset. * @example * var assets = app.assets.find("My Image", "texture"); * var img = "&lt;img src='" + assets[0].getFileUrl() + "'&gt;"; * @returns The URL. */ getFileUrl(): string; /** * 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. * @example * var asset = app.assets.find("My Asset"); * asset.ready(function (asset) { * // asset loaded * }); * app.assets.load(asset); * @param callback - The function called when the asset is ready. Passed the (asset) arguments. * @param [scope] - Scope object to use when calling the callback. */ ready(callback: callbacks.AssetReady, scope?: any): void; /** * Destroys the associated resource and marks asset as unloaded. * @example * var asset = app.assets.find("My Asset"); * asset.unload(); * // asset.resource is null */ unload(): void; /** * The name of the asset */ name: string; /** * The asset id */ id: number; /** * The type of the asset. One of ["animation", "audio", "binary", "container", "cubemap", "css", "font", "json", "html", "material", "model", "script", "shader", "sprite", "template", "text", "texture"] */ type: "animation" | "audio" | "binary" | "container" | "cubemap" | "css" | "font" | "json" | "html" | "material" | "model" | "script" | "shader" | "sprite" | "template" | "text" | "texture"; /** * Interface for tagging. Allows to find assets by tags using {@link AssetRegistry#findByTag} method. */ tags: Tags; /** * The file details or null if no file */ file: { url?: string; filename?: string; size?: number; hash?: string; contents?: ArrayBuffer; }; /** * Optional JSON data that contains either the complete resource data. (e.g. in the case of a material) or additional data (e.g. in the case of a model it contains mappings from mesh to material) */ data?: any; /** * Optional JSON data that contains the asset handler options. */ options?: any; /** * A reference to the resource when the asset is loaded. e.g. a {@link Texture} or a {@link Model} */ resource: any; /** * A reference to the resources of the asset when it's loaded. An asset can hold more runtime resources than one e.g. cubemaps */ resources: any[]; /** * If true the asset will be loaded during the preload phase of application set up. */ preload: boolean; /** * True if the resource is loaded. e.g. if asset.resource is not null */ loaded: boolean; /** * True if the resource is currently being loaded */ loading: boolean; /** * The asset registry that this Asset belongs to */ registry: AssetRegistry; } /** * Asset type name for animation. */ export const ASSET_ANIMATION: string; /** * Asset type name for audio. */ export const ASSET_AUDIO: string; /** * Asset type name for image. */ export const ASSET_IMAGE: string; /** * Asset type name for json. */ export const ASSET_JSON: string; /** * Asset type name for model. */ export const ASSET_MODEL: string; /** * Asset type name for material. */ export const ASSET_MATERIAL: string; /** * Asset type name for text. */ export const ASSET_TEXT: string; /** * Asset type name for texture. */ export const ASSET_TEXTURE: string; /** * Asset type name for cubemap. */ export const ASSET_CUBEMAP: string; /** * Asset type name for shader. */ export const ASSET_SHADER: string; /** * Asset type name for CSS. */ export const ASSET_CSS: string; /** * Asset type name for HTML. */ export const ASSET_HTML: string; /** * Asset type name for script. */ export const ASSET_SCRIPT: string; /** * Asset type name for a container. */ export const ASSET_CONTAINER: string; /** * Linear distance model. */ export const DISTANCE_LINEAR: string; /** * Inverse distance model. */ export const DISTANCE_INVERSE: string; /** * Exponential distance model. */ export const DISTANCE_EXPONENTIAL: string; /** * Namespace for callback definitions. */ export namespace callbacks { /** * Callback used by {@link EventHandler} functions. Note the callback is limited to 8 arguments. * @param [arg1] - First argument that is passed from caller. * @param [arg2] - Second argument that is passed from caller. * @param [arg3] - Third argument that is passed from caller. * @param [arg4] - Fourth argument that is passed from caller. * @param [arg5] - Fifth argument that is passed from caller. * @param [arg6] - Sixth argument that is passed from caller. * @param [arg7] - Seventh argument that is passed from caller. * @param [arg8] - Eighth argument that is passed from caller. */ type HandleEvent = (arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any) => void; /** * Callback used by {@link AssetRegistry#loadFromUrl} and called when an asset is loaded (or an error occurs). * @param err - The error message is null if no errors were encountered. * @param [asset] - The loaded asset if no errors were encountered. */ type LoadAsset = (err: string | null, asset?: Asset) => void; /** * Callback used by {@link AssetRegistry#filter} to filter assets. * @param asset - The current asset to filter. */ type FilterAsset = (asset: Asset) => boolean; /** * Callback used by {@link Asset#ready} and called when an asset is ready. * @param asset - The ready asset. */ type AssetReady = (asset: Asset) => void; /** * Callback used by {@link Application#configure} when configuration file is loaded and parsed (or an error occurs). * @param err - The error message in the case where the loading or parsing fails. */ type ConfigureApp = (err: string | null) => void; /** * Callback used by {@link Application#preload} when all assets (marked as 'preload') are loaded. */ type PreloadApp = () => void; /** * Callback used by {@link SceneRegistry.loadSceneData}. * @param err - The error message in the case where the loading or parsing fails. * @param [sceneItem] - The scene registry item if no errors were encountered. */ type LoadSceneData = (err: string | null, sceneItem?: SceneRegistryItem) => void; /** * Callback used by {@link SceneRegistry.loadSceneData}. * @param err - The error message in the case where the loading or parsing fails. * @param [sceneItem] - The scene registry item if no errors were encountered. */ type UnloadSceneData = (err: string | null, sceneItem?: SceneRegistryItem) => void; /** * Callback used by {@link SceneRegistry#loadSceneHierarchy}. * @param err - The error message in the case where the loading or parsing fails. * @param [entity] - The loaded root entity if no errors were encountered. */ type LoadHierarchy = (err: string | null, entity?: Entity) => void; /** * Callback used by {@link SceneRegistry#loadSceneSettings}. * @param err - The error message in the case where the loading or parsing fails. */ type LoadSettings = (err: string | null) => void; /** * Callback used by {@link SceneRegistry#loadScene}. * @param err - The error message in the case where the loading or parsing fails. * @param [entity] - The loaded root entity if no errors were encountered. */ type LoadScene = (err: string | null, entity?: Entity) => void; /** * Callback used by {@link CameraComponent#calculateTransform} and {@link CameraComponent#calculateProjection}. * @param transformMatrix - Output of the function. * @param view - Type of view. Can be {@link VIEW_CENTER}, {@link VIEW_LEFT} or {@link VIEW_RIGHT}. Left and right are only used in stereo rendering. */ type CalculateMatrix = (transformMatrix: Mat4, view: number) => void; /** * Callback used by {@link Layer} to calculate the "sort distance" for a {@link MeshInstance}, which determines its place in the render order. * @param meshInstance - The mesh instance. * @param cameraPosition - The position of the camera. * @param cameraForward - The forward vector of the camera. */ type CalculateSortDistance = (meshInstance: MeshInstance, cameraPosition: Vec3, cameraForward: Vec3) => void; /** * Callback used by {@link CameraComponent#enterVr} and {@link CameraComponent#exitVr}. * @param err - On success it is null on failure it is the error message. */ type VrCamera = (err: string | null) => void; /** * Callback used by {@link script.createLoadingScreen}. * @param app - The application. */ type CreateScreen = (app: Application) => void; /** * Callback used by {@link Mouse#enablePointerLock} and {@link Application#disablePointerLock}. */ type LockMouse = () => void; /** * Callback used by {@link Http#get}, {@link Http#post}, {@link Http#put}, {@link Http#del}, and {@link Http#request}. * @param err - The error code, message, or exception in the case where the request fails. * @param [response] - The response data if no errors were encountered. (format depends on response type: text, Object, ArrayBuffer, XML). */ type HttpResponse = (err: number | string | Error | null, response?: any) => void; /** * Callback used by {@link ResourceHandler#load} when a resource is loaded (or an error occurs). * @param err - The error message in the case where the load fails. * @param [response] - The raw data that has been successfully loaded. */ type ResourceHandler = (err: string | null, response?: any) => void; /** * Callback used by {@link ResourceLoader#load} when a resource is loaded (or an error occurs). * @param err - The error message in the case where the load fails. * @param [resource] - The resource that has been successfully loaded. */ type ResourceLoader = (err: string | null, resource?: any) => void; /** * Callback used by {@link ModelHandler#addParser} to decide on which parser to use. * @param url - The resource url. * @param data - The raw model data. */ type AddParser = (url: string, data: any) => boolean; /** * Callback used by {@link GraphNode#find} and {@link GraphNode#findOne} to search through a graph node and all of its descendants. * @param node - The current graph node. */ type FindNode = (node: GraphNode) => boolean; /** * Callback used by {@link GraphNode#forEach} to iterate through a graph node and all of its descendants. * @param node - The current graph node. */ type ForEach = (node: GraphNode) => void; /** * Callback used by {@link StandardMaterial#onUpdateShader}. * @param options - An object with shader generator settings (based on current material and scene properties), that you can change and then return. * Properties of the object passed into this function are documented in {@link StandardMaterial#onUpdateShader}. */ type UpdateShader = (options: any) => any; /** * Callback used by {@link XrManager#endXr} and {@link XrManager#startXr}. * @param err - The Error object or null if operation was successfull. */ type XrError = (err: Error | null) => void; /** * Callback used by {@link XrHitTest#start} and {@link XrHitTest#startForInputSource}. * @param err - The Error object if failed to create hit test source or null. * @param hitTestSource - Object that provides access to hit results against real world geometry. */ type XrHitTestStart = (err: Error | null, hitTestSource: XrHitTestSource | null) => void; } /** * Root namespace for the PlayCanvas Engine. */ export namespace pc { } /** * Create a new event handler. * @example * var obj = new EventHandlerSubclass(); * * // subscribe to an event * obj.on('hello', function (str) { * console.log('event hello is fired', str); * }); * * // fire event * obj.fire('hello', 'world'); */ export class EventHandler { /** * Attach an event handler to an event. * @example * obj.on('test', function (a, b) { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console * @param name - Name of the event to bind the callback to. * @param callback - Function that is called when event is fired. Note the callback is limited to 8 arguments. * @param [scope] - Object to use as 'this' when the event is fired, defaults to current this. * @returns Self for chaining. */ on(name: string, callback: callbacks.HandleEvent, 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. * @example * var handler = function () { * }; * obj.on('test', handler); * * obj.off(); // Removes all events * obj.off('test'); // Removes all events called 'test' * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this * @param [name] - Name of the event to unbind. * @param [callback] - Function to be unbound. * @param [scope] - Scope that was used as the this when the event is fired. * @returns Self for chaining. */ off(name?: string, callback?: callbacks.HandleEvent, scope?: any): EventHandler; /** * Fire an event, all additional arguments are passed on to the event listener. * @example * obj.fire('test', 'This is the message'); * @param name - Name of event to fire. * @param [arg1] - First argument that is passed to the event handler. * @param [arg2] - Second argument that is passed to the event handler. * @param [arg3] - Third argument that is passed to the event handler. * @param [arg4] - Fourth argument that is passed to the event handler. * @param [arg5] - Fifth argument that is passed to the event handler. * @param [arg6] - Sixth argument that is passed to the event handler. * @param [arg7] - Seventh argument that is passed to the event handler. * @param [arg8] - Eighth argument that is passed to the event handler. * @returns Self for chaining. */ fire(name: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler; /** * Attach an event handler to an event. This handler will be removed after being fired once. * @example * obj.once('test', function (a, b) { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled * @param name - Name of the event to bind the callback to. * @param callback - Function that is called when event is fired. Note the callback is limited to 8 arguments. * @param [scope] - Object to use as 'this' when the event is fired, defaults to current this. * @returns Self for chaining. */ once(name: string, callback: callbacks.HandleEvent, scope?: any): EventHandler; /** * Test if there are any handlers bound to an event name. * @example * obj.on('test', function () { }); // bind an event to 'test' * obj.hasEvent('test'); // returns true * obj.hasEvent('hello'); // returns false * @param name - The name of the event to test. * @returns True if the object has handlers bound to the specified event name. */ hasEvent(name: string): boolean; } /** * 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. */ export namespace guid { /** * Create an RFC4122 version 4 compliant GUID. * @returns A new GUID. */ function create(): string; } /** * File path API. */ export namespace path { /** * The character that separates path segments. */ const delimiter: string; /** * Join two or more sections of file path together, inserting a * delimiter if needed. * @example * var path = pc.path.join('foo', 'bar'); * console.log(path); // Prints 'foo/bar' * @example * var path = pc.path.join('alpha', 'beta', 'gamma'); * console.log(path); // Prints 'alpha/beta/gamma' * @param section - Section of path to join. 2 or more can be * provided as parameters. * @returns The joined file path. */ function join(...section: string[]): string; /** * Normalize the path by removing '.' and '..' instances. * @param pathname - The path to normalize. * @returns The normalized path. */ function normalize(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. * @param pathname - The path to split. * @returns The split path which is an array of two strings, the path and the filename. */ function split(pathname: string): string[]; /** * Return the basename of the path. That is the second element of the pair returned by * passing path into {@link path.split}. * @example * pc.path.getBasename("/path/to/file.txt"); // returns "file.txt" * pc.path.getBasename("/path/to/dir"); // returns "dir" * @param pathname - The path to process. * @returns The basename. */ function getBasename(pathname: string): string; /** * Get the directory name from the path. This is everything up to the final instance of {@link path.delimiter}. * @param pathname - The path to get the directory from. * @returns The directory part of the path. */ function getDirectory(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. * @example * pc.path.getExtension("/path/to/file.txt"); // returns ".txt" * pc.path.getExtension("/path/to/file.jpg"); // returns ".jpg" * pc.path.getExtension("/path/to/file.txt?function=getExtension"); // returns ".txt" * @param pathname - The path to process. * @returns The extension. */ function getExtension(pathname: string): string; /** * Check if a string s is relative path. * @example * pc.path.isRelativePath("file.txt"); // returns true * pc.path.isRelativePath("path/to/file.txt"); // returns true * pc.path.isRelativePath("./path/to/file.txt"); // returns true * pc.path.isRelativePath("../path/to/file.jpg"); // returns true * pc.path.isRelativePath("/path/to/file.jpg"); // returns false * pc.path.isRelativePath("http://path/to/file.jpg"); // returns false * @param pathname - The path to process. * @returns True if s doesn't start with slash and doesn't include colon and double slash. */ function isRelativePath(pathname: string): boolean; /** * Return the path without file name. If path is relative path, start with period. * @example * pc.path.extractPath("path/to/file.txt"); // returns "./path/to" * pc.path.extractPath("./path/to/file.txt"); // returns "./path/to" * pc.path.extractPath("../path/to/file.txt"); // returns "../path/to" * pc.path.extractPath("/path/to/file.txt"); // returns "/path/to" * @param pathname - The full path to process. * @returns The path without a last element from list split by slash. */ function extractPath(pathname: string): string; } /** * Global namespace that stores flags regarding platform environment and features support. * @example * if (pc.platform.touch) { * // touch is supported * } */ export namespace platform { /** * Is it a desktop or laptop device. */ const desktop: boolean; /** * Is it a mobile or tablet device. */ const mobile: boolean; /** * If it is iOS. */ const ios: boolean; /** * If it is Android. */ const android: boolean; /** * If it is Windows. */ const windows: boolean; /** * If it is Xbox. */ const xbox: boolean; /** * If platform supports gamepads. */ const gamepads: boolean; /** * If platform supports touch input. */ const touch: boolean; /** * If the platform supports Web Workers. */ const workers: boolean; } /** * Extended String API. */ export namespace string { /** * All lowercase letters. */ const ASCII_LOWERCASE: string; /** * All uppercase letters. */ const ASCII_UPPERCASE: string; /** * All ASCII letters. */ const ASCII_LETTERS: string; /** * Return a string with {n} replaced with the n-th argument. * @example * var s = pc.string.format("Hello {0}", "world"); * console.log(s); // Prints "Hello world" * @param s - The string to format. * @param [arguments] - All other arguments are substituted into the string. * @returns The formatted string. */ function format(s: string, arguments?: any): string; /** * Convert a string value to a boolean. In non-strict mode (the default), 'true' is converted to true, all other values * are converted to false. In strict mode, 'true' is converted to true, 'false' is converted to false, all other values will throw * an Exception. * @param s - The string to convert. * @param [strict] - In strict mode an Exception is thrown if s is not an accepted string value. Defaults to false. * @returns The converted value. */ function toBool(s: string, strict?: boolean): boolean; /** * Get the code point number for a character in a string. Polyfill for * [`codePointAt`]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt}. * @param string - The string to get the code point from. * @param [i] - The index in the string. * @returns The code point value for the character in the string. */ function getCodePoint(string: string, i?: number): number; /** * Gets an array of all code points in a string. * @param string - The string to get code points from. * @returns The code points in the string. */ function getCodePoints(string: string): number[]; /** * 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 * {@link https://mathiasbynens.be/notes/javascript-unicode here} for more info. * @param string - The string to break into symbols. * @returns The symbols in the string. */ function getSymbols(string: string): string[]; /** * Get the string for a given code point or set of code points. Polyfill for * [`fromCodePoint`]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint}. * @param args - The code points to convert to a string. * @returns The converted string. */ function fromCodePoint(...args: number[]): string; } /** * Create an instance of a Tags. * @param [parent] - Parent object who tags belong to. * Note: Tags are automatically available on {@link Entity} and {@link Asset} as `tags` field. */ export class Tags extends EventHandler { constructor(parent?: any); /** * Add a tag, duplicates are ignored. Can be array or comma separated arguments for multiple tags. * @example * tags.add('level-1'); * @example * tags.add('ui', 'settings'); * @example * tags.add(['level-2', 'mob']); * @param name - Name of a tag, or array of tags. * @returns True if any tag were added. */ add(...name: any[]): boolean; /** * Remove tag. * @example * tags.remove('level-1'); * @example * tags.remove('ui', 'settings'); * @example * tags.remove(['level-2', 'mob']); * @param name - Name of a tag or array of tags. * @returns True if any tag were removed. */ remove(...name: any[]): boolean; /** * Remove all tags. * @example * tags.clear(); */ clear(): void; /** * 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. * @example * tags.has('player'); // player * @example * tags.has('mob', 'player'); // player OR mob * @example * tags.has(['level-1', 'mob']); // monster AND level-1 * @example * tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels) * @param query - Name of a tag or array of tags. * @returns True if filters are satisfied. */ has(...query: any[]): boolean; /** * Returns immutable array of tags. * @returns Copy of tags array. */ list(): string[]; /** * Number of tags in set. */ readonly size: number; } /** * Represents the resource of a font asset. * @property intensity - The font intensity. * @property textures - The font textures. * @param textures - The font textures. * @param data - The font data. */ export class Font { constructor(textures: Texture[], data: any); /** * The font intensity. */ intensity: number; /** * The font textures. */ textures: Texture[]; } /** * Create a new Application. * @example * // Engine-only example: create the application manually * var app = new pc.Application(canvas, options); * * // Start the application's main loop * app.start(); * @param canvas - The canvas element. * @param [options.elementInput] - Input handler for {@link ElementComponent}s. * @param [options.keyboard] - Keyboard handler for input. * @param [options.mouse] - Mouse handler for input. * @param [options.touch] - TouchDevice handler for input. * @param [options.gamepads] - Gamepad handler for input. * @param [options.scriptPrefix] - Prefix to apply to script urls before loading. * @param [options.assetPrefix] - Prefix to apply to asset urls before loading. * @param [options.graphicsDeviceOptions] - Options object that is passed into the {@link GraphicsDevice} constructor. * @param [options.scriptsOrder] - Scripts in order of loading first. */ export class Application extends EventHandler { constructor(canvas: Element, options: { elementInput?: ElementInput; keyboard?: Keyboard; mouse?: Mouse; touch?: TouchDevice; gamepads?: GamePads; scriptPrefix?: string; assetPrefix?: string; graphicsDeviceOptions?: any; scriptsOrder?: string[]; }); /** * The scene managed by the application. * @example * // Set the tone mapping property of the application's scene * this.app.scene.toneMapping = pc.TONEMAP_FILMIC; */ scene: Scene; /** * Scales the global time delta. Defaults to 1. * @example * // Set the app to run at half speed * this.app.timeScale = 0.5; */ timeScale: number; /** * Clamps per-frame delta time to an upper bound. Useful since returning from a tab * deactivation can generate huge values for dt, which can adversely affect game state. Defaults * to 0.1 (seconds). * @example * // Don't clamp inter-frame times of 200ms or less * this.app.maxDeltaTime = 0.2; */ maxDeltaTime: number; /** * The scene registry managed by the application. * @example * // Search the scene registry for a item with the name 'racetrack1' * var sceneItem = this.app.scenes.find('racetrack1'); * * // Load the scene using the item's url * this.app.scenes.loadScene(sceneItem.url); */ scenes: SceneRegistry; /** * The asset registry managed by the application. * @example * // Search the asset registry for all assets with the tag 'vehicle' * var vehicleAssets = this.app.assets.findByTag('vehicle'); */ assets: AssetRegistry; /** * The graphics device used by the application. */ graphicsDevice: GraphicsDevice; /** * The application's component system registry. The Application * constructor adds the following component systems to its component system registry: * * * anim ({@link AnimComponentSystem}) * * animation ({@link AnimationComponentSystem}) * * audiolistener ({@link AudioListenerComponentSystem}) * * button ({@link ButtonComponentSystem}) * * camera ({@link CameraComponentSystem}) * * collision ({@link CollisionComponentSystem}) * * element ({@link ElementComponentSystem}) * * layoutchild ({@link LayoutChildComponentSystem}) * * layoutgroup ({@link LayoutGroupComponentSystem}) * * light ({@link LightComponentSystem}) * * model ({@link ModelComponentSystem}) * * particlesystem ({@link ParticleSystemComponentSystem}) * * rigidbody ({@link RigidBodyComponentSystem}) * * render ({@link RenderComponentSystem}) * * screen ({@link ScreenComponentSystem}) * * script ({@link ScriptComponentSystem}) * * scrollbar ({@link ScrollbarComponentSystem}) * * scrollview ({@link ScrollViewComponentSystem}) * * sound ({@link SoundComponentSystem}) * * sprite ({@link SpriteComponentSystem}) * @example * // Set global gravity to zero * this.app.systems.rigidbody.gravity.set(0, 0, 0); * @example * // Set the global sound volume to 50% * this.app.systems.sound.volume = 0.5; */ systems: ComponentSystemRegistry; /** * The XR Manager that provides ability to start VR/AR sessions. * @example * // check if VR is available * if (app.xr.isAvailable(pc.XRTYPE_VR)) { * // VR is available * } */ xr: XrManager; /** * The run-time lightmapper. */ lightmapper: Lightmapper; /** * The resource loader. */ loader: ResourceLoader; /** * The root entity of the application. * @example * // Return the first entity called 'Camera' in a depth-first search of the scene hierarchy * var camera = this.app.root.findByName('Camera'); */ root: Entity; /** * The keyboard device. */ keyboard: Keyboard; /** * The mouse device. */ mouse: Mouse; /** * Used to get touch events input. */ touch: TouchDevice; /** * Used to access GamePad input. */ gamepads: GamePads; /** * Used to handle input for {@link ElementComponent}s. */ elementInput: ElementInput; /** * The application's script registry. */ scripts: ScriptRegistry; /** * The application's batch manager. The batch manager is used to * m