This demo does not test Reddit installation, Redis storage, live
community activity or comment permissions. The existing game canvas uses
pointer controls; the date selector and local summary are native HTML.
Source and bundled licenses
Source commit: ce7cc1bf961c490f2d37fdff94dc2d31b1fd5802
BSD 3-Clause License
Copyright (c) 2025, Reddit Inc.
Copyright (c) 2026, Chunyu Dai
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Bundled dependencies
# Licenses
The app bundles dependencies which contain the following licenses:
## phaser - 4.2.0 (MIT)
The MIT License (MIT)
Copyright (c) 2026 Richard Davey, Phaser Studio Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
EventEmitter3 embedded in Phaser
The MIT License (MIT)
Copyright (c) 2014 Arnout Kazemier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Matter.js embedded in Phaser
/**
* The MIT License (MIT)
*
* Copyright (c) Liam Brummitt and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
Supplementary notices for credited upstream sources
These source-specific notices supplement the exact packaged credits below; they do not relabel all Phaser adaptations with one license.
schteppe/poly-decomp.js
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/LICENSE
The MIT License (MIT)
Copyright (c) 2013 Stefan Hedman
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Two-Screen/stable
https://github.com/Two-Screen/stable/blob/fff2be6088a96c9613e3799cb966c912c6d6fcb7/README.md
#### License
Copyright (C) 2018 Angry Bytes and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
stegu/psrdnoise
https://github.com/stegu/psrdnoise/blob/419175a270862ce7ae692038fafafb42ec0427e9/src/psrdnoise2.glsl
//
// psrdnoise2.glsl
//
// Authors: Stefan Gustavson (stefan.gustavson@gmail.com)
// and Ian McEwan (ijm567@gmail.com)
// Version 2021-12-02, published under the MIT license (see below)
//
// Copyright (c) 2021 Stefan Gustavson and Ian McEwan.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
mattdesl/line-circle-collision
https://github.com/mattdesl/line-circle-collision/blob/cf424adfebfb417a50b06b63ebaff2993fa8d45a/LICENSE.md
The MIT License (MIT)
Copyright (c) 2014 Matt DesLauriers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
niklasvh/base64-arraybuffer
https://github.com/niklasvh/base64-arraybuffer/blob/5339d8f0abed59c893e87116a785bf52acdc17aa/LICENSE
Copyright (c) 2012 Niklas von Hertzen
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
toji/gl-matrix
https://github.com/toji/gl-matrix/blob/6f96d577ee0217b5cfce334e2cad92a6ac3572d2/LICENSE.md
Copyright (c) 2015-2025, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
mrdoob/three.js
https://github.com/mrdoob/three.js/blob/3efcf0f0a3d8ae5107742cba2f7de81d811f130e/LICENSE
The MIT License
Copyright © 2010-2026 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
mourner/rbush
https://github.com/mourner/rbush/blob/e59712716a84dda2e31f9b471b32faa178d8056f/LICENSE
MIT License
Copyright (c) 2024 Volodymyr Agafonkin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
mourner/quickselect
https://github.com/mourner/quickselect/blob/0711310d28fe5f8a5ca75c721626d8e49feb9ccb/LICENSE
ISC License
Copyright (c) 2024, Vladimir Agafonkin
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
mattdesl/klasse
https://github.com/mattdesl/klasse/blob/c4cbe8846b6aa30d41ce2ca44589d00b4abe8230/package.json
klasse 1.0.9 declares BSD-2-Clause. Author: Matt DesLauriers.
BSD 2-Clause License
Copyright (c) Matt DesLauriers
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
mattdesl/vecmath
https://github.com/mattdesl/vecmath/blob/86bcdc2d1d93e58e664df28f72a0bd77dd4a71ad/readme.md
vecmath by Matt DesLauriers. Upstream declares MIT and credits its gl-matrix codebase (Brandon Jones and Colin MacKenzie IV). The gl-matrix full MIT notice is retained above; the exact Phaser adaptation credits are retained below.
Gavin Kistner reuse notice
https://phrogz.net/js/_ReuseLicense.txt
Copyright (c), Gavin Kistner (!@phrogz.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1) Redistributions of source code must retain the above copyright
notice verbatim, and this list of conditions and the following
disclaimer, either verbatim or through the inclusion of this
file's url.
2) Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3) You must include in the source code a description of any
modifications made to the code (including bugfixes).
Neither the names of Gavin Kistner, Refinery Inc., Anark Inc.,
NVIDIA Corporation, nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Retained copyright, license and source-credit comments from pinned Phaser 4.2.0
The standalone runtime excludes unused requestVideoFrame polyfill module 63595; other video APIs are not a supported demo feature.
/**
* @author Benjamin D. Richards <benjamindrichards@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @author samme
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Takes an array of Game Objects, or any objects that have public `x` and `y` properties,
* and positions them in a grid layout based on the configuration provided.
*
* The grid is defined by a `width` (number of columns) and/or `height` (number of rows).
* Each cell in the grid has a size defined by `cellWidth` and `cellHeight`, in pixels.
* Items are placed into cells starting from the top-left origin (`x`, `y`) and filling
* left-to-right, top-to-bottom by default. If only `width` is set to -1, items are laid
* out in a single horizontal row. If only `height` is set to -1, items are laid out in a
* single vertical column. When both `width` and `height` are set, the grid fills
* row-by-row, stopping early if the grid is full before all items have been placed.
*
* The `position` option controls how each item is aligned within its cell, using one of
* the `Phaser.Display.Align` constants such as `CENTER` or `TOP_LEFT`.
*
* @function Phaser.Actions.GridAlign
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - The array of items to be updated by this action.
* @param {Phaser.Types.Actions.GridAlignConfig} options - The GridAlign Configuration object.
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of objects that were passed to this Action.
*/
/**
* Iterates over all items in the given array and calls `setInteractive` on each one, applying the same hit area shape and callback to every Game Object in the array.
*
* @see {@link Phaser.GameObjects.GameObject#setInteractive}
*
* @function Phaser.Actions.SetHitArea
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action.
* @param {(Phaser.Types.Input.InputConfiguration|any)} [hitArea] - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not given it will try to create a Rectangle based on the texture frame.
* @param {Phaser.Types.Input.HitAreaCallback} [hitAreaCallback] - The callback that determines if the pointer is within the Hit Area shape or not. If you provide a shape you must also provide a callback.
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action.
*/
/**
* Takes an array of Game Objects and distributes values across the specified property using
* smoothstep interpolation. Each item in the array is assigned a smoothstep-interpolated value
* based on its position, creating a smooth ease-in/ease-out transition across the items.
*
* Smoothstep is a sigmoid-like interpolation and clamping function.
*
* The function depends on three parameters, the input x, the "left edge"
* and the "right edge", with the left edge being assumed smaller than the right edge.
*
* The function receives a real number x as an argument and returns 0 if x is less than
* or equal to the left edge, 1 if x is greater than or equal to the right edge, and smoothly
* interpolates, using a Hermite polynomial, between 0 and 1 otherwise. The slope of the
* smoothstep function is zero at both edges.
*
* This is convenient for creating a sequence of transitions using smoothstep to interpolate
* each segment as an alternative to using more sophisticated or expensive interpolation techniques.
*
* @function Phaser.Actions.SmoothStep
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action.
* @param {string} property - The property of the Game Object to interpolate.
* @param {number} min - The left edge of the smoothstep. This value should be smaller than `max`.
* @param {number} max - The right edge of the smoothstep. This value should be larger than `min`.
* @param {boolean} [inc=false] - Should the property value be incremented (`true`) or set (`false`)?
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action.
*/
/**
* Takes an array of Game Objects and distributes values across the specified property using
* smootherstep interpolation. Each item in the array is assigned a smootherstep-interpolated
* value based on its position, creating an even smoother transition than SmoothStep.
*
* Smootherstep is a sigmoid-like interpolation and clamping function.
*
* The function depends on three parameters, the input x, the "left edge" and the "right edge", with the left edge being assumed smaller than the right edge. The function receives a real number x as an argument and returns 0 if x is less than or equal to the left edge, 1 if x is greater than or equal to the right edge, and smoothly interpolates, using a Hermite polynomial, between 0 and 1 otherwise. The slope of the smootherstep function is zero at both edges. This is convenient for creating a sequence of transitions using smootherstep to interpolate each segment as an alternative to using more sophisticated or expensive interpolation techniques.
*
* @function Phaser.Actions.SmootherStep
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action.
* @param {string} property - The property of the Game Object to interpolate.
* @param {number} min - The minimum interpolation value.
* @param {number} max - The maximum interpolation value.
* @param {boolean} [inc=false] - If `true`, the values are incremented. If `false` (default), the values are set.
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author samme <samme.npm@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Creates AnimationFrame instances based on the given frame data.
*
* @method Phaser.Animations.Animation#getFrames
* @since 3.0.0
*
* @param {Phaser.Textures.TextureManager} textureManager - A reference to the global Texture Manager.
* @param {(string|Phaser.Types.Animations.AnimationFrame[])} frames - Either a string, in which case it will use all frames from a texture with the matching key, or an array of Animation Frame configuration objects.
* @param {string} [defaultTextureKey] - The key to use if no key is set in the frame configuration object.
*
* @return {Phaser.Animations.AnimationFrame[]} An array of newly created AnimationFrame instances.
*/
/**
* Create one, or more animations from a loaded Aseprite JSON file.
*
* Aseprite is a powerful animated sprite editor and pixel art tool.
*
* You can find more details at https://www.aseprite.org/
*
* To export a compatible JSON file in Aseprite, please do the following:
*
* 1. Go to "File - Export Sprite Sheet"
*
* 2. On the **Layout** tab:
* 2a. Set the "Sheet type" to "Packed"
* 2b. Set the "Constraints" to "None"
* 2c. Check the "Merge Duplicates" checkbox
*
* 3. On the **Sprite** tab:
* 3a. Set "Layers" to "Visible layers"
* 3b. Set "Frames" to "All frames", unless you only wish to export a sub-set of tags
*
* 4. On the **Borders** tab:
* 4a. Check the "Trim Sprite" and "Trim Cells" options
* 4b. Ensure "Border Padding", "Spacing" and "Inner Padding" are all > 0 (1 is usually enough)
*
* 5. On the **Output** tab:
* 5a. Check "Output File", give your image a name and make sure you choose "png files" as the file type
* 5b. Check "JSON Data" and give your json file a name
* 5c. The JSON Data type can be either a Hash or Array, Phaser doesn't mind.
* 5d. Make sure "Tags" is checked in the Meta options
* 5e. In the "Item Filename" input box, make sure it says just "{frame}" and nothing more.
*
* 6. Click export
*
* This was tested with Aseprite 1.2.25.
*
* This will export a png and json file which you can load using the Aseprite Loader, i.e.:
*
* ```javascript
* function preload ()
* {
* this.load.path = 'assets/animations/aseprite/';
* this.load.aseprite('paladin', 'paladin.png', 'paladin.json');
* }
* ```
*
* Once loaded, you can call this method from within a Scene with the 'atlas' key:
*
* ```javascript
* this.anims.createFromAseprite('paladin');
* ```
*
* Any animations defined in the JSON will now be available to use in Phaser and you play them
* via their Tag name. For example, if you have an animation called 'War Cry' on your Aseprite timeline,
* you can play it in Phaser using that Tag name:
*
* ```javascript
* this.add.sprite(400, 300).play('War Cry');
* ```
*
* When calling this method you can optionally provide an array of tag names, and only those animations
* will be created. For example:
*
* ```javascript
* this.anims.createFromAseprite('paladin', [ 'step', 'War Cry', 'Magnum Break' ]);
* ```
*
* This will only create the 3 animations defined. Note that the tag names are case-sensitive.
*
* @method Phaser.Animations.AnimationManager#createFromAseprite
* @since 3.50.0
*
* @param {string} key - The key of the loaded Aseprite atlas. It must have been loaded prior to calling this method.
* @param {string[]} [tags] - An array of Tag names. If provided, only animations found in this array will be created.
* @param {(Phaser.Animations.AnimationManager|Phaser.GameObjects.GameObject)} [target] - Create the animations on this target Sprite. If not given, they will be created globally in this Animation Manager.
*
* @return {Phaser.Animations.Animation[]} An array of Animation instances that were successfully created.
*/
/**
* Removes an Animation from this Animation Manager, based on the given key.
*
* This is a global action. Once an Animation has been removed, no Game Objects
* can carry on using it.
*
* @method Phaser.Animations.AnimationManager#remove
* @fires Phaser.Animations.Events#REMOVE_ANIMATION
* @since 3.0.0
*
* @param {string} key - The key of the animation to remove.
*
* @return {Phaser.Animations.Animation} The Animation instance that was removed from the Animation Manager.
*/
/**
* Returns the Animation data as JavaScript object based on the given key.
* Or, if no key is defined, it will return the data of all animations as array of objects.
*
* @method Phaser.Animations.AnimationManager#toJSON
* @since 3.0.0
*
* @param {string} [key] - The animation to get the JSONAnimation data from. If not provided, all animations are returned as an array.
*
* @return {Phaser.Types.Animations.JSONAnimations} The resulting JSONAnimations formatted object.
*/
/**
* Load the animation based on the key and set-up all of the internal values
* needed for playback to start. If there is no delay, it will also fire the start events.
*
* @method Phaser.Animations.AnimationState#startAnimation
* @fires Phaser.Animations.Events#ANIMATION_START
* @since 3.50.0
*
* @param {(string|Phaser.Types.Animations.PlayAnimationConfig)} key - The string-based key of the animation to play, or a `PlayAnimationConfig` object.
*
* @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component.
*/
/**
* Returns a value between 0 and 1 indicating how far this animation is through, ignoring repeats and yoyos.
*
* The value is based on the current frame and how far that is in the animation, it is not based on
* the duration of the animation.
*
* @method Phaser.Animations.AnimationState#getProgress
* @since 3.4.0
*
* @return {number} The progress of the current animation in frames, between 0 and 1.
*/
/**
* Takes a value between 0 and 1 and uses it to set how far this animation is through playback.
*
* Does not factor in repeats or yoyos, but does handle playing forwards or backwards.
*
* The value is based on the current frame and how far that is in the animation, it is not based on
* the duration of the animation.
*
* @method Phaser.Animations.AnimationState#setProgress
* @since 3.4.0
*
* @param {number} [value=0] - The progress value, between 0 and 1.
*
* @return {Phaser.GameObjects.GameObject} The Game Object that owns this Animation Component.
*/
/**
* Create one, or more animations from a loaded Aseprite JSON file.
*
* Aseprite is a powerful animated sprite editor and pixel art tool.
*
* You can find more details at https://www.aseprite.org/
*
* To export a compatible JSON file in Aseprite, please do the following:
*
* 1. Go to "File - Export Sprite Sheet"
*
* 2. On the **Layout** tab:
* 2a. Set the "Sheet type" to "Packed"
* 2b. Set the "Constraints" to "None"
* 2c. Check the "Merge Duplicates" checkbox
*
* 3. On the **Sprite** tab:
* 3a. Set "Layers" to "Visible layers"
* 3b. Set "Frames" to "All frames", unless you only wish to export a sub-set of tags
*
* 4. On the **Borders** tab:
* 4a. Check the "Trim Sprite" and "Trim Cells" options
* 4b. Ensure "Border Padding", "Spacing" and "Inner Padding" are all > 0 (1 is usually enough)
*
* 5. On the **Output** tab:
* 5a. Check "Output File", give your image a name and make sure you choose "png files" as the file type
* 5b. Check "JSON Data" and give your json file a name
* 5c. The JSON Data type can be either a Hash or Array, Phaser doesn't mind.
* 5d. Make sure "Tags" is checked in the Meta options
* 5e. In the "Item Filename" input box, make sure it says just "{frame}" and nothing more.
*
* 6. Click export
*
* This was tested with Aseprite 1.2.25.
*
* This will export a png and json file which you can load using the Aseprite Loader, i.e.:
*
* ```javascript
* function preload ()
* {
* this.load.path = 'assets/animations/aseprite/';
* this.load.aseprite('paladin', 'paladin.png', 'paladin.json');
* }
* ```
*
* Once loaded, you can call this method on a Sprite with the 'atlas' key:
*
* ```javascript
* const sprite = this.add.sprite(400, 300);
*
* sprite.anims.createFromAseprite('paladin');
* ```
*
* Any animations defined in the JSON will now be available to use on this Sprite and you play them
* via their Tag name. For example, if you have an animation called 'War Cry' on your Aseprite timeline,
* you can play it on the Sprite using that Tag name:
*
* ```javascript
* const sprite = this.add.sprite(400, 300);
*
* sprite.anims.createFromAseprite('paladin');
*
* sprite.play('War Cry');
* ```
*
* When calling this method you can optionally provide an array of tag names, and only those animations
* will be created. For example:
*
* ```javascript
* sprite.anims.createFromAseprite('paladin', [ 'step', 'War Cry', 'Magnum Break' ]);
* ```
*
* This will only create the 3 animations defined. Note that the tag names are case-sensitive.
*
* @method Phaser.Animations.AnimationState#createFromAseprite
* @since 3.60.0
*
* @param {string} key - The key of the loaded Aseprite atlas. It must have been loaded prior to calling this method.
* @param {string[]} [tags] - An array of Tag names. If provided, only animations found in this array will be created.
*
* @return {Phaser.Animations.Animation[]} An array of Animation instances that were successfully created.
*/
/**
* Removes a locally created Animation from this Sprite, based on the given key.
*
* Once an Animation has been removed, this Sprite cannot play it again without re-creating it.
*
* @method Phaser.Animations.AnimationState#remove
* @since 3.50.0
*
* @param {string} key - The key of the animation to remove.
*
* @return {Phaser.Animations.Animation} The Animation instance that was removed from this Sprite, if the key was valid.
*/
/**
* The Animation Update Event.
*
* This event is dispatched by a Sprite when an animation playing on it updates. This happens when the animation changes frame.
* An animation will change frame based on the frame rate and other factors like `timeScale` and `delay`. It can also change
* frame when stopped or restarted.
*
* Listen for it on the Sprite using `sprite.on('animationupdate', listener)`
*
* If an animation is playing faster than the game frame-rate can handle, it's entirely possible for it to emit several
* update events in a single game frame, so please be aware of this in your code. The **final** event received that frame
* is the one that is rendered to the game.
*
* The animation event flow is as follows:
*
* 1. `ANIMATION_START`
* 2. `ANIMATION_UPDATE` (repeated for however many frames the animation has)
* 3. `ANIMATION_REPEAT` (only if the animation is set to repeat, it then emits more update events after this)
* 4. `ANIMATION_COMPLETE` (only if there is a finite, or zero, repeat count)
* 5. `ANIMATION_COMPLETE_KEY` (only if there is a finite, or zero, repeat count)
*
* If the animation is stopped directly, the `ANIMATION_STOP` event is dispatched instead of `ANIMATION_COMPLETE`.
*
* If the animation is restarted while it is already playing, `ANIMATION_RESTART` is emitted.
*
* @event Phaser.Animations.Events#ANIMATION_UPDATE
* @type {string}
* @since 3.50.0
*
* @param {Phaser.Animations.Animation} animation - A reference to the Animation that has updated.
* @param {Phaser.Animations.AnimationFrame} frame - The current Animation Frame of the Animation.
* @param {Phaser.GameObjects.Sprite} gameObject - A reference to the Game Object on which the animation updated.
* @param {string} frameKey - The unique key of the Animation Frame within the Animation.
*/
/**
* Gets an item from this cache based on the given key.
*
* @method Phaser.Cache.BaseCache#get
* @since 3.0.0
*
* @param {string} key - The unique key of the item to be retrieved from this cache.
*
* @return {*} The item in the cache, or `null` if no item matching the given key was found.
*/
/**
* Removes an item from this cache based on the given key.
*
* If an entry matching the key is found it is removed from the cache and a `remove` event emitted.
* No additional checks are done on the item removed. If other systems or parts of your game code
* are relying on this item, it is up to you to sever those relationships prior to removing the item.
*
* @method Phaser.Cache.BaseCache#remove
* @fires Phaser.Cache.Events#REMOVE
* @since 3.0.0
*
* @param {string} key - The unique key of the item to remove from the cache.
*
* @return {this} This BaseCache object.
*/
/**
* The rotation of the Camera in radians.
*
* Camera rotation always takes place based on the Camera viewport. By default, rotation happens
* in the center of the viewport. You can adjust this with the `originX` and `originY` properties.
*
* Rotation influences the rendering of _all_ Game Objects visible by this Camera. However, it does not
* rotate the Camera viewport itself, which always remains an axis-aligned rectangle.
*
* @name Phaser.Cameras.Scene2D.BaseCamera#_rotation
* @type {number}
* @private
* @default 0
* @since 3.11.0
*/
/**
* Can this Camera render rounded pixel values?
*
* This property is updated during the `preRender` method and should not be
* set directly. It is set based on the `roundPixels` property of the Camera
* combined with the zoom level. If the zoom is an integer then the WebGL
* Renderer can apply rounding during rendering.
*
* @name Phaser.Cameras.Scene2D.BaseCamera#renderRoundPixels
* @type {boolean}
* @readonly
* @default true
* @since 3.86.0
*/
/**
* Calculates what the Camera.scrollX and scrollY values would need to be in order to move
* the Camera so it is centered on the given x and y coordinates, without actually moving
* the Camera there. The results are clamped based on the Camera bounds, if set.
*
* @method Phaser.Cameras.Scene2D.BaseCamera#getScroll
* @since 3.11.0
*
* @param {number} x - The horizontal coordinate to center on.
* @param {number} y - The vertical coordinate to center on.
* @param {Phaser.Math.Vector2} [out] - A Vector2 to store the values in. If not given a new Vector2 is created.
*
* @return {Phaser.Math.Vector2} The scroll coordinates stored in the `x` and `y` properties.
*/
/**
* Moves the Camera so that it is re-centered based on its viewport size.
*
* @method Phaser.Cameras.Scene2D.BaseCamera#centerToSize
* @since 3.0.0
*
* @return {this} This Camera instance.
*/
/**
* Converts the given `x` and `y` coordinates into World space, based on this Cameras transform.
* You can optionally provide a Vector2, or similar object, to store the results in.
*
* @method Phaser.Cameras.Scene2D.BaseCamera#getWorldPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [output,$return]
*
* @param {number} x - The x position to convert to world space.
* @param {number} y - The y position to convert to world space.
* @param {(object|Phaser.Math.Vector2)} [output] - An optional object to store the results in. If not provided a new Vector2 will be created.
*
* @return {Phaser.Math.Vector2} An object holding the converted values in its `x` and `y` properties.
*/
/**
* The rotation of the Camera in radians.
*
* Camera rotation always takes place based on the Camera viewport. By default, rotation happens
* in the center of the viewport. You can adjust this with the `originX` and `originY` properties.
*
* Rotation influences the rendering of _all_ Game Objects visible by this Camera. However, it does not
* rotate the Camera viewport itself, which always remains an axis-aligned rectangle.
*
* @name Phaser.Cameras.Scene2D.BaseCamera#rotation
* @type {number}
* @private
* @default 0
* @since 3.11.0
*/
/**
* Adds a new Camera into the Camera Manager. The Camera Manager can support up to 31 different Cameras.
*
* Each Camera has its own viewport, which controls the size of the Camera and its position within the canvas.
*
* Use the `Camera.scrollX` and `Camera.scrollY` properties to change where the Camera is looking, or the
* Camera methods such as `centerOn`. Cameras also have built in special effects, such as fade, flash, shake,
* pan and zoom.
*
* By default Cameras are transparent and will render anything that they can see based on their `scrollX`
* and `scrollY` values. Game Objects can be set to be ignored by a Camera by using the `Camera.ignore` method.
*
* The Camera will have its `roundPixels` property set to whatever `CameraManager.roundPixels` is. You can change
* it after creation if required.
*
* See the Camera class documentation for more details.
*
* @method Phaser.Cameras.Scene2D.CameraManager#add
* @since 3.0.0
*
* @param {number} [x=0] - The horizontal position of the Camera viewport.
* @param {number} [y=0] - The vertical position of the Camera viewport.
* @param {number} [width] - The width of the Camera viewport. If not given it'll be the game config size.
* @param {number} [height] - The height of the Camera viewport. If not given it'll be the game config size.
* @param {boolean} [makeMain=false] - Set this Camera as being the 'main' camera. This just makes the property `main` a reference to it.
* @param {string} [name=''] - The name of the Camera.
*
* @return {Phaser.Cameras.Scene2D.Camera} The newly created Camera.
*/
/**
* Populates this Camera Manager based on the given configuration object, or an array of config objects.
*
* See the `Phaser.Types.Cameras.Scene2D.CameraConfig` documentation for details of the object structure.
*
* @method Phaser.Cameras.Scene2D.CameraManager#fromJSON
* @since 3.0.0
*
* @param {(Phaser.Types.Cameras.Scene2D.CameraConfig|Phaser.Types.Cameras.Scene2D.CameraConfig[])} config - A Camera configuration object, or an array of them, to be added to this Camera Manager.
*
* @return {this} This Camera Manager instance.
*/
/**
* Gets a Camera based on its name.
*
* Camera names are optional and don't have to be set, so this method is only of any use if you
* have given your Cameras unique names.
*
* @method Phaser.Cameras.Scene2D.CameraManager#getCamera
* @since 3.0.0
*
* @param {string} name - The name of the Camera.
*
* @return {?Phaser.Cameras.Scene2D.Camera} The first Camera with a name matching the given string, otherwise `null`.
*/
/**
* @author Jason Nicholls <nicholls.jason@gmail.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @classdesc
* A Camera Rotate effect that smoothly rotates the Camera to a target angle over a specified duration.
*
* This effect will rotate the Camera so that its viewport finishes at the given angle in radians,
* over the duration and with the ease specified.
*
* Camera rotation always takes place based on the Camera viewport. By default, rotation happens
* in the center of the viewport. You can adjust this with the `originX` and `originY` properties.
*
* Rotation influences the rendering of _all_ Game Objects visible by this Camera. However, it does not
* rotate the Camera viewport itself, which always remains an axis-aligned rectangle.
*
* Only the camera is rotated. None of the objects it is displaying are impacted, i.e. their positions do
* not change.
*
* The effect will dispatch several events on the Camera itself and you can also specify an `onUpdate` callback,
* which is invoked each frame for the duration of the effect if required.
*
* @class RotateTo
* @memberof Phaser.Cameras.Scene2D.Effects
* @constructor
* @since 3.23.0
*
* @param {Phaser.Cameras.Scene2D.Camera} camera - The camera this effect is acting upon.
*/
/**
* Applies the results of pressing the control keys to the Camera.
*
* You must call this every step, it is not called automatically.
*
* @method Phaser.Cameras.Controls.FixedKeyControl#update
* @since 3.0.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Applies the results of pressing the control keys to the Camera.
*
* You must call this every step, it is not called automatically.
*
* @method Phaser.Cameras.Controls.SmoothedKeyControl#update
* @since 3.0.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* @const {string[]} Phaser.Core.Config#seed - A seed which the Random Data Generator will use. If not given, a dynamic seed based on the time is used.
*/
/**
* @const {(number|boolean)} Phaser.Core.Config#stableSort - `false` or `0` = Use the built-in StableSort (needed for older browsers), `true` or `1` = Rely on ES2019 Array.sort being stable (modern browsers only), or `-1` = Try and determine this automatically based on browser inspection (not guaranteed to work, errs on side of caution).
*/
/**
* @const {boolean} Phaser.Core.Config#desynchronized - When set to `true` it will create a desynchronized context for both 2D and WebGL. See https://developers.google.com/web/updates/2019/05/desynchronized for details.
*/
/**
* @const {boolean} Phaser.Core.Config#selfShadow - On textured objects with lighting, this enables self-shadowing based on the diffuse map.
*/
/**
* @const {string} Phaser.Core.Config#loaderBaseURL - A URL used to resolve paths given to the loader. Example: 'http://labs.phaser.io/assets/'.
*/
/**
* @const {(string|undefined)} Phaser.Core.Config#loaderCrossOrigin - 'anonymous', 'use-credentials', or `undefined`. If you're not making cross-origin requests, leave this as `undefined`. See {@link https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes}.
*/
/**
* The main Game Step. Called automatically by the Time Step, once per browser frame (typically as a result of
* Request Animation Frame, or Set Timeout on very old browsers.)
*
* The step will update the global managers first, then proceed to update each Scene in turn, via the Scene Manager.
*
* It will then render each Scene in turn, via the Renderer. This process emits `prerender` and `postrender` events.
*
* @method Phaser.Game#step
* @fires Phaser.Core.Events#PRE_STEP
* @fires Phaser.Core.Events#STEP
* @fires Phaser.Core.Events#POST_STEP
* @fires Phaser.Core.Events#PRE_RENDER
* @fires Phaser.Core.Events#POST_RENDER
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* A special version of the Game Step for the HEADLESS renderer only.
*
* The main Game Step. Called automatically by the Time Step, once per browser frame (typically as a result of
* Request Animation Frame, or Set Timeout on very old browsers.)
*
* The step will update the global managers first, then proceed to update each Scene in turn, via the Scene Manager.
*
* This process emits `prerender` and `postrender` events, even though nothing actually displays.
*
* @method Phaser.Game#headlessStep
* @fires Phaser.Core.Events#PRE_RENDER
* @fires Phaser.Core.Events#POST_RENDER
* @since 3.2.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Returns the time that the current game step started at, as based on `performance.now`.
*
* @method Phaser.Game#getTime
* @since 3.16.0
*
* @return {number} The current game timestamp.
*/
/**
* @classdesc
* The core runner class that Phaser uses to handle the game loop. It can use either Request Animation Frame,
* or SetTimeout, based on browser support and config settings, to create a continuous loop within the browser.
*
* Each time the loop fires, `TimeStep.step` is called and this is then passed onto the core Game update loop,
* it is the core heartbeat of your game. It will fire as often as Request Animation Frame is capable of handling
* on the target device.
*
* Note that there are lots of situations where a browser will stop updating your game. Such as if the player
* switches tabs, or covers up the browser window with another application. In these cases, the 'heartbeat'
* of your game will pause, and only resume when focus is returned to it by the player. There is no way to avoid
* this situation, all you can do is use the visibility events the browser, and Phaser, provide to detect when
* it has happened and then gracefully recover.
*
* @class TimeStep
* @memberof Phaser.Core
* @constructor
* @since 3.0.0
*
* @param {Phaser.Game} game - A reference to the Phaser.Game instance that owns this Time Step.
* @param {Phaser.Types.Core.FPSConfig} config - The FPS configuration object, as parsed by the Game Config.
*/
/**
* The time, set at the start of the current step.
*
* This is typically a high resolution timer value, as provided by Request Animation Frame.
*
* This can differ from the `time` value in that it isn't calculated based on the delta value.
*
* @name Phaser.Core.TimeStep#now
* @type {number}
* @default 0
* @since 3.18.0
*/
/**
* Takes the delta value and smooths it based on the previous frames.
*
* Called automatically as part of the step.
*
* @method Phaser.Core.TimeStep#smoothDelta
* @since 3.60.0
*
* @param {number} delta - The delta value for this step.
*
* @return {number} The smoothed delta value.
*/
/**
* Wakes-up the TimeStep, restarting Request Animation Frame (or SetTimeout) and toggling the `running` flag to true.
* The `seamless` argument controls if the wake-up should adjust the start time or not.
*
* @method Phaser.Core.TimeStep#wake
* @since 3.0.0
*
* @param {boolean} [seamless=false] - Adjust the startTime based on the lastTime values.
*/
/**
* The Game Post-Step Event.
*
* This event is dispatched after the Scene Manager has updated.
* Hook into it from plugins or systems that need to do things before the render starts.
*
* @event Phaser.Core.Events#POST_STEP
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* The Game Pre-Step Event.
*
* This event is dispatched before the main Game Step starts. By this point in the game cycle none of the Scene updates have yet happened.
* Hook into it from plugins or systems that need to update before the Scene Manager does.
*
* @event Phaser.Core.Events#PRE_STEP
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* The Game Step Event.
*
* This event is dispatched after the Game Pre-Step and before the Scene Manager steps.
* Hook into it from plugins or systems that need to update before the Scene Manager does, but after the core Systems have.
*
* @event Phaser.Core.Events#STEP
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* @classdesc
* A Base Curve class, which all other curve types extend.
*
* A Curve represents a mathematical path through 2D space and provides methods for
* sampling points, calculating arc lengths, and obtaining tangent vectors along it.
* Curves are the building blocks of `Phaser.Curves.Path`, which allows Game Objects
* to follow complex routes through a scene.
*
* This class is not intended to be instantiated directly. Instead, use one of the
* concrete subclasses in the `Phaser.Curves` namespace, such as `LineCurve`,
* `QuadraticBezier`, `CubicBezier`, `EllipseCurve`, or `SplineCurve`.
*
* Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog)
*
* @class Curve
* @memberof Phaser.Curves
* @constructor
* @since 3.0.0
*
* @param {string} type - The curve type.
*/
/**
* @classdesc
* An Ellipse Curve is a smooth curve that describes the path of an ellipse. It can be used
* to move Game Objects along an elliptical path, generate points distributed around an ellipse,
* or draw elliptical arcs as part of a Path or Graphics object.
*
* You can control the center position, horizontal and vertical radii, start and end angles,
* rotation, and whether the curve runs clockwise or anti-clockwise. Passing only `xRadius`
* will create a circle (both radii are equal by default).
*
* This curve extends the base `Phaser.Curves.Curve` class and can be used anywhere a Curve
* is accepted in Phaser, such as `Phaser.Curves.Path` or a `PathFollower` Game Object.
*
* See https://en.wikipedia.org/wiki/Ellipse for more details.
*
* @class Ellipse
* @extends Phaser.Curves.Curve
* @memberof Phaser.Curves
* @constructor
* @since 3.0.0
*
* @param {(number|Phaser.Types.Curves.EllipseCurveConfig)} [x=0] - The x coordinate of the ellipse, or an Ellipse Curve configuration object.
* @param {number} [y=0] - The y coordinate of the ellipse.
* @param {number} [xRadius=0] - The horizontal radius of ellipse.
* @param {number} [yRadius=0] - The vertical radius of ellipse.
* @param {number} [startAngle=0] - The start angle of the ellipse, in degrees.
* @param {number} [endAngle=360] - The end angle of the ellipse, in degrees.
* @param {boolean} [clockwise=false] - Whether the ellipse angles are given as clockwise (`true`) or counter-clockwise (`false`).
* @param {number} [rotation=0] - The rotation of the ellipse, in degrees.
*/
/**
* Determines the browser type and version running this Phaser Game instance.
* These values are read-only and populated during the boot sequence of the game.
* They are then referenced by internal game systems and are available for you to access
* via `this.sys.game.device.browser` from within any Scene.
*
* @typedef {object} Phaser.Device.Browser
* @since 3.0.0
*
* @property {boolean} chrome - Set to true if running in Chrome.
* @property {boolean} edge - Set to true if running in Microsoft Edge browser.
* @property {boolean} firefox - Set to true if running in Firefox.
* @property {boolean} ie - Set to true if running in Internet Explorer 11 or less (not Edge).
* @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
* @property {boolean} opera - Set to true if running in Opera.
* @property {boolean} safari - Set to true if running in Safari.
* @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle).
* @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11 or earlier).
* @property {boolean} es2019 - Set to true if the browser appears to support ES2019 features.
* @property {number} chromeVersion - If running in Chrome this will contain the major version number.
* @property {number} firefoxVersion - If running in Firefox this will contain the major version number.
* @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Browser.trident and Browser.tridentVersion.
* @property {number} safariVersion - If running in Safari this will contain the major version number.
* @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx}
*/
/**
* The color interpolation.
* This can be one of the following codes:
*
* - 0: LINEAR - a straight blend.
* - 1: CURVED - color changes quickly at start and end,
* flattening in the middle. Good for convex surfaces.
* - 2: SINUSOIDAL - color changes quickly in the middle,
* flattening at start and end. Good for smooth transitions.
* - 3: CURVE_START - color changes quickly at the start,
* flattening at the end.
* - 4: CURVE_END - color changes quickly at the end,
* flattening at the start.
*
* Modes 2, 3, and 4 use the circular easing function directly.
* Mode 1 uses a related custom formula based on the unit circle.
*
* @name Phaser.Display.ColorBand#interpolation
* @type {number}
* @default 0
* @since 4.0.0
*/
/**
* Takes a given Game Object and aligns it so that it is positioned relative to another Game Object.
* The alignment used is based on the `position` argument, which is an `ALIGN_CONST` value, such as `LEFT_CENTER` or `TOP_RIGHT`.
*
* @function Phaser.Display.Align.In.QuickSet
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject} G - [child,$return]
*
* @param {Phaser.GameObjects.GameObject} child - The Game Object that will be positioned.
* @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on.
* @param {number} position - The position to align the Game Object with. This is an align constant, such as `ALIGN_CONST.LEFT_CENTER`.
* @param {number} [offsetX=0] - Optional horizontal offset from the position.
* @param {number} [offsetY=0] - Optional vertical offset from the position.
*
* @return {Phaser.GameObjects.GameObject} The Game Object that was aligned.
*/
/**
* Takes a Game Object and aligns it next to another, at the given position.
* The alignment used is based on the `position` argument, which is a `Phaser.Display.Align` property such as `LEFT_CENTER` or `TOP_RIGHT`.
*
* @function Phaser.Display.Align.To.QuickSet
* @since 3.22.0
*
* @generic {Phaser.GameObjects.GameObject} G - [child,$return]
*
* @param {Phaser.GameObjects.GameObject} child - The Game Object that will be positioned.
* @param {Phaser.GameObjects.GameObject} alignTo - The Game Object to base the alignment position on.
* @param {number} position - The position to align the Game Object with. This is an align constant, such as `Phaser.Display.Align.LEFT_CENTER`.
* @param {number} [offsetX=0] - Optional horizontal offset from the position, in pixels.
* @param {number} [offsetY=0] - Optional vertical offset from the position, in pixels.
*
* @return {Phaser.GameObjects.GameObject} The Game Object that was aligned.
*/
/**
* Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use.
* The canvas has its width and height set to 1, and its parent attribute nulled.
*
* @function Phaser.Display.Canvas.CanvasPool.remove
* @since 3.0.0
*
* @param {*} parent - The canvas or the parent of the canvas to free.
*/
/**
* Sets the color based on the color object given.
*
* @method Phaser.Display.Color#setFromRGB
* @since 3.0.0
*
* @param {Phaser.Types.Display.InputColorObject} color - An object containing `r`, `g`, `b` and optionally `a` values in the range 0 to 255.
*
* @return {Phaser.Display.Color} This Color object.
*/
/**
* Sets the color based on the hue, saturation and value (HSV) components given.
*
* @method Phaser.Display.Color#setFromHSV
* @since 3.13.0
*
* @param {number} h - The hue, in the range 0 - 1. This is the base color.
* @param {number} s - The saturation, in the range 0 - 1. This controls how much of the hue will be in the final color, where 1 is fully saturated and 0 will give you white.
* @param {number} v - The value, in the range 0 - 1. This controls how dark the color is. Where 1 is as bright as possible and 0 is black.
*
* @return {Phaser.Display.Color} This Color object.
*/
/**
* Sets this Color object to be grayscaled based on the shade value given.
*
* @method Phaser.Display.Color#gray
* @since 3.13.0
*
* @param {number} shade - A value between 0 and 255.
*
* @return {Phaser.Display.Color} This Color object.
*/
/**
* Converts a HSV (hue, saturation and value) color set to RGB.
*
* Conversion formula from https://en.wikipedia.org/wiki/HSL_and_HSV
*
* Assumes HSV values are contained in the set [0, 1].
*
* @function Phaser.Display.Color.HSVToRGB
* @since 3.0.0
*
* @param {number} h - The hue, in the range 0 - 1. This is the base color.
* @param {number} s - The saturation, in the range 0 - 1. This controls how much of the hue will be in the final color, where 1 is fully saturated and 0 will give you a greyscale color.
* @param {number} v - The value, in the range 0 - 1. This controls how bright the color is, where 1 is as bright as possible and 0 is black.
* @param {(Phaser.Types.Display.ColorObject|Phaser.Display.Color)} [out] - A Color object to store the results in. If not given a new ColorObject will be created.
*
* @return {(Phaser.Types.Display.ColorObject|Phaser.Display.Color)} An object with the red, green and blue values set in the r, g and b properties.
*/
/**
* Calculates a single RGB channel value from a hue offset and the two intermediate
* lightness values used during HSL to RGB conversion. Call this function once for each
* channel (red, green, and blue), passing the appropriate hue offset each time.
* Based on code by Michael Jackson (https://github.com/mjijackson)
*
* @function Phaser.Display.Color.HueToComponent
* @since 3.0.0
*
* @param {number} p - The first intermediate value derived from the lightness during HSL to RGB conversion.
* @param {number} q - The second intermediate value derived from the lightness and saturation during HSL to RGB conversion.
* @param {number} t - The hue offset for the color channel being calculated (red, green, or blue).
*
* @return {number} The RGB channel value for the given hue offset, in the range 0 to 1.
*/
/**
* Converts an RGB color value to HSV (hue, saturation and value).
* Conversion formula from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
* Based on code by Michael Jackson (https://github.com/mjijackson)
*
* @function Phaser.Display.Color.RGBToHSV
* @since 3.0.0
*
* @param {number} r - The red color value. A number between 0 and 255.
* @param {number} g - The green color value. A number between 0 and 255.
* @param {number} b - The blue color value. A number between 0 and 255.
* @param {(Phaser.Types.Display.HSVColorObject|Phaser.Display.Color)} [out] - An object to store the color values in. If not given an HSV Color Object will be created.
*
* @return {(Phaser.Types.Display.HSVColorObject|Phaser.Display.Color)} An object with the properties `h`, `s` and `v` set.
*/
/**
* Creates a new Color object where the r, g, and b values have been set to random values
* based on the given min max values.
*
* @function Phaser.Display.Color.RandomRGB
* @since 3.0.0
*
* @param {number} [min=0] - The minimum value to set the random range from (between 0 and 255)
* @param {number} [max=255] - The maximum value to set the random range from (between 0 and 255)
*
* @return {Phaser.Display.Color} A Color object.
*/
/**
* Attempts to determine the document inner height across iOS and standard devices.
* On non-iOS devices this simply returns `window.innerHeight`. On iOS, Safari's dynamic
* browser chrome (such as the address bar appearing or hiding on scroll) can cause
* `window.innerHeight` to report an inaccurate value. To work around this, a temporary
* fixed-position element sized to `100vh` is injected into the DOM, its measured height
* is used instead, and the element is immediately removed. The result is also adjusted
* for landscape orientation using `window.orientation`.
* Based on code by @tylerjpeterson
*
* @function Phaser.DOM.GetInnerHeight
* @since 3.16.0
*
* @param {boolean} iOS - Is this running on iOS?
*
* @return {number} The inner height of the viewport, in pixels.
*/
/**
* Attempts to get the target DOM element based on the given value, which can be either
* a string, in which case it will be looked-up by ID, or an element node. If nothing
* can be found it will return a reference to the document.body.
*
* @function Phaser.DOM.GetTarget
* @since 3.16.0
*
* @param {HTMLElement} element - The DOM element to look-up. Can be either a string, in which case it is used as an element ID to look up via `document.getElementById`, or a direct reference to an existing HTMLElement node.
*
* @return {HTMLElement} The DOM element matching the given ID or node reference, or `document.body` if no valid target was found.
*/
/*
The padding is calculated based on the camera height and the radius of the bokeh effect.
The constant value is derived from the shader.
The shader samples based on a complicated formula,
but it is based on camera height and radius,
multiplied by various constants including 0.025 and 0.06,
and an iteration which sums to 14.284061040284603 after 100 iterations.
Together, these multiply to the constant 0.021426096060426905.
This is the maximum padding required for the bokeh effect.
*/
/**
* @classdesc
* The Displacement Filter Controller.
*
* This Filter controller manages the displacement effect.
*
* The displacement effect is a visual technique that alters the position of pixels in an image
* or texture based on the values of a displacement map. This effect is used to create the illusion
* of depth, surface irregularities, or distortion in otherwise flat elements. It can be applied to
* characters, objects, or backgrounds to enhance realism, convey movement, or achieve various
* stylistic appearances.
*
* This effect samples across an area. To avoid missing data at the edges,
* use `controller.setPaddingOverride(null)` to automatically pad game objects,
* or `camera.getPaddingWrapper(x)` to enlarge a camera.
*
* A Displacement effect is added to a Camera via the FilterList component:
*
* ```js
* const camera = this.cameras.main;
*
* camera.filters.internal.addDisplacement();
* camera.filters.external.addDisplacement();
* ```
*
* @class Displacement
* @memberof Phaser.Filters
* @constructor
* @since 4.0.0
* @extends Phaser.Filters.Controller
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that owns this filter.
* @param {string} [texture='__WHITE'] - The unique string-based key of the texture to use for displacement, which must exist in the Texture Manager.
* @param {number} [x=0.005] - The amount of horizontal displacement to apply. A very small float number, such as 0.005.
* @param {number} [y=0.005] - The amount of vertical displacement to apply. A very small float number, such as 0.005.
*/
/**
* The source of the model rotation, used when the filter renders.
* If a function, it will be called to get the rotation.
* If a GameObject, it will be used to get the rotation from the GameObject's world transform.
* If null, the model rotation will be taken from the modelRotation property.
*
* @name Phaser.Filters.ImageLight#modelRotationSource
* @type {Phaser.GameObjects.GameObject | Phaser.Types.Filters.ImageLightSourceCallback | null}
* @since 4.0.0
*/
/**
* @classdesc
* The Quantize Filter Controller.
*
* This controller manages the Quantize effect on a Camera.
*
* Quantization reduces the unique number of colors in an image,
* based on some limited number of steps per color channel.
* This is good for creating a retro or stylized effect.
*
* Basic quantization breaks each channel up into a number of `steps`.
* These steps are normally regular. You can bias them towards the top or bottom
* by changing that channel's `gamma` value.
* You can adjust the lowest step, thus all subsequent steps, with the `offset`.
*
* Quantization is done in either RGBA or HSVA space.
* The steps, gamma, and offset always apply in the same order,
* but depending on color mode, they are either applied to
* `[ red, green, blue, alpha ]` or `[ hue, saturation, value, alpha ]`.
*
* The output may optionally be dithered, to eliminate banding
* and create the illusion that there are many more colors in use.
*
* @example
* const camera = this.cameras.main;
* camera.filters.internal.addQuantize(); // Default effect.
* camera.filters.external.addQuantize({
* steps: [ 16, 1, 1, 1 ],
* dither: true,
* mode: 1
* }); // Quantize into 16 fully saturated rainbow hues, and dither.
*
* @class Quantize
* @memberof Phaser.Filters
* @constructor
* @since 4.0.0
* @extends Phaser.Filters.Controller
* @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that owns this filter.
* @param {Phaser.Types.Filters.QuantizeConfig} [config] - The configuration object for the Quantize effect.
*/
/**
* Pass this Game Object to the Input Manager to enable it for Input.
*
* Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area
* for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced
* input detection.
*
* If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If
* this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific
* shape for it to use.
*
* You can also provide an Input Configuration Object as the only argument to this method.
*
* @example
* sprite.setInteractive();
*
* @example
* sprite.setInteractive(new Phaser.Geom.Circle(45, 46, 45), Phaser.Geom.Circle.Contains);
*
* @example
* graphics.setInteractive(new Phaser.Geom.Rectangle(0, 0, 128, 128), Phaser.Geom.Rectangle.Contains);
*
* @method Phaser.GameObjects.GameObject#setInteractive
* @since 3.0.0
*
* @param {(Phaser.Types.Input.InputConfiguration|any)} [hitArea] - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not given it will try to create a Rectangle based on the texture frame.
* @param {Phaser.Types.Input.HitAreaCallback} [callback] - The callback that determines if the pointer is within the Hit Area shape or not. If you provide a shape you must also provide a callback.
* @param {boolean} [dropZone=false] - Should this Game Object be treated as a drop zone target?
*
* @return {this} This GameObject.
*/
/**
* Checks if this Game Object should round its vertices,
* based on the given Camera and the `vertexRoundMode` of this Game Object.
* This is used by the WebGL Renderer to determine how to round the vertex positions.
*
* You can override this method in your own custom Game Object classes to provide
* custom logic for vertex rounding.
*
* @method Phaser.GameObjects.GameObject#willRoundVertices
* @since 4.0.0
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object.
* @param {boolean} onlyTranslated - If true, the object is only translated, not scaled or rotated.
* @return {boolean} True if the Game Object should be rounded, otherwise false.
*/
/**
* @classdesc
* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
*
* During rendering, each letter of the text is rendered to the display, proportionally spaced out and aligned to
* match the font structure.
*
* Dynamic Bitmap Text objects are different from Static Bitmap Text in that they invoke a callback for each
* letter being rendered during the render pass. This callback allows you to manipulate the properties of
* each letter being rendered, such as its position, scale or tint, allowing you to create interesting effects
* like jiggling text, which can't be done with Static text. This means that Dynamic Text takes more processing
* time, so only use them if you require the callback ability they have.
*
* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
* processing the font texture in an image editor, applying fills and any other effects required.
*
* To create multi-line text insert \r, \n or \r\n escape codes into the text string.
*
* To create a BitmapText data files you need a 3rd party app such as:
*
* BMFont (Windows, free): {@link http://www.angelcode.com/products/bmfont/|http://www.angelcode.com/products/bmfont/}
* Glyph Designer (OS X, commercial): {@link http://www.71squared.com/en/glyphdesigner|http://www.71squared.com/en/glyphdesigner}
* Snow BMF (Web-based, free): {@link https://snowb.org//|https://snowb.org/}
* Littera (Flash-based, free): {@link http://kvazars.com/littera/|http://kvazars.com/littera/}
*
* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: {@link http://codebeautify.org/xmltojson|http://codebeautify.org/xmltojson}
*
* @class DynamicBitmapText
* @extends Phaser.GameObjects.BitmapText
* @memberof Phaser.GameObjects
* @constructor
* @since 3.0.0
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. It can only belong to one Scene at any given time.
* @param {number} x - The x coordinate of this Game Object in world space.
* @param {number} y - The y coordinate of this Game Object in world space.
* @param {string} font - The key of the font to use from the Bitmap Font cache.
* @param {(string|string[])} [text] - The string, or array of strings, to be set as the content of this Bitmap Text.
* @param {number} [size] - The font size of this Bitmap Text.
* @param {number} [align=0] - The alignment of the text in a multi-line BitmapText object.
*/
/**
* Creates a new Dynamic Bitmap Text Game Object and adds it to the Scene.
*
* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
*
* During rendering, each letter of the text is rendered to the display, proportionally spaced out and aligned to
* match the font structure.
*
* Dynamic Bitmap Text objects are different from Static Bitmap Text in that they invoke a callback for each
* letter being rendered during the render pass. This callback allows you to manipulate the properties of
* each letter being rendered, such as its position, scale or tint, allowing you to create interesting effects
* like jiggling text, which can't be done with Static text. This means that Dynamic Text takes more processing
* time, so only use them if you require the callback ability they have.
*
* BitmapText objects are less flexible than Text objects, in that they have fewer features such as shadows, fills and the ability
* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
* processing the font texture in an image editor, applying fills and any other effects required.
*
* To create multi-line text insert \r, \n or \r\n escape codes into the text string.
*
* To create a BitmapText data files you need a 3rd party app such as:
*
* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
* Littera (Web-based, free): http://kvazars.com/littera/
*
* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson
*
* Note: This method will only be available if the Dynamic Bitmap Text Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectFactory#dynamicBitmapText
* @since 3.0.0
*
* @param {number} x - The x position of the Game Object.
* @param {number} y - The y position of the Game Object.
* @param {string} font - The key of the font to use from the BitmapFont cache.
* @param {(string|string[])} [text] - The string, or array of strings, to be set as the content of this Bitmap Text.
* @param {number} [size] - The font size to set.
*
* @return {Phaser.GameObjects.DynamicBitmapText} The Game Object that was created.
*/
/**
* @classdesc
* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
*
* During rendering for each letter of the text is rendered to the display, proportionally spaced out and aligned to
* match the font structure.
*
* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
* processing the font texture in an image editor, applying fills and any other effects required.
*
* To create multi-line text insert \r, \n or \r\n escape codes into the text string.
*
* To create a BitmapText data files you need a 3rd party app such as:
*
* BMFont (Windows, free): {@link http://www.angelcode.com/products/bmfont/|http://www.angelcode.com/products/bmfont/}
* Glyph Designer (OS X, commercial): {@link http://www.71squared.com/en/glyphdesigner|http://www.71squared.com/en/glyphdesigner}
* Snow BMF (Web-based, free): {@link https://snowb.org//|https://snowb.org/}
* Littera (Flash-based, free): {@link http://kvazars.com/littera/|http://kvazars.com/littera/}
*
* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: {@link http://codebeautify.org/xmltojson|http://codebeautify.org/xmltojson}
*
* @class BitmapText
* @extends Phaser.GameObjects.GameObject
* @memberof Phaser.GameObjects
* @constructor
* @since 3.0.0
*
* @extends Phaser.GameObjects.Components.Alpha
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.GetBounds
* @extends Phaser.GameObjects.Components.Lighting
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.Origin
* @extends Phaser.GameObjects.Components.RenderNodes
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.Texture
* @extends Phaser.GameObjects.Components.Tint
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. It can only belong to one Scene at any given time.
* @param {number} x - The x coordinate of this Game Object in world space.
* @param {number} y - The y coordinate of this Game Object in world space.
* @param {string} font - The key of the font to use from the Bitmap Font cache.
* @param {(string|string[])} [text] - The string, or array of strings, to be set as the content of this Bitmap Text.
* @param {number} [size] - The font size of this Bitmap Text.
* @param {number} [align=0] - The alignment of the text in a multi-line BitmapText object.
*/
/**
* Controls the alignment of each line of text in this BitmapText object.
* Only has any effect when this BitmapText contains multiple lines of text, split with carriage-returns.
* Has no effect with single-lines of text.
*
* See the methods `setLeftAlign`, `setCenterAlign` and `setRightAlign`.
*
* 0 = Left aligned (default)
* 1 = Middle aligned
* 2 = Right aligned
*
* The alignment position is based on the longest line of text.
*
* @name Phaser.GameObjects.BitmapText#_align
* @type {number}
* @private
* @since 3.11.0
*/
/**
* Sets a tint on a matching word within this Bitmap Text.
*
* The `word` parameter can be either a string or a number.
*
* If a string, it will run a string comparison against the text contents, and if matching,
* it will tint the whole word.
*
* If a number, it will tint that word, based on its index within the words array.
*
* The `count` parameter controls how many words are replaced. Pass in -1 to replace them all.
*
* This parameter is ignored if you pass a number as the `word` to be searched for.
*
* This is a WebGL only feature and only works with Static Bitmap Text, not Dynamic.
*
* The tint applies a color to the pixel color values
* from the Bitmap Text texture in one of several modes:
*
* - Phaser.TintModes.MULTIPLY (default)
* - Phaser.TintModes.FILL
* - Phaser.TintModes.ADD
* - Phaser.TintModes.SCREEN
* - Phaser.TintModes.OVERLAY
* - Phaser.TintModes.HARD_LIGHT
*
* You can provide either one color value,
* in which case the whole character will be tinted in that color. Or you can provide a color
* per corner. The colors are blended together across the extent of the character range.
*
* To modify the tint color once set, call this method again with new color values.
*
* Using `setCharacterTint` can override tints set by this function, and vice versa.
*
* @method Phaser.GameObjects.BitmapText#setWordTint
* @webglOnly
* @since 3.50.0
*
* @param {(string|number)} word - The word to search for. Either a string, or an index of the word in the words array.
* @param {number} [count=1] - The number of matching words to tint. Pass -1 to tint all matching words.
* @param {number} [tintMode=Phaser.TintModes.MULTIPLY] - The tint mode to use.
* @param {number} [topLeft=0xffffff] - The tint being applied to the top-left of the word. If no other values are given this value is applied evenly, tinting the whole word.
* @param {number} [topRight] - The tint being applied to the top-right of the word.
* @param {number} [bottomLeft] - The tint being applied to the bottom-left of the word.
* @param {number} [bottomRight] - The tint being applied to the bottom-right of the word.
*
* @return {this} This BitmapText Object.
*/
/**
* Calculate the bounds of this Bitmap Text.
*
* An object is returned that contains the position, width and height of the Bitmap Text in local and global
* contexts.
*
* Local size is based on just the font size and a [0, 0] position.
*
* Global size takes into account the Game Object's scale, world position and display origin.
*
* Also in the object is data regarding the length of each line, should this be a multi-line BitmapText.
*
* @method Phaser.GameObjects.BitmapText#getTextBounds
* @since 3.0.0
*
* @param {boolean} [round=false] - Whether to round the results up to the nearest integer.
*
* @return {Phaser.Types.GameObjects.BitmapText.BitmapTextSize} An object that describes the size of this Bitmap Text.
*/
/**
* Gets the character located at the given x/y coordinate within this Bitmap Text.
*
* The coordinates you pass in are translated into the local space of the
* Bitmap Text, however, it is up to you to first translate the input coordinates to world space.
*
* If you wish to use this in combination with an input event, be sure
* to pass in `Pointer.worldX` and `worldY` so they are in world space.
*
* In some cases, based on kerning, characters can overlap. When this happens,
* the first character in the word is returned.
*
* Note that this does not work for DynamicBitmapText if you have changed the
* character positions during render. It will only scan characters in their un-translated state.
*
* @method Phaser.GameObjects.BitmapText#getCharacterAt
* @since 3.50.0
*
* @param {number} x - The x position to check.
* @param {number} y - The y position to check.
* @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera which is being tested against. If not given will use the Scene default camera.
*
* @return {Phaser.Types.GameObjects.BitmapText.BitmapTextCharacter} The character object at the given position, or `null`.
*/
/**
* Sets the maximum display width of this BitmapText in pixels.
*
* If `BitmapText.text` is longer than `maxWidth` then the lines will be automatically wrapped
* based on the previous whitespace character found in the line.
*
* If no whitespace was found then no wrapping will take place and consequently the `maxWidth` value will not be honored.
*
* Disable maxWidth by setting the value to 0.
*
* You can set the whitespace character to be searched for by setting the `wordWrapCharCode` parameter or property.
*
* @method Phaser.GameObjects.BitmapText#setMaxWidth
* @since 3.21.0
*
* @param {number} value - The maximum display width of this BitmapText in pixels. Set to zero to disable.
* @param {number} [wordWrapCharCode] - The character code to check for when word wrapping. Defaults to 32 (the space character).
*
* @return {this} This BitmapText Object.
*/
/**
* Controls the alignment of each line of text in this BitmapText object.
*
* Only has any effect when this BitmapText contains multiple lines of text, split with carriage-returns.
* Has no effect with single-lines of text.
*
* See the methods `setLeftAlign`, `setCenterAlign` and `setRightAlign`.
*
* 0 = Left aligned (default)
* 1 = Middle aligned
* 2 = Right aligned
*
* The alignment position is based on the longest line of text.
*
* @name Phaser.GameObjects.BitmapText#align
* @type {number}
* @since 3.11.0
*/
/**
* The maximum display width of this BitmapText in pixels.
*
* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped
* based on the last whitespace character found in the line.
*
* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored.
*
* Disable maxWidth by setting the value to 0.
*
* @name Phaser.GameObjects.BitmapText#maxWidth
* @type {number}
* @since 3.21.0
*/
/**
* Creates a new Bitmap Text Game Object and adds it to the Scene.
*
* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
*
* During rendering, each letter of the text is rendered to the display, proportionally spaced out and aligned to
* match the font structure.
*
* BitmapText objects are less flexible than Text objects, in that they have fewer features such as shadows, fills and the ability
* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
* processing the font texture in an image editor, applying fills and any other effects required.
*
* To create multi-line text insert \r, \n or \r\n escape codes into the text string.
*
* To create BitmapText data files you need a 3rd party app such as:
*
* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
* Littera (Web-based, free): http://kvazars.com/littera/
*
* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson
*
* Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectFactory#bitmapText
* @since 3.0.0
*
* @param {number} x - The x position of the Game Object.
* @param {number} y - The y position of the Game Object.
* @param {string} font - The key of the font to use from the BitmapFont cache.
* @param {(string|string[])} [text] - The string, or array of strings, to be set as the content of this Bitmap Text.
* @param {number} [size] - The font size to set.
* @param {number} [align=0] - The alignment of the text in a multi-line BitmapText object.
*
* @return {Phaser.GameObjects.BitmapText} The Game Object that was created.
*/
/**
* Adds a Displacement effect.
*
* The displacement effect is a visual technique that alters the position of pixels in an image
* or texture based on the values of a displacement map. This effect is used to create the illusion
* of depth, surface irregularities, or distortion in otherwise flat elements. It can be applied to
* characters, objects, or backgrounds to enhance realism, convey movement, or achieve various
* stylistic appearances.
*
* @method Phaser.GameObjects.Components.FilterList#addDisplacement
* @since 4.0.0
*
* @param {string} [texture='__WHITE'] - The unique string-based key of the texture to use for displacement, which must exist in the Texture Manager.
* @param {number} [x=0.005] - The amount of horizontal displacement to apply. A very small float number, such as 0.005.
* @param {number} [y=0.005] - The amount of vertical displacement to apply. A very small float number, such as 0.005.
*
* @return {Phaser.Filters.Displacement} The new Displacement filter controller.
*/
/**
* Adds a Quantize effect.
*
* Quantization reduces the unique number of colors in an image,
* based on some limited number of steps per color channel.
* This is good for creating a retro or stylized effect.
*
* Basic quantization breaks each channel up into a number of `steps`.
* These steps are normally regular. You can bias them towards the top or bottom
* by changing that channel's `gamma` value.
* You can adjust the lowest step, thus all subsequent steps, with the `offset`.
*
* Quantization is done in either RGBA or HSVA space.
* The steps, gamma, and offset always apply in the same order,
* but depending on color mode, they are either applied to
* `[ red, green, blue, alpha ]` or `[ hue, saturation, value, alpha ]`.
*
* The output may optionally be dithered, to eliminate banding
* and create the illusion that there are many more colors in use.
*
* @method Phaser.GameObjects.Components.FilterList#addQuantize
* @since 4.0.0
*
* @param {Phaser.Types.Filters.QuantizeConfig} [config] - The configuration object for the Quantize effect.
*
* @return {this} The new Quantize filter controller.
*/
/**
* The maximum size of the base filter texture.
* Filters may use a larger texture after the base texture is rendered.
* The maximum texture size is at least 4096 in WebGL, based on the hardware.
* You may set this lower to save memory or prevent resizing.
*
* @name Phaser.GameObjects.Components.Filters#maxFilterSize
* @type {Phaser.Math.Vector2}
* @since 4.0.0
* @webglOnly
*/
/**
* Provides methods for enabling WebGL-based per-pixel lighting effects on a Game Object,
* using normal maps to simulate surface depth under dynamic light sources.
*
* When lighting is enabled, the Game Object will respond to lights added to the scene
* via the Lights plugin. This component also supports self-shadowing, which creates
* contact shadows on the surface based on the object's normal map.
*
* This component should only be applied to Game Objects that have RenderNodes, and
* requires the WebGL renderer. It has no effect in Canvas rendering mode.
*
* @namespace Phaser.GameObjects.Components.Lighting
* @webglOnly
* @since 4.0.0
*/
/**
* Configuration object controlling self-shadowing for this Game Object.
* Self-shadowing causes surfaces to cast contact shadows on themselves based on
* the normal map, giving the appearance of depth. It is only active when
* `lighting` is also enabled.
*
* If `enabled` is `null`, the value from the game config option `render.selfShadow`
* is used instead.
*
* This object is used to select and configure the appropriate WebGL shader at render time.
*
* @name Phaser.GameObjects.Components.Lighting#selfShadow
* @type {{ enabled: boolean, penumbra: number, diffuseFlatThreshold: number }}
* @webglOnly
* @since 4.0.0
*/
/**
* The horizontal origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the left of the Game Object.
* Set this value with `setOrigin()`.
*
* @name Phaser.GameObjects.Components.Origin#originX
* @type {number}
* @default 0.5
* @since 3.0.0
*/
/**
* The vertical origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the top of the Game Object.
* Set this value with `setOrigin()`.
*
* @name Phaser.GameObjects.Components.Origin#originY
* @type {number}
* @default 0.5
* @since 3.0.0
*/
/**
* Sets the origin of this Game Object based on the Pivot values in its Frame.
* If the Frame has a custom pivot point defined, the origin is set to match it.
* If the Frame does not have a custom pivot, this method falls back to `setOrigin()`,
* resetting the origin to the default value of 0.5 for both axes.
*
* @method Phaser.GameObjects.Components.Origin#setOriginFromFrame
* @since 3.0.0
*
* @return {this} This Game Object instance.
*/
/**
* The horizontal scroll factor of this Game Object.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken into consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Components.ScrollFactor#scrollFactorX
* @type {number}
* @default 1
* @since 3.0.0
*/
/**
* The vertical scroll factor of this Game Object.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken into consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Components.ScrollFactor#scrollFactorY
* @type {number}
* @default 1
* @since 3.0.0
*/
/**
* Sets the horizontal and vertical scroll factor of this Game Object. If only the `x` value is
* provided, it is applied to both axes. This is a convenience method for setting `scrollFactorX`
* and `scrollFactorY` in a single call.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken into consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @method Phaser.GameObjects.Components.ScrollFactor#setScrollFactor
* @since 3.0.0
*
* @param {number} x - The horizontal scroll factor of this Game Object.
* @param {number} [y=x] - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
*
* @return {this} This Game Object instance.
*/
/**
* Performs the 8 calculations required to create the vertices of
* a quad based on this matrix and the given vertex coordinates.
*
* The result is stored in `TransformMatrix.quad`, which is returned
* from this method.
*
* @method Phaser.GameObjects.Components.TransformMatrix#setQuad
* @since 3.60.0
*
* @param {number} x - The x value of the top-left vertex of the quad.
* @param {number} y - The y value of the top-left vertex of the quad.
* @param {number} xw - The x value of the bottom-right vertex of the quad. This is the x + width.
* @param {number} yh - The y value of the bottom-right vertex of the quad. This is the y + height.
* @param {Float32Array} [quad] - Optional Float32Array to store the results in. Otherwise uses the local quad array.
*
* @return {Float32Array} The quad Float32Array.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Felipe Alfonso <@bitnenfer>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* The horizontal scroll factor of this Container.
*
* The scroll factor controls the influence of the movement of a Camera upon this Container.
*
* When a camera scrolls it will change the location at which this Container is rendered on-screen.
* It does not change the Containers actual position values.
*
* For a Container, setting this value will only update the Container itself, not its children.
* If you wish to change the scrollFactor of the children as well, use the `setScrollFactor` method.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Container.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Container#scrollFactorX
* @type {number}
* @default 1
* @since 3.4.0
*/
/**
* The vertical scroll factor of this Container.
*
* The scroll factor controls the influence of the movement of a Camera upon this Container.
*
* When a camera scrolls it will change the location at which this Container is rendered on-screen.
* It does not change the Containers actual position values.
*
* For a Container, setting this value will only update the Container itself, not its children.
* If you wish to change the scrollFactor of the children as well, use the `setScrollFactor` method.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Container.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Container#scrollFactorY
* @type {number}
* @default 1
* @since 3.4.0
*/
/**
* Sort the contents of this Container so the items are in order based on the given property.
* For example: `sort('alpha')` would sort the elements based on the value of their `alpha` property.
*
* @method Phaser.GameObjects.Container#sort
* @since 3.4.0
*
* @param {string} property - The property to lexically sort by.
* @param {function} [handler] - Provide your own custom handler function. Will receive 2 children which it should compare and return a negative, zero, or positive number.
*
* @return {this} This Container instance.
*/
/**
* Sets the scroll factor of this Container and optionally all of its children.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @method Phaser.GameObjects.Container#setScrollFactor
* @since 3.4.0
*
* @param {number} x - The horizontal scroll factor of this Game Object.
* @param {number} [y=x] - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
* @param {boolean} [updateChildren=false] - Apply this scrollFactor to all Container children as well?
*
* @return {this} This Game Object instance.
*/
/**
* The angle, in radians, by which to skew the DOM Element on the horizontal axis.
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform
*
* @name Phaser.GameObjects.DOMElement#skewX
* @type {number}
* @since 3.17.0
*/
/**
* The angle, in radians, by which to skew the DOM Element on the vertical axis.
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform
*
* @name Phaser.GameObjects.DOMElement#skewY
* @type {number}
* @since 3.17.0
*/
/**
* A Vector4 that contains the 3D rotation of this DOM Element around a fixed axis in 3D space.
*
* The x, y, and z components define the direction of the rotation axis. The w component holds the
* angle of rotation, in the unit defined by the `rotate3dAngle` property (degrees by default).
*
* For more details see the following MDN page:
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
*
* @name Phaser.GameObjects.DOMElement#rotate3d
* @type {Phaser.Math.Vector4}
* @since 3.17.0
*/
/**
* The unit that represents the 3D rotation values. By default this is `deg` for degrees, but can
* be changed to any supported unit. See this page for further details:
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
*
* @name Phaser.GameObjects.DOMElement#rotate3dAngle
* @type {string}
* @since 3.17.0
*/
/**
* The computed display width of this Game Object, based on the `getBoundingClientRect` DOM call.
*
* The property `width` holds the un-scaled width of this DOM Element.
*
* @name Phaser.GameObjects.DOMElement#displayWidth
* @type {number}
* @readonly
* @since 3.17.0
*/
/**
* The computed display height of this Game Object, based on the `getBoundingClientRect` DOM call.
*
* The property `height` holds the un-scaled height of this DOM Element.
*
* @name Phaser.GameObjects.DOMElement#displayHeight
* @type {number}
* @readonly
* @since 3.17.0
*/
/**
* Sets the horizontal and vertical skew values of this DOM Element.
*
* For more information see: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
*
* @method Phaser.GameObjects.DOMElement#setSkew
* @since 3.17.0
*
* @param {number} [x=0] - The angle, in radians, by which to skew the DOM Element on the horizontal axis.
* @param {number} [y=x] - The angle, in radians, by which to skew the DOM Element on the vertical axis.
*
* @return {this} This DOM Element instance.
*/
/**
* Sets the perspective CSS property of the _parent DOM Container_. This determines the distance between the z=0
* plane and the user in order to give a 3D-positioned element some perspective. Each 3D element with
* z > 0 becomes larger; each 3D-element with z < 0 becomes smaller. The strength of the effect is determined
* by the value of this property.
*
* For more information see: https://developer.mozilla.org/en-US/docs/Web/CSS/perspective
*
* **Changing this value changes it globally for all DOM Elements, as they all share the same parent container.**
*
* @method Phaser.GameObjects.DOMElement#setPerspective
* @since 3.17.0
*
* @param {number} value - The perspective value, in pixels, that determines the distance between the z plane and the user.
*
* @return {this} This DOM Element instance.
*/
/**
* The perspective CSS property value of the _parent DOM Container_. This determines the distance between the z=0
* plane and the user in order to give a 3D-positioned element some perspective. Each 3D element with
* z > 0 becomes larger; each 3D-element with z < 0 becomes smaller. The strength of the effect is determined
* by the value of this property.
*
* For more information see: https://developer.mozilla.org/en-US/docs/Web/CSS/perspective
*
* **Changing this value changes it globally for all DOM Elements, as they all share the same parent container.**
*
* @name Phaser.GameObjects.DOMElement#perspective
* @type {number}
* @since 3.17.0
*/
/**
* Creates a native DOM Element, adds it to the parent DOM Container and then binds it to this Game Object,
* so you can control it. The `tagName` should be a string and is passed to `document.createElement`:
*
* ```javascript
* this.add.dom().createElement('div');
* ```
*
* For more details on acceptable tag names see: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
*
* You can also pass in a DOMString or style object to set the CSS on the created element, and an optional `innerText`
* value as well. Here is an example of a DOMString:
*
* ```javascript
* this.add.dom().createElement('div', 'background-color: lime; width: 220px; height: 100px; font: 48px Arial', 'Phaser');
* ```
*
* And using a style object:
*
* ```javascript
* var style = {
* 'background-color': 'lime';
* 'width': '200px';
* 'height': '100px';
* 'font': '48px Arial';
* };
*
* this.add.dom().createElement('div', style, 'Phaser');
* ```
*
* If this Game Object already has an Element, it is removed from the DOM entirely first.
* Any event listeners you may have previously created will need to be re-created after this call.
*
* @method Phaser.GameObjects.DOMElement#createElement
* @since 3.17.0
*
* @param {string} tagName - A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method.
* @param {(string|any)} [style] - Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be read from.
* @param {string} [innerText] - A DOMString that holds the text that will be set as the innerText of the created element.
*
* @return {this} This DOM Element instance.
*/
/**
* The Video Game Object Loop Event.
*
* This event is dispatched when a Video that is currently playing has looped. This only
* happens if the `loop` parameter was specified, or the `setLoop` method was called,
* and if the video has a fixed duration. Video streams, for example, cannot loop, as
* they have no duration.
*
* Looping is based on the result of the Video `timeupdate` event. This event is not
* frame-accurate, due to the way browsers work, so please do not rely on this loop
* event to be time or frame precise.
*
* Listen for it from a Video Game Object instance using `Video.on('loop', listener)`.
*
* @event Phaser.GameObjects.Events#VIDEO_LOOP
* @type {string}
* @since 3.20.0
*
* @param {Phaser.GameObjects.Video} video - The Video Game Object which has looped.
*/
/**
* @author Benjamin D. Richards <benjamindrichards@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Move the start of the gradient.
* You can animate gradients in this way.
*
* Note that the offset effect changes based on shape and repeat mode.
* Conic gradients may appear weird!
*
* Animate the offset from -1 to 1 using mode 1 (TRUNCATE)
* to create a one-time shockwave.
*
* Use mode 2 (SAWTOOTH) or 3 (TRIANGULAR) to create a moving pattern.
*
* @name Phaser.GameObjects.Gradient#offset
* @type {number}
* @default 0
* @since 4.0.0
*/
/**
* The shape mode of the gradient.
* Shapes are based on the `shape` vector.
*
* This can be one of the following:
*
* - 0 (LINEAR): a ribbon where the shape points from one side to the other.
* Commonly used for skies etc.
* - 1 (BILINEAR): like LINEAR, but reflected in both directions.
* Useful for gentle waves, reflections etc.
* - 2 (RADIAL): gradient spreads out from the `start`,
* to the radius described by `shape`.
* Useful for glows, ripples etc.
* - 3 (CONIC_SYMMETRIC): gradient is determined by angle to `shape`,
* going from 0 along the shape vector to 1 opposite it.
* Useful for sharp-looking features or light effects.
* - 4 (CONIC_ASYMMETRIC): gradient is determined by angle to `shape`,
* going from 0 to 1 with a full rotation. This creates a seam.
* Good for creating colors that change with angle,
* like speed meters.
*
* @name Phaser.GameObjects.Gradient#shapeMode
* @type {number}
* @default 0
* @since 4.0.0
*/
/**
* @classdesc
* A Graphics object is a way to draw primitive shapes to your game. Primitives include forms of geometry, such as
* Rectangles, Circles, and Polygons. They also include lines, arcs and curves. When you initially create a Graphics
* object it will be empty.
*
* To draw to it you must first specify a line style or fill style (or both), draw shapes using paths, and finally
* fill or stroke them. For example:
*
* ```javascript
* graphics.lineStyle(5, 0xFF00FF, 1.0);
* graphics.beginPath();
* graphics.moveTo(100, 100);
* graphics.lineTo(200, 200);
* graphics.closePath();
* graphics.strokePath();
* ```
*
* There are also many helpful methods that draw and fill/stroke common shapes for you.
*
* ```javascript
* graphics.lineStyle(5, 0xFF00FF, 1.0);
* graphics.fillStyle(0xFFFFFF, 1.0);
* graphics.fillRect(50, 50, 400, 200);
* graphics.strokeRect(50, 50, 400, 200);
* ```
*
* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or WebGL.
* Under Canvas it will use the HTML Canvas context drawing operations to draw the path.
* Under WebGL the graphics data is decomposed into polygons. Both of these are expensive processes, especially with
* complex shapes.
*
* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help
* performance by calling {@link Phaser.GameObjects.Graphics#generateTexture}. This will 'bake' the Graphics object into
* a Texture, and return it. You can then use this Texture for Sprites or other display objects. If your Graphics object
* updates frequently then you should avoid doing this, as it will constantly generate new textures, which will consume
* memory.
*
* Under WebGL, Graphics uses its own shader which will batch drawing operations.
* Try to keep Graphics objects grouped together so they can be batched together.
* Avoid mixing object types where possible, as each batch will be flushed,
* costing performance.
*
* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful
* in their complexity and quantity of them in your game.
*
* @class Graphics
* @extends Phaser.GameObjects.GameObject
* @memberof Phaser.GameObjects
* @constructor
* @since 3.0.0
*
* @extends Phaser.GameObjects.Components.AlphaSingle
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.Lighting
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.RenderNodes
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
* @extends Phaser.GameObjects.Components.ScrollFactor
*
* @param {Phaser.Scene} scene - The Scene to which this Graphics object belongs.
* @param {Phaser.Types.GameObjects.Graphics.Options} [options] - Options that set the position and default style of this Graphics object.
*/
/**
* Path detail threshold for the WebGL renderer, in pixels.
* Path segments will be combined until the path is complete
* or the segment length is above the threshold.
*
* If the value is negative, the threshold will be taken from the
* game config `render.pathDetailThreshold` property.
*
* This threshold can greatly improve performance on complex shapes.
* It is calculated at render time and does not affect the original
* path data.
* The threshold is evaluated in screen pixels, so if the object is
* scaled up, fine detail will emerge.
*
* @name Phaser.GameObjects.Graphics#pathDetailThreshold
* @type {number}
* @default -1
* @since 4.0.0
*/
/**
* Returns all children in this Group that match the given criteria based on the `property` and `value` arguments.
*
* For example: `getMatching('visible', true)` would return only children that have their `visible` property set.
*
* Optionally, you can specify a start and end index. For example if the Group has 100 elements,
* and you set `startIndex` to 0 and `endIndex` to 50, it would return matches from only
* the first 50.
*
* @method Phaser.GameObjects.Group#getMatching
* @since 3.50.0
*
* @param {string} [property] - The property to test on each array element.
* @param {*} [value] - The value to test the property against. Must pass a strict (`===`) comparison check.
* @param {number} [startIndex] - An optional start index to search from.
* @param {number} [endIndex] - An optional end index to search to.
*
* @return {any[]} An array of matching Group members. The array will be empty if nothing matched.
*/
/**
* Sort the contents of this List so the items are in order based on the given property.
* For example, `sort('alpha')` would sort the List contents based on the value of their `alpha` property.
*
* @method Phaser.GameObjects.Layer#sort
* @since 3.0.0
*
* @param {string} property - The property to lexically sort by.
* @param {function} [handler] - Provide your own custom handler function. Will receive 2 children which it should compare and return a number (negative if the first should come before the second, positive if after, zero if equal).
*
* @return {Phaser.GameObjects.Layer} This List object.
*/
/**
* Get all lights that can be seen by the given Camera.
*
* It will automatically cull lights that are outside the world view of the Camera.
*
* If more lights are returned than supported by the renderer, the lights are then culled
* based on the distance from the center of the camera. Only those closest are rendered.
*
* @method Phaser.GameObjects.LightsManager#getLights
* @since 3.50.0
*
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to cull Lights for.
*
* @return {Phaser.GameObjects.Light[]} The culled Lights.
*/
/**
* @classdesc
* A Nine Slice Game Object allows you to display a texture-based object that
* can be stretched both horizontally and vertically, but that retains
* fixed-sized corners. The dimensions of the corners are set via the
* parameters to this class.
*
* This is extremely useful for UI and button like elements, where you need
* them to expand to accommodate the content without distorting the texture.
*
* The texture you provide for this Game Object should be based on the
* following layout structure:
*
* ```
* A B
* +---+----------------------+---+
* C | 1 | 2 | 3 |
* +---+----------------------+---+
* | | | |
* | 4 | 5 | 6 |
* | | | |
* +---+----------------------+---+
* D | 7 | 8 | 9 |
* +---+----------------------+---+
* ```
*
* When changing this objects width and / or height:
*
* areas 1, 3, 7 and 9 (the corners) will remain unscaled
* areas 2 and 8 will be stretched horizontally only
* areas 4 and 6 will be stretched vertically only
* area 5 will be stretched both horizontally and vertically
*
* You can also create a 3 slice Game Object:
*
* This works in a similar way, except you can only stretch it horizontally.
* Therefore, it requires less configuration:
*
* ```
* A B
* +---+----------------------+---+
* | | | |
* C | 1 | 2 | 3 |
* | | | |
* +---+----------------------+---+
* ```
*
* When changing this objects width (you cannot change its height)
*
* areas 1 and 3 will remain unscaled
* area 2 will be stretched horizontally
*
* The above configuration concept is adapted from the Pixi NineSlicePlane.
*
* To specify a 3 slice object instead of a 9 slice you should only
* provide the `leftWidth` and `rightWidth` parameters. To create a 9 slice
* you must supply all parameters.
*
* The _minimum_ width this Game Object can be is the total of
* `leftWidth` + `rightWidth`. The _minimum_ height this Game Object
* can be is the total of `topHeight` + `bottomHeight`.
* If you need to display this object at a smaller size, you can scale it.
*
* In terms of performance, using a 3 slice Game Object is the equivalent of
* having 3 Sprites in a row. Using a 9 slice Game Object is the equivalent
* of having 9 Sprites in a row. The vertices of this object are all batched
* together and can co-exist with other Sprites and graphics on the display
* list, without incurring any additional overhead.
*
* This Game Object can now populate its values automatically
* if they have been set within Texture Packer 7.1.0 or above and exported with
* the atlas json. If this is the case, you can just create this Game Object without
* specifying anything more than the texture key and frame and it will pull the
* area data from the atlas.
*
* This object does not support trimmed textures from Texture Packer.
* Trimming interferes with the ability to stretch the texture correctly.
*
* @class NineSlice
* @extends Phaser.GameObjects.GameObject
* @memberof Phaser.GameObjects
* @constructor
* @since 3.60.0
*
* @extends Phaser.GameObjects.Components.AlphaSingle
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.GetBounds
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.Origin
* @extends Phaser.GameObjects.Components.RenderNodes
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.Texture
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* @param {number} x - The horizontal position of the center of this Game Object in the world.
* @param {number} y - The vertical position of the center of this Game Object in the world.
* @param {(string|Phaser.Textures.Texture)} texture - The key, or instance of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* @param {(string|number)} [frame] - An optional frame from the Texture this Game Object is rendering with.
* @param {number} [width=256] - The width of the Nine Slice Game Object. You can adjust the width post-creation.
* @param {number} [height=256] - The height of the Nine Slice Game Object. If this is a 3 slice object the height will be fixed to the height of the texture and cannot be changed.
* @param {number} [leftWidth=10] - The size of the left vertical column (A).
* @param {number} [rightWidth=10] - The size of the right vertical column (B).
* @param {number} [topHeight=0] - The size of the top horizontal row (C). Set to zero or undefined to create a 3 slice object.
* @param {number} [bottomHeight=0] - The size of the bottom horizontal row (D). Set to zero or undefined to create a 3 slice object.
* @param {boolean} [tileX=false] - When enabled, the scalable horizontal regions are repeated across the object instead of being stretched. Each tile is still slightly stretched so that it remains visible in full, which may cause minor distortion but far less than pure stretching. The texture should be seamless to avoid visible artifacts between tiles.
* @param {boolean} [tileY=false] - When enabled, the scalable vertical regions are repeated across the object instead of being stretched. Each tile is still slightly stretched so that it remains visible in full, which may cause minor distortion but far less than pure stretching. The texture should be seamless to avoid visible artifacts between tiles.
*/
/**
* Recalculates all of the vertices in this Nine Slice Game Object
* based on the `leftWidth`, `rightWidth`, `topHeight`, `bottomHeight`,
* `tileX` and `tileY` properties, combined with the Game Object size.
*
* This method is called automatically when this object is created
* or if its origin is changed.
*
* You should not typically need to call this method directly, but it
* is left public should you find a need to modify one of those properties
* after creation.
*
* @method Phaser.GameObjects.NineSlice#updateVertices
* @since 3.60.0
*/
/**
* Internally updates the UV coordinates across all vertices of the
* given quad offset, based on the frame size.
*
* You should not typically need to call this method directly, but it
* is left public should an extended class require it.
*
* @method Phaser.GameObjects.NineSlice#updateQuadUVs
* @since 3.60.0
*
* @param {number} offset - The offset in the vertices array of the quad to update.
* @param {number} u1 - The top-left U coordinate of the quad, in the range 0 to 1.
* @param {number} v1 - The top-left V coordinate of the quad, in the range 0 to 1.
* @param {number} u2 - The bottom-right U coordinate of the quad, in the range 0 to 1.
* @param {number} v2 - The bottom-right V coordinate of the quad, in the range 0 to 1.
*/
/**
* The horizontal origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the left of the Game Object.
*
* @name Phaser.GameObjects.NineSlice#originX
* @type {number}
* @since 3.60.0
*/
/**
* The vertical origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the top of the Game Object.
*
* @name Phaser.GameObjects.NineSlice#originY
* @type {number}
* @since 3.60.0
*/
/**
* A Nine Slice Game Object allows you to display a texture-based object that
* can be stretched both horizontally and vertically, but that retains
* fixed-sized corners. The dimensions of the corners are set via the
* parameters to this class.
*
* This is extremely useful for UI and button like elements, where you need
* them to expand to accommodate the content without distorting the texture.
*
* The texture you provide for this Game Object should be based on the
* following layout structure:
*
* ```
* A B
* +---+----------------------+---+
* C | 1 | 2 | 3 |
* +---+----------------------+---+
* | | | |
* | 4 | 5 | 6 |
* | | | |
* +---+----------------------+---+
* D | 7 | 8 | 9 |
* +---+----------------------+---+
* ```
*
* When changing this object's width and / or height:
*
* areas 1, 3, 7 and 9 (the corners) will remain unscaled
* areas 2 and 8 will be stretched horizontally only
* areas 4 and 6 will be stretched vertically only
* area 5 will be stretched both horizontally and vertically
*
* You can also create a 3 slice Game Object:
*
* This works in a similar way, except you can only stretch it horizontally.
* Therefore, it requires less configuration:
*
* ```
* A B
* +---+----------------------+---+
* | | | |
* C | 1 | 2 | 3 |
* | | | |
* +---+----------------------+---+
* ```
*
* When changing this object's width (you cannot change its height)
*
* areas 1 and 3 will remain unscaled
* area 2 will be stretched horizontally
*
* The above configuration concept is adapted from the Pixi NineSlicePlane.
*
* To specify a 3 slice object instead of a 9 slice you should only
* provide the `leftWidth` and `rightWidth` parameters. To create a 9 slice
* you must supply all parameters.
*
* The _minimum_ width this Game Object can be is the total of
* `leftWidth` + `rightWidth`. The _minimum_ height this Game Object
* can be is the total of `topHeight` + `bottomHeight`.
* If you need to display this object at a smaller size, you can scale it.
*
* In terms of performance, using a 3 slice Game Object is the equivalent of
* having 3 Sprites in a row. Using a 9 slice Game Object is the equivalent
* of having 9 Sprites in a row. The vertices of this object are all batched
* together and can co-exist with other Sprites and graphics on the display
* list, without incurring any additional overhead.
*
* As of Phaser 3.60 this Game Object is WebGL only.
*
* @method Phaser.GameObjects.GameObjectFactory#nineslice
* @webglOnly
* @since 3.60.0
*
* @param {number} x - The horizontal position of the center of this Game Object in the world.
* @param {number} y - The vertical position of the center of this Game Object in the world.
* @param {(string|Phaser.Textures.Texture)} texture - The key, or instance of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* @param {(string|number)} [frame] - An optional frame from the Texture this Game Object is rendering with.
* @param {number} [width=256] - The width of the Nine Slice Game Object. You can adjust the width post-creation.
* @param {number} [height=256] - The height of the Nine Slice Game Object. If this is a 3 slice object the height will be fixed to the height of the texture and cannot be changed.
* @param {number} [leftWidth=10] - The size of the left vertical column (A).
* @param {number} [rightWidth=10] - The size of the right vertical column (B).
* @param {number} [topHeight=0] - The size of the top horizontal row (C). Set to zero or undefined to create a 3 slice object.
* @param {number} [bottomHeight=0] - The size of the bottom horizontal row (D). Set to zero or undefined to create a 3 slice object.
* @param {boolean} [tileX=false] - Whether to tile the horizontal regions instead of stretching them. Some stretching will still occur to keep the tile count a whole number.
* @param {boolean} [tileY=false] - Whether to tile the vertical regions instead of stretching them. Some stretching will still occur to keep the tile count a whole number.
*
* @return {Phaser.GameObjects.NineSlice} The Game Object that was created.
*/
/**
* Configures the emit and update callbacks for this color op based on the
* current `method` value. When a color array is present (method 9), it
* decomposes each packed hex color in `propertyValue` into separate red,
* green, and blue component arrays, sets up the linear easing and
* interpolation functions, and assigns the eased emit and update handlers.
* If no color value is set (method 0), the default no-op handlers are used.
*
* @method Phaser.GameObjects.Particles.EmitterColorOp#setMethods
* @since 3.60.0
*
* @return {this} This Emitter Op object.
*/
/**
* An `onUpdate` callback that returns an interpolated packed RGB color value
* across the configured color array, based on the particle's current
* normalized lifetime.
*
* @method Phaser.GameObjects.Particles.EmitterColorOp#easeValueUpdate
* @since 3.60.0
*
* @param {Phaser.GameObjects.Particles.Particle} particle - The particle.
* @param {string} key - The name of the property.
* @param {number} t - The current normalized lifetime of the particle, between 0 (birth) and 1 (death).
*
* @return {number} The new value of the property.
*/
/**
* Update the {@link Phaser.GameObjects.Particles.EmitterOp#onEmit} and
* {@link Phaser.GameObjects.Particles.EmitterOp#onUpdate} callbacks based on the method returned
* from `getMethod`. The method is stored in the `EmitterOp.method` property
* and is a number between 0 and 9 inclusively.
*
* @method Phaser.GameObjects.Particles.EmitterOp#setMethods
* @since 3.0.0
*
* @return {this} This Emitter Op object.
*/
/**
* Takes a Particle and updates its velocity based on the gravitational force exerted
* by this Gravity Well. The force is calculated using the squared distance between the
* particle and the well, clamped by `epsilon` to avoid extreme forces at very close range,
* then applied to the particle's horizontal and vertical velocity components.
*
* @method Phaser.GameObjects.Particles.GravityWell#update
* @since 3.0.0
*
* @param {Phaser.GameObjects.Particles.Particle} particle - The Particle to update.
* @param {number} delta - The delta time in ms.
* @param {number} step - The delta value divided by 1000.
*/
/**
* If set, either via the Emitter config, or by directly setting this property,
* the Particle Emitter will stop emitting particles once this total has been
* reached. It will then enter a 'stopped' state, firing the `STOP`
* event. Note that entering a stopped state doesn't mean all the particles
* have finished, just that it's not emitting any further ones.
*
* To know when the final particle expires, listen for the COMPLETE event.
*
* Use this if you wish to launch an exact number of particles and then stop
* your emitter afterwards.
*
* The counter is reset each time the `ParticleEmitter.start` method is called.
*
* 0 means the emitter will not stop based on total emitted particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#stopAfter
* @type {number}
* @default 0
* @since 3.60.0
*/
/**
* The number of milliseconds this emitter will emit particles for when in flow mode,
* before it stops emission. A value of 0 (the default) means there is no duration.
*
* When the duration expires the `STOP` event is emitted. Note that entering a
* stopped state doesn't mean all the particles have finished, just that it's
* not emitting any further ones.
*
* To know when the final particle expires, listen for the COMPLETE event.
*
* The counter is reset each time the `ParticleEmitter.start` method is called.
*
* 0 means the emitter will not stop based on duration.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#duration
* @type {number}
* @default 0
* @since 3.60.0
*/
/**
* Optionally sort the particles before they render based on this
* property. The property must exist on the `Particle` class, such
* as `y`, `lifeT`, `scaleX`, etc.
*
* When set this overrides the `particleBringToTop` setting.
*
* To reset this and disable sorting, set this property to an empty string.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#sortProperty
* @type {string}
* @since 3.60.0
*/
/**
* Sets a callback to be used to sort the particles before rendering each frame.
*
* This allows you to define your own logic and behavior in the callback.
*
* The callback will be sent two parameters: the two Particles being compared,
* and must adhere to the criteria of the `compareFn` in `Array.sort`:
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description
*
* Call this method with no parameters to reset the sort callback.
*
* Setting your own callback will override both the `particleBringToTop` and
* `sortProperty` settings of this Emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setSortCallback
* @since 3.60.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleSortCallback} [callback] - The callback to invoke when the particles are sorted. Leave undefined to reset to the default.
*
* @return {this} This Particle Emitter.
*/
/**
* Returns a bounds Rectangle calculated from the bounds of all currently
* _active_ Particles in this Emitter. If this Emitter has only just been
* created and not yet rendered, then calling this method will return a Rectangle
* with a max safe integer for dimensions. Use the `advance` parameter to
* avoid this.
*
* Typically it takes a few seconds for a flow Emitter to 'warm up'. You can
* use the `advance` and `delta` parameters to force the Emitter to
* 'fast forward' in time to try and allow the bounds to be more accurate,
* as it will calculate the bounds based on the particle bounds across all
* timesteps, giving a better result.
*
* You can also use the `padding` parameter to increase the size of the
* bounds. Emitters with a lot of randomness in terms of direction or lifespan
* can often return a bounds smaller than their possible maximum. By using
* the `padding` (and `advance` if needed) you can help limit this.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#getBounds
* @since 3.60.0
*
* @param {number} [padding] - The amount of padding, in pixels, to add to the bounds Rectangle.
* @param {number} [advance] - The number of ms to advance the Particle Emitter by. Defaults to 0, i.e. not used.
* @param {number} [delta] - The amount of delta to use for each step. Defaults to 1000 / 60.
* @param {Phaser.Geom.Rectangle} [output] - The Rectangle to store the results in. If not given a new one will be created.
*
* @return {Phaser.Geom.Rectangle} A Rectangle containing the calculated bounds of this Emitter.
*/
/**
* Creates a new Particle Emitter Game Object and returns it.
*
* A Particle Emitter is a Game Object that produces a stream of particles based on a
* configuration object. It can be used to create effects such as explosions, fire, smoke,
* rain, or any other particle-based visual. The emitter is added to the Scene and managed
* as a standard Game Object, supporting transforms, depth, and other common properties.
*
* Prior to Phaser v3.60 this function would create a `ParticleEmitterManager`. These were removed
* in v3.60 and replaced with creating a `ParticleEmitter` instance directly. Please see the
* updated function parameters and class documentation for more details.
*
* Note: This method will only be available if the Particles Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectCreator#particles
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCreatorConfig} config - The configuration object this Game Object will use to create itself.
* @param {boolean} [addToScene] - Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} The Game Object that was created.
*/
/**
* The Particle Processor update method should be overridden by your own
* method and handle the processing of the particles, typically modifying
* their velocityX/Y values based on the criteria of this processor.
*
* @method Phaser.GameObjects.Particles.ParticleProcessor#update
* @since 3.60.0
*
* @param {Phaser.GameObjects.Particles.Particle} particle - The Particle to update.
* @param {number} delta - The delta time in ms.
* @param {number} step - The delta value divided by 1000.
* @param {number} t - The current normalized lifetime of the particle, between 0 (birth) and 1 (death).
*/
/**
* Takes the given texture key and frame and then stamps it at the given
* x and y coordinates. You can use the optional 'config' argument to provide
* lots more options about how the stamp is applied, including the alpha,
* tint, angle, scale and origin.
*
* By default, the frame will stamp on the x/y coordinates based on its center.
*
* If you wish to stamp from the top-left, set the config `originX` and
* `originY` properties both to zero.
*
* This method ignores the `camera` property of the Dynamic Texture.
*
* @method Phaser.GameObjects.RenderTexture#stamp
* @since 3.60.0
*
* @param {string} key - The key of the texture to be used, as stored in the Texture Manager.
* @param {(string|number)} [frame] - The name or index of the frame within the Texture. Set to `null` to skip this argument if not required.
* @param {number} [x=0] - The x position to draw the frame at.
* @param {number} [y=0] - The y position to draw the frame at.
* @param {Phaser.Types.Textures.StampConfig} [config] - The stamp configuration object, allowing you to set the alpha, tint, angle, scale and origin of the stamp.
*
* @return {this} This Render Texture instance.
*/
/**
* Draws the given object, or an array of objects, to this RenderTexture.
*
* It can accept any of the following:
*
* * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
* * Tilemap Layers.
* * A Group. The contents of which will be iterated and drawn in turn.
* * A Container. The contents of which will be iterated fully, and drawn in turn.
* * A Scene Display List. Pass in `Scene.children` to draw the whole list.
* * Another Dynamic Texture, or a Render Texture.
* * A Texture Frame instance.
* * A string. This is used to look-up the texture from the Texture Manager.
*
* Note 1: You cannot draw a Render Texture to itself.
*
* Note 2: GameObjects will use the camera, while textures and frames will not.
* Textures and frames are drawn using the `stamp` method.
*
* If passing in a Group or Container it will only draw children that return `true`
* when their `willRender()` method is called. I.e. a Container with 10 children,
* 5 of which have `visible=false` will only draw the 5 visible ones.
*
* If passing in an array of Game Objects it will draw them all, regardless if
* they pass a `willRender` check or not.
*
* You can pass in a string in which case it will look for a texture in the Texture
* Manager matching that string, and draw the base frame. If you need to specify
* exactly which frame to draw then use the method `drawFrame` instead.
*
* You can pass in the `x` and `y` coordinates to draw the objects at. The use of
* the coordinates differ based on what objects are being drawn. If the object is
* a Group, Container or Display List, the coordinates are _added_ to the positions
* of the children. For all other types of object, the coordinates are exact.
* For textures and frames, the `x` and `y` values are the middle of the texture.
*
* The `alpha` and `tint` values are only used by Texture Frames.
* Game Objects use their own alpha and tint values when being drawn.
*
* @method Phaser.GameObjects.RenderTexture#draw
* @since 3.2.0
*
* @param {any} entries - Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these.
* @param {number} [x=0] - The x position to draw the Frame at, or the offset applied to the object.
* @param {number} [y=0] - The y position to draw the Frame at, or the offset applied to the object.
* @param {number} [alpha=1] - The alpha value. Only used when drawing Texture Frames to this texture. Game Objects use their own alpha.
* @param {number} [tint=0xffffff] - The tint color value. Only used when drawing Texture Frames to this texture. Game Objects use their own tint. WebGL only.
*
* @return {this} This Render Texture instance.
*/
/**
* Takes the given Texture Frame and draws it to this Dynamic Texture as a fill pattern,
* i.e. in a grid-layout based on the frame dimensions.
* It uses a `TileSprite` internally to draw the frame repeatedly.
*
* Textures are referenced by their string-based keys, as stored in the Texture Manager.
*
* You can optionally provide a position, width, height, alpha and tint value to apply to
* the frames before they are drawn. The position controls the top-left where the repeating
* fill will start from. The width and height control the size of the filled area.
*
* The position can be negative if required, but the dimensions cannot.
*
* This method respects the camera settings of the Dynamic Texture.
*
* @method Phaser.GameObjects.RenderTexture#repeat
* @since 3.60.0
*
* @param {string} key - The key of the texture to be used, as stored in the Texture Manager.
* @param {(string|number)} [frame] - The name or index of the frame within the Texture. Set to `null` to skip this argument if not required.
* @param {number} [x=0] - The x position to start drawing the frames from (can be negative to offset).
* @param {number} [y=0] - The y position to start drawing the frames from (can be negative to offset).
* @param {number} [width=this.width] - The width of the area to repeat the frame within. Defaults to the width of this Dynamic Texture.
* @param {number} [height=this.height] - The height of the area to repeat the frame within. Defaults to the height of this Dynamic Texture.
* @param {Phaser.Types.GameObjects.TileSprite.TileSpriteConfig} [config] - The configuration object for the TileSprite which repeats the texture, allowing you to set further properties on it.
*
* @return {this} This Render Texture instance.
*/
/**
* An array containing the vertices data for this Rope.
*
* This data is calculated automatically in the `updateVertices` method, based on the points provided.
*
* @name Phaser.GameObjects.Rope#vertices
* @type {Float32Array}
* @since 3.23.0
*/
/**
* An array containing the uv data for this Rope.
*
* This data is calculated automatically in the `setPoints` method, based on the points provided.
*
* @name Phaser.GameObjects.Rope#uv
* @type {Float32Array}
* @since 3.23.0
*/
/**
* Sets the points used by this Rope.
*
* The points should be provided as an array of Vector2, or vector2-like objects (i.e. those with public x/y properties).
*
* Each point corresponds to one segment of the Rope. The more points in the array, the more segments the rope has.
*
* Point coordinates are given in local-space, not world-space, and are directly related to the size of the texture
* this Rope object is using.
*
* For example, a Rope using a 512 px wide texture, split into 4 segments (128px each) would use the following points:
*
* ```javascript
* rope.setPoints([
* { x: 0, y: 0 },
* { x: 128, y: 0 },
* { x: 256, y: 0 },
* { x: 384, y: 0 }
* ]);
* ```
*
* Or, you can provide an integer to do the same thing:
*
* ```javascript
* rope.setPoints(4);
* ```
*
* Which will divide the Rope into 4 equally sized segments based on the frame width.
*
* Note that calling this method with a different number of points than the Rope has currently will
* _reset_ the color and alpha values, unless you provide them as arguments to this method.
*
* @method Phaser.GameObjects.Rope#setPoints
* @since 3.23.0
*
* @param {(number|Phaser.Types.Math.Vector2Like[])} [points=2] - An array containing the vertices data for this Rope, or a number that indicates how many segments to split the texture frame into. If none is provided a simple quad is created.
* @param {(number|number[])} [colors] - Either a single color value, or an array of values.
* @param {(number|number[])} [alphas] - Either a single alpha value, or an array of values.
*
* @return {this} This Game Object instance.
*/
/**
* Updates all of the UVs based on the Rope.points and `flipX` and `flipY` settings.
*
* @method Phaser.GameObjects.Rope#updateUVs
* @since 3.23.0
*
* @return {this} This Game Object instance.
*/
/**
* Updates the vertices based on the Rope points.
*
* This method is called automatically during rendering if `Rope.dirty` is `true`, which is set
* by the `setPoints` and `setDirty` methods. You should flag the Rope as being dirty if you modify
* the Rope points directly.
*
* @method Phaser.GameObjects.Rope#updateVertices
* @since 3.23.0
*
* @return {this} This Game Object instance.
*/
/**
* Sets the fillStyle on the target context based on the given Shape.
*
* @method Phaser.GameObjects.Shape#FillStyleCanvas
* @since 3.13.0
* @private
*
* @param {CanvasRenderingContext2D} ctx - The context to set the fill style on.
* @param {Phaser.GameObjects.Shape} src - The Game Object to set the fill style from.
* @param {number} [altColor] - An alternative color to render with.
* @param {number} [altAlpha] - An alternative alpha to render with.
*/
/**
* Sets the strokeStyle and lineWidth on the target context based on the given Shape.
*
* @method Phaser.GameObjects.Shape#LineStyleCanvas
* @since 3.13.0
* @private
*
* @param {CanvasRenderingContext2D} ctx - The context to set the stroke style on.
* @param {Phaser.GameObjects.Shape} src - The Game Object to set the stroke style from.
* @param {number} [altColor] - An alternative color to render with.
* @param {number} [altAlpha] - An alternative alpha to render with.
*/
/**
* Updates the width and height of the Line based on its geometry.
*
* @method Phaser.GameObjects.Line#updateSize
* @private
* @since 4.2.0
*
* @return {this} This Line instance.
*/
/**
* A texture containing the frame data for the SpriteGPULayer.
* This is used by the vertex shader.
*
* The texture is composed of pixel strides, where each stride
* is interpreted as 6 16-bit unsigned integers,
* representing the x, y, width, height, and origin x and y of a frame.
* The texture will be up to 4096 pixels wide and as tall as necessary.
*
* There are two sets of data in the texture: frames and animations.
* Frames are taken from the `texture`.
* Animations are defined by calling `setAnimations`,
* and consist of runs of frames suited to shader animation.
* Although the texture will be regenerated by `setAnimations`,
* the frames are stored first, so their indices won't change.
*
* If you change the `texture` of this layer, you will need to
* regenerate this by calling `generateFrameDataTexture`.
*
* @name Phaser.GameObjects.SpriteGPULayer#frameDataTexture
* @type {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper}
* @since 4.0.0
*/
/**
* @classdesc
* A Stencil Game Object.
*
* A Stencil is a special type of Game Object used to place stencils over the canvas.
* You can use it to efficiently control where subsequent objects are rendered.
* It is WebGL-only.
* Study the documentation carefully to understand how it works.
*
* A Stencil is an extended Container Game Object.
* It contains a list of child Game Objects to render to the stencil buffer.
* Think of these as opaque sheets of card held up over the canvas,
* preventing anything from being drawn through them.
*
* The stencil buffer is provided by WebGL.
* It is available if the game render config set `stencil` to `true`.
* It is an 8-bit attachment to framebuffers, like an extra alpha channel.
* But if the stencil channel is not 0 at a pixel, WebGL will skip rendering that pixel.
* There are no degrees of transparency, only on or off.
*
* When you draw objects with alpha to a Stencil,
* a special `alphaStrategy` is used. Compatible shaders switch from rendering
* alpha, to discarding fragments based on their alpha value.
* By default, this uses dithering to preserve alpha gradients.
* You can change `stencilAlphaStrategy` to a threshold value to instead
* discard without dithering.
* If `stencilAlphaStrategy` is `'keep'`,
* or the child's shader does not support alpha strategies,
* transparent pixels will be drawn as opaque to the stencil buffer!
* This is rarely what you want.
* Fragment shaders must `discard` fragments for them to be transparent to the stencil buffer.
*
* By default, most Phaser shaders support alpha strategies.
* Notable exceptions include:
*
* - PointLight (additive lighting)
* - Shader game objects, and extended classes like Noise
*
* To apply an alpha strategy without a compatible shader,
* force stencil composition by setting `stencilCompositeCheck` to `true`.
* This will composite the stencil contents to a framebuffer,
* which is rendered using a compatible shader.
*
* Stencils are drawn as order-independent layers.
* You can add or remove layers in sequence using `addLayer` and `removeLayer`.
* Each layer adds or subtracts 1 from the stencil buffer.
* Only when the stencil is 0 at a pixel will anything be drawn there.
* (This 0-test is a rule set by the renderer's base DrawingContext.)
* Note that overlapping geometry within the same Stencil is additive,
* and can adjust the layer by more than 1 in aggregate.
* The results can be surprising, so try to avoid overlaps.
*
* You can invert the stencil by setting `stencilInvert` to `true`.
* This will use an extra draw call to invert the stencil:
* it adds a layer everywhere that the children would not draw.
* It is more efficient to render a shape that covers the whole area you wish to stencil,
* but if that's not possible, you can use this.
* Inversion makes it possible to render to parts of the screen not touched
* by child geometry.
* It works by filling the camera, then drawing the child stencil in reverse.
*
* You can remove the stencil by using {@link Phaser.GameObjects.StencilReference}.
* This object copies a target Stencil, and re-renders it
* with different stencil options, elsewhere in the display list.
* This is an efficient way to re-use stencil geometry.
*
* You can also clear the stencil by setting `stencilLayerMode` to `clear`.
* It replaces all stencil buffer values with the `stencilClearValue`.
* This should normally set them back to 0 so everything renders again.
* This destroys all layer information.
* It does not use the child list.
* Be careful not to mess up your scene this way.
*
* Set `stencilLayerMode` to `clearRegion` to fill a region
* of the stencil buffer defined by the children, with the `stencilClearValue`.
* This can be used as a selective eraser, or to set a region to a specific value.
*
* You cannot invert the stencil if the `stencilLayerMode` is `clear` or `clearRegion`.
*
* Sequential stencil layers combine and persist,
* because they are drawn to the stencil buffer and stay there until the next frame.
* Do not add too many layers, though. There are only 8 bits in the stencil buffer,
* so it only safely supports 255 layers.
* If you go over this limit, the buffer wraps back to 0.
* You can still add and remove layers in this case,
* and they will continue to be accurately tracked,
* but layer 256 (and subsequent multiples of 256) will be effectively 0 and allow drawing.
* The same applies if you remove layers below 0: it wraps back to 255
* and prevents drawing.
*
* Deactivate `stencilValueWrap` to prevent the stencil buffer from wrapping.
* This is useful when defining stencils with subtraction,
* and you don't want to underflow from 0 to 255.
* For example, you can use one stencil in `clearRegion` to define a value,
* then use another stencil in `subtractLayer` to erase parts of that region.
* But be careful when using stencils for different purposes:
* if you mix stencil data, you will get unexpected results.
*
* Nested stencils are a separate concern.
* If you add a Stencil as the child of another Stencil,
* the parent Stencil will composite its contents to a framebuffer,
* including child stencils.
* This effectively traps the child stencil in the framebuffer,
* and only the final composite from the framebuffer needs to be considered.
* It is used as the source for the stencil, subject to alpha strategy.
* This requires extra draw calls to composite,
* and framebuffers have poor anti-aliasing quality,
* so you should avoid nesting stencils unless you know what you are doing.
*
* To determine whether the stencil needs to composite to a framebuffer,
* it runs a check before rendering (`'auto'` mode).
* If you know the answer already,
* or if you have a custom game object that Phaser doesn't understand,
* you can set `stencilCompositeCheck` to `true` or `false`
* to skip the auto check.
* If you set it to `false`, it will never composite,
* and any child stencils may render in unexpected ways.
* (Generally, they will appear backwards from what you expect:
* child stencils will not affect the parent stencil, but things drawn later.)
*
* Best practice: use few stencils and don't nest them.
*
* Stencil is best used for efficient, sharp-edged, reused masks.
* You can draw a stencil once, and it will affect everything that is drawn later.
* Its rendering cost is minimal: it is just the draw cost of its children.
* This can be as low as 1 call.
* If there are nested stencils, it will take more calls for the framebuffer.
*
* If you need better quality alpha handling, consider using a Mask filter instead.
* Filters have a higher rendering cost, and apply to just 1 object at a time,
* but they have the best quality.
* (And you can apply them to Containers, to cheat the object limitation.)
*
* @class Stencil
* @extends Phaser.GameObjects.Container
* @extends Phaser.GameObjects.Components.StencilModifier
* @memberof Phaser.GameObjects
* @constructor
* @since 4.2.0
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs.
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {Phaser.GameObjects.GameObject[]} [children] - An optional array of Game Objects to add to the Stencil.
* @param {Phaser.Types.GameObjects.Stencil.StencilOptions} [options] - The options for the Stencil.
*/
/**
* The stencil render step.
* This is an internal function, which is automatically assigned;
* you should not call it directly.
*
* This runs before other render steps,
* so it can set up the drawing context to render properly.
* It delegates to the appropriate render step function based on the `stencilLayerMode`.
*
* @method Phaser.GameObjects.Stencil#stencilRenderStep
* @webglOnly
* @since 4.2.0
* @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
* @param {Phaser.GameObjects.GameObject} gameObject - The Game Object being rendered in this call.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
* @param {Phaser.GameObjects.Components.TransformMatrix} [parentMatrix] - This transform matrix is defined if the game object is nested
* @param {number} [renderStep=0] - The index of this function in the Game Object's list of render processes. Used to support multiple rendering functions.
* @param {Phaser.GameObjects.GameObject[]} [displayList] - The display list which is currently being rendered.
* @param {number} [displayListIndex] - The index of the Game Object within the display list.
*/
/**
* @classdesc
* A Text Game Object.
*
* Text objects work by creating their own internal hidden Canvas and then renders text to it using
* the standard Canvas `fillText` API. It then creates a texture from this canvas which is rendered
* to your game during the render pass.
*
* Because it uses the Canvas API you can take advantage of all the features this offers, such as
* applying gradient fills to the text, or strokes, shadows and more. You can also use custom fonts
* loaded externally, such as Google or TypeKit Web fonts.
*
* **Important:** The font name must be quoted if it contains certain combinations of digits or
* special characters, either when creating the Text object, or when setting the font via `setFont`
* or `setFontFamily`, e.g.:
*
* ```javascript
* this.add.text(0, 0, 'Hello World', { fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif' });
* ```
*
* ```javascript
* this.add.text(0, 0, 'Hello World', { font: '"Press Start 2P"' });
* ```
*
* You can only display fonts that are currently loaded and available to the browser: therefore fonts must
* be pre-loaded. Phaser does not do this for you, so you will require the use of a 3rd party font loader,
* or have the fonts readily available in the CSS on the page in which your Phaser game resides.
*
* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts
* across mobile browsers.
*
* A note on performance: Every time the contents of a Text object changes, i.e. changing the text being
* displayed, or the style of the text, it needs to remake the Text canvas, and if on WebGL, re-upload the
* new texture to the GPU. This can be an expensive operation if used often, or with large quantities of
* Text objects in your game. If you run into performance issues you would be better off using Bitmap Text
* instead, as it benefits from batching and avoids expensive Canvas API calls.
*
* @class Text
* @extends Phaser.GameObjects.GameObject
* @memberof Phaser.GameObjects
* @constructor
* @since 3.0.0
*
* @extends Phaser.GameObjects.Components.Alpha
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.ComputedSize
* @extends Phaser.GameObjects.Components.Crop
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.Flip
* @extends Phaser.GameObjects.Components.GetBounds
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.Origin
* @extends Phaser.GameObjects.Components.RenderNodes
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.Tint
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {(string|string[])} text - The text this Text object will display.
* @param {Phaser.Types.GameObjects.Text.TextStyle} style - The text style configuration object.
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Valid_family_names
*/
/**
* Set the font.
*
* If a string is given, the font family is set.
*
* If an object is given, the `fontFamily`, `fontSize` and `fontStyle`
* properties of that object are set.
*
* **Important:** The font name must be quoted if it contains certain combinations of digits or
* special characters:
*
* ```javascript
* Text.setFont('"Press Start 2P"');
* ```
*
* Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all
* quoted properly, too:
*
* ```javascript
* Text.setFont('Georgia, "Goudy Bookletter 1911", Times, serif');
* ```
*
* @method Phaser.GameObjects.Text#setFont
* @since 3.0.0
*
* @param {string} font - The font family or font settings to set.
*
* @return {this} This Text object.
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Valid_family_names
*/
/**
* Set the font family.
*
* **Important:** The font name must be quoted if it contains certain combinations of digits or
* special characters:
*
* ```javascript
* Text.setFontFamily('"Press Start 2P"');
* ```
*
* Equally, if you wish to provide a list of fallback fonts, then you should ensure they are all
* quoted properly, too:
*
* ```javascript
* Text.setFontFamily('Georgia, "Goudy Bookletter 1911", Times, serif');
* ```
*
* @method Phaser.GameObjects.Text#setFontFamily
* @since 3.0.0
*
* @param {string} family - The font family.
*
* @return {this} This Text object.
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Valid_family_names
*/
/**
* Set the fill style to be used by the Text object.
*
* This can be any valid CanvasRenderingContext2D fillStyle value, such as
* a color (in hex, rgb, rgba, hsl or named values), a gradient or a pattern.
*
* See the [MDN fillStyle docs](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle) for more details.
*
* @method Phaser.GameObjects.Text#setFill
* @since 3.0.0
*
* @param {(string|CanvasGradient|CanvasPattern)} color - The text fill style. Can be any valid CanvasRenderingContext `fillStyle` value.
*
* @return {this} This Text object.
*/
/**
* The horizontal origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the left of the Game Object.
*
* @name Phaser.GameObjects.Text#originX
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* The vertical origin of this Game Object.
* The origin maps the relationship between the size and position of the Game Object.
* The default value is 0.5, meaning all Game Objects are positioned based on their center.
* Setting the value to 0 means the position now relates to the top of the Game Object.
*
* @name Phaser.GameObjects.Text#originY
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* Creates a new Text Game Object and adds it to the Scene.
*
* The Text object renders one or more lines of styled text to an internal hidden Canvas, which is
* then uploaded as a texture and displayed within the Scene.
*
* Text objects work by creating their own internal hidden Canvas and then renders text to it using
* the standard Canvas `fillText` API. It then creates a texture from this canvas which is rendered
* to your game during the render pass.
*
* Because it uses the Canvas API you can take advantage of all the features this offers, such as
* applying gradient fills to the text, or strokes, shadows and more. You can also use custom fonts
* loaded externally, such as Google or TypeKit Web fonts.
*
* You can only display fonts that are currently loaded and available to the browser: therefore fonts must
* be pre-loaded. Phaser does not do this for you, so you will require the use of a 3rd party font loader,
* or have the fonts already available in the CSS on the page in which your Phaser game resides.
*
* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts
* across mobile browsers.
*
* A note on performance: Every time the contents of a Text object changes, i.e. changing the text being
* displayed, or the style of the text, it needs to remake the Text canvas, and if on WebGL, re-upload the
* new texture to the GPU. This can be an expensive operation if used often, or with large quantities of
* Text objects in your game. If you run into performance issues you would be better off using Bitmap Text
* instead, as it benefits from batching and avoids expensive Canvas API calls.
*
* Note: This method will only be available if the Text Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectFactory#text
* @since 3.0.0
*
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {(string|string[])} text - The text this Text object will display.
* @param {Phaser.Types.GameObjects.Text.TextStyle} [style] - The Text style configuration object.
*
* @return {Phaser.GameObjects.Text} The Game Object that was created.
*/
/**
* @classdesc
* A Video Game Object.
*
* This Game Object is capable of handling playback of a video file, video stream or media stream.
*
* You can optionally 'preload' the video into the Phaser Video Cache:
*
* ```javascript
* preload () {
* this.load.video('ripley', 'assets/aliens.mp4');
* }
*
* create () {
* this.add.video(400, 300, 'ripley');
* }
* ```
*
* You don't have to 'preload' the video. You can also play it directly from a URL:
*
* ```javascript
* create () {
* this.add.video(400, 300).loadURL('assets/aliens.mp4');
* }
* ```
*
* To all intents and purposes, a video is a standard Game Object, just like a Sprite. And as such, you can do
* all the usual things to it, such as scaling, rotating, cropping, tinting, making interactive, giving a
* physics body, etc.
*
* Transparent videos are also possible via the WebM file format. Providing the video file has was encoded with
* an alpha channel, and providing the browser supports WebM playback (not all of them do), then it will render
* in-game with full transparency.
*
* Transparent videos are supported by the HEVC (H.265) codec,
* but only on some devices and browsers, and sometimes the alpha channel is ignored,
* which can be a problem if you're aiming for a consistent experience.
* We advise against relying on HEVC.
*
* Playback is handled entirely via the Request Video Frame API, which is supported by most modern browsers.
* A polyfill is provided for older browsers.
*
* ### Autoplaying Videos
*
* Videos can only autoplay if the browser has been unlocked with an interaction, or satisfies the MEI settings.
* The policies that control autoplaying are vast and vary between browser. You can, and should, read more about
* it here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
*
* If your video doesn't contain any audio, then set the `noAudio` parameter to `true` when the video is _loaded_,
* and it will often allow the video to play immediately:
*
* ```javascript
* preload () {
* this.load.video('pixar', 'nemo.mp4', true);
* }
* ```
*
* The 3rd parameter in the load call tells Phaser that the video doesn't contain any audio tracks. Video without
* audio can autoplay without requiring a user interaction. Video with audio cannot do this unless it satisfies
* the browsers MEI settings. See the MDN Autoplay Guide for further details.
*
* Or:
*
* ```javascript
* create () {
* this.add.video(400, 300).loadURL('assets/aliens.mp4', true);
* }
* ```
*
* You can set the `noAudio` parameter to `true` even if the video does contain audio. It will still allow the video
* to play immediately, but the audio will not start.
*
* More details about video playback and the supported media formats can be found on MDN:
*
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement
* https://developer.mozilla.org/en-US/docs/Web/Media/Formats
*
* @class Video
* @extends Phaser.GameObjects.GameObject
* @memberof Phaser.GameObjects
* @constructor
* @since 3.20.0
*
* @extends Phaser.GameObjects.Components.Alpha
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.ComputedSize
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.Flip
* @extends Phaser.GameObjects.Components.GetBounds
* @extends Phaser.GameObjects.Components.Lighting
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.Origin
* @extends Phaser.GameObjects.Components.RenderNodes
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.TextureCrop
* @extends Phaser.GameObjects.Components.Tint
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {string} [key] - Optional key of the Video this Game Object will play, as stored in the Video Cache.
*/
/**
* A Phaser `CanvasTexture` instance that holds the most recent snapshot taken from the video.
*
* This will only be set if the `snapshot` or `snapshotArea` methods have been called.
*
* Until those methods are called, this property will be `undefined`.
*
* @name Phaser.GameObjects.Video#snapshotTexture
* @type {?Phaser.Textures.CanvasTexture}
* @since 3.20.0
*/
/**
* If the browser supports the Request Video Frame API then this
* property will hold the metadata that is returned from
* the callback each time it is invoked.
*
* See https://wicg.github.io/video-rvfc/#video-frame-metadata-callback
* for a complete list of all properties that will be in this object.
* Likely of most interest is the `mediaTime` property:
*
* The media presentation timestamp (PTS) in seconds of the frame presented
* (e.g. its timestamp on the video.currentTime timeline). MAY have a zero
* value for live-streams or WebRTC applications.
*
* If the browser doesn't support the API then this property will be undefined.
*
* @name Phaser.GameObjects.Video#metadata
* @type {VideoFrameCallbackMetadata}
* @since 3.60.0
*/
/**
* This method handles the Request Video Frame callback.
*
* It is called by the browser when a new video frame is ready to be displayed.
*
* It's also responsible for the creation of the video texture, if it doesn't
* already exist. If it does, it updates the texture as required.
*
* For more details about the Request Video Frame callback, see:
* https://web.dev/requestvideoframecallback-rvfc
*
* @method Phaser.GameObjects.Video#requestVideoFrame
* @fires Phaser.GameObjects.Events#VIDEO_CREATED
* @fires Phaser.GameObjects.Events#VIDEO_LOOP
* @fires Phaser.GameObjects.Events#VIDEO_COMPLETE
* @fires Phaser.GameObjects.Events#VIDEO_PLAY
* @fires Phaser.GameObjects.Events#VIDEO_TEXTURE
* @since 3.60.0
*
* @param {DOMHighResTimeStamp} now - The current time in milliseconds.
* @param {VideoFrameCallbackMetadata} metadata - Useful metadata about the video frame that was most recently presented for composition. See https://wicg.github.io/video-rvfc/#video-frame-metadata-callback
*/
/**
* Starts this video playing.
*
* If the video is already playing, or has been queued to play with `changeSource` then this method just returns.
*
* Videos can only autoplay if the browser has been unlocked. This happens if you have interacted with the browser, i.e.
* by clicking on it or pressing a key, or due to server settings. The policies that control autoplaying are vast and
* vary between browser. You can read more here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
*
* If your video doesn't contain any audio, then set the `noAudio` parameter to `true` when the video is loaded,
* and it will often allow the video to play immediately:
*
* ```javascript
* preload () {
* this.load.video('pixar', 'nemo.mp4', true);
* }
* ```
*
* The 3rd parameter in the load call tells Phaser that the video doesn't contain any audio tracks. Video without
* audio can autoplay without requiring a user interaction. Video with audio cannot do this unless it satisfies
* the browsers MEI settings. See the MDN Autoplay Guide for details.
*
* If you need audio in your videos, then you'll have to consider the fact that the video cannot start playing until the
* user has interacted with the browser, into your game flow.
*
* @method Phaser.GameObjects.Video#play
* @since 3.20.0
*
* @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats.
* @param {number} [markerIn] - Optional in marker time, in seconds, for playback of a sequence of the video.
* @param {number} [markerOut] - Optional out marker time, in seconds, for playback of a sequence of the video.
*
* @return {this} This Video Game Object for method chaining.
*/
/**
* Creates the video.play promise and adds the success and error handlers to it.
*
* Not all browsers support the video.play promise, so this method will fall back to
* the old-school way of handling the video.play call.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play#browser_compatibility for details.
*
* @method Phaser.GameObjects.Video#createPlayPromise
* @since 3.60.0
*
* @param {boolean} [catchError=true] - Should the error be caught and the video marked as failed to play?
*/
/**
* Adds a sequence marker to this video.
*
* Markers allow you to split a video up into sequences, delineated by a start and end time, given in seconds.
*
* You can then play back specific markers via the `playMarker` method.
*
* Note that marker timing is _not_ frame-perfect. You should construct your videos in such a way that you allow for
* plenty of extra padding before and after each sequence to allow for discrepancies in browser seek and currentTime accuracy.
*
* See https://github.com/w3c/media-and-entertainment/issues/4 for more details about this issue.
*
* @method Phaser.GameObjects.Video#addMarker
* @since 3.20.0
*
* @param {string} key - A unique name to give this marker.
* @param {number} markerIn - The time, in seconds, representing the start of this marker.
* @param {number} markerOut - The time, in seconds, representing the end of this marker.
*
* @return {this} This Video Game Object for method chaining.
*/
/**
* Plays a pre-defined sequence in this video.
*
* Markers allow you to split a video up into sequences, delineated by a start and end time, given in seconds and
* specified via the `addMarker` method.
*
* Note that marker timing is _not_ frame-perfect. You should construct your videos in such a way that you allow for
* plenty of extra padding before and after each sequence to allow for discrepancies in browser seek and currentTime accuracy.
*
* See https://github.com/w3c/media-and-entertainment/issues/4 for more details about this issue.
*
* @method Phaser.GameObjects.Video#playMarker
* @since 3.20.0
*
* @param {string} key - The name of the marker sequence to play.
* @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that not all browsers support _seamless_ video looping for all encoding formats.
*
* @return {this} This Video Game Object for method chaining.
*/
/**
* Seeks to a given point in the video. The value is given as a float between 0 and 1,
* where 0 represents the start of the video and 1 represents the end.
*
* Seeking only works if the video has a duration, so will not work for live streams.
*
* When seeking begins, this video will emit a `seeking` event. When the video completes
* seeking (i.e. reaches its designated timestamp) it will emit a `seeked` event.
*
* If you wish to seek based on time instead, use the `Video.setCurrentTime` method.
*
* Unfortunately, the DOM video element does not guarantee frame-accurate seeking.
* This has been an ongoing subject of discussion: https://github.com/w3c/media-and-entertainment/issues/4
*
* @method Phaser.GameObjects.Video#seekTo
* @since 3.20.0
*
* @param {number} value - The point in the video to seek to. A value between 0 and 1.
*
* @return {this} This Video Game Object for method chaining.
*/
/**
* Seeks to a given playback time in the video. The value is given in _seconds_ or as a string.
*
* Seeking only works if the video has a duration, so will not work for live streams.
*
* When seeking begins, this video will emit a `seeking` event. When the video completes
* seeking (i.e. reaches its designated timestamp) it will emit a `seeked` event.
*
* You can provide a string prefixed with either a `+` or a `-`, such as `+2.5` or `-2.5`.
* In this case it will seek to +/- the value given, relative to the _current time_.
*
* If you wish to seek based on a duration percentage instead, use the `Video.seekTo` method.
*
* @method Phaser.GameObjects.Video#setCurrentTime
* @since 3.20.0
*
* @param {(string|number)} value - The playback time to seek to in seconds. Can be expressed as a string, such as `+2` to seek 2 seconds ahead from the current time.
*
* @return {this} This Video Game Object for method chaining.
*/
/**
* Creates a new Video Game Object and adds it to the Scene.
*
* This Game Object is capable of handling playback of a video file, video stream or media stream.
*
* You can optionally 'preload' the video into the Phaser Video Cache:
*
* ```javascript
* preload () {
* this.load.video('ripley', 'assets/aliens.mp4');
* }
*
* create () {
* this.add.video(400, 300, 'ripley');
* }
* ```
*
* You don't have to 'preload' the video. You can also play it directly from a URL:
*
* ```javascript
* create () {
* this.add.video(400, 300).loadURL('assets/aliens.mp4');
* }
* ```
*
* To all intents and purposes, a video is a standard Game Object, just like a Sprite. And as such, you can do
* all the usual things to it, such as scaling, rotating, cropping, tinting, making interactive, giving a
* physics body, etc.
*
* Transparent videos are also possible via the WebM file format. Providing the video file has been encoded with
* an alpha channel, and providing the browser supports WebM playback (not all of them do), then it will render
* in-game with full transparency.
*
* ### Autoplaying Videos
*
* Videos can only autoplay if the browser has been unlocked with an interaction, or satisfies the MEI settings.
* The policies that control autoplaying are vast and vary between browser. You can, and should, read more about
* it here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
*
* If your video doesn't contain any audio, then set the `noAudio` parameter to `true` when the video is _loaded_,
* and it will often allow the video to play immediately:
*
* ```javascript
* preload () {
* this.load.video('pixar', 'nemo.mp4', true);
* }
* ```
*
* The 3rd parameter in the load call tells Phaser that the video doesn't contain any audio tracks. Video without
* audio can autoplay without requiring a user interaction. Video with audio cannot do this unless it satisfies
* the browsers MEI settings. See the MDN Autoplay Guide for further details.
*
* Or:
*
* ```javascript
* create () {
* this.add.video(400, 300).loadURL('assets/aliens.mp4', true);
* }
* ```
*
* You can set the `noAudio` parameter to `true` even if the video does contain audio. It will still allow the video
* to play immediately, but the audio will not start.
*
* More details about video playback and the supported media formats can be found on MDN:
*
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement
* https://developer.mozilla.org/en-US/docs/Web/Media/Formats
*
* Note: This method will only be available if the Video Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectFactory#video
* @since 3.20.0
*
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {string} [key] - Optional key of the Video this Game Object will play, as stored in the Video Cache.
*
* @return {Phaser.GameObjects.Video} The Game Object that was created.
*/
/**
* Enables this Zone as an interactive Drop Zone by calling `setInteractive` with the given
* hit area shape and callback. You can pass any Phaser geometry shape, or a custom shape with
* a matching hit-test callback. If no arguments are provided, a Rectangle matching the size of
* this Zone will be used automatically. Has no effect if this Zone is already interactive.
*
* @method Phaser.GameObjects.Zone#setDropZone
* @since 3.0.0
*
* @param {object} [hitArea] - A Geometry shape instance, such as Phaser.Geom.Ellipse, or your own custom shape. If not given it will try to create a Rectangle based on the size of this zone.
* @param {Phaser.Types.Input.HitAreaCallback} [hitAreaCallback] - A function that will return `true` if the given x/y coords it is sent are within the shape. If you provide a shape you must also provide a callback.
*
* @return {this} This Game Object.
*/
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Circle
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the circle.
*
* @method Phaser.Geom.Circle#getPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {number} position - A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the circle.
* @param {Phaser.Math.Vector2} [out] - A Vector2 to store the return values in. If not given a Vector2 object will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 containing the coordinates of the point around the circle.
*/
/**
* Returns an array of Point objects containing the coordinates of the points around the circumference of the Circle,
* based on the given quantity or stepRate values.
*
* @method Phaser.Geom.Circle#getPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [output,$return]
*
* @param {number} quantity - The amount of points to return. If a falsy value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the circumference of the circle and dividing it by the stepRate.
* @param {Phaser.Math.Vector2[]} [output] - An array to insert the Vector2s in to. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the circumference of the circle.
*/
/**
* Returns a Vector2 object containing the coordinates of a point on the circumference of the Circle based on the given angle.
*
* @function Phaser.Geom.Circle.CircumferencePoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Circle} circle - The Circle to get the circumference point on.
* @param {number} angle - The angle from the center of the Circle to the circumference to return the point from. Given in radians.
* @param {Phaser.Math.Vector2} [out] - A Vector2 to store the results in. If not given a Vector2 will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 object where the `x` and `y` properties are the point on the circumference.
*/
/**
* Creates a new Circle instance based on the values contained in the given source.
*
* @function Phaser.Geom.Circle.Clone
* @since 3.0.0
*
* @param {(Phaser.Geom.Circle|object)} source - The Circle to be cloned. Can be an instance of a Circle or a circle-like object, with x, y and radius properties.
*
* @return {Phaser.Geom.Circle} A clone of the source Circle.
*/
/**
* Returns a Vector2 object containing the coordinates of a point on the circumference of the Circle
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the circle.
*
* @function Phaser.Geom.Circle.GetPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Circle} circle - The Circle to get the circumference point on.
* @param {number} position - A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the circle.
* @param {Phaser.Math.Vector2} [out] - A Vector2 instance to store the return values in. If not given a new Vector2 object will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 containing the coordinates of the point around the circle.
*/
/**
* Returns an array of Vector2 objects containing the coordinates of the points around the circumference of the Circle,
* based on the given quantity or stepRate values.
*
* @function Phaser.Geom.Circle.GetPoints
* @since 3.0.0
*
* @param {Phaser.Geom.Circle} circle - The Circle to get the points from.
* @param {number} quantity - The amount of points to return. If a falsy value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the circumference of the circle and dividing it by the stepRate.
* @param {array} [out] - An array to insert the points in to. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the circumference of the circle.
*/
/**
* Returns a Vector2 containing the coordinates of a point on the circumference of the Ellipse based on the given angle.
*
* @function Phaser.Geom.Ellipse.CircumferencePoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the circumference point on.
* @param {number} angle - The angle from the center of the Ellipse to the circumference to return the point from. Given in radians.
* @param {Phaser.Math.Vector2} [out] - A Vector2 to store the results in. If not given a Vector2 will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 object where the `x` and `y` properties are the point on the circumference.
*/
/**
* Creates a new Ellipse instance based on the values contained in the given source.
*
* @function Phaser.Geom.Ellipse.Clone
* @since 3.0.0
*
* @param {Phaser.Geom.Ellipse} source - The Ellipse to be cloned. Can be an instance of an Ellipse or an ellipse-like object, with x, y, width and height properties.
*
* @return {Phaser.Geom.Ellipse} A clone of the source Ellipse.
*/
/**
* Returns a Vector2 object containing the coordinates of a point on the circumference of the Ellipse
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the ellipse.
*
* @method Phaser.Geom.Ellipse#getPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {number} position - A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the ellipse.
* @param {Phaser.Math.Vector2} [point] - A Vector2 to store the return values in. If not given a Vector2 object will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 instance containing the coordinates of the point around the ellipse.
*/
/**
* Returns an array of Vector2 objects containing the coordinates of the points around the circumference of the Ellipse,
* based on the given quantity or stepRate values.
*
* @method Phaser.Geom.Ellipse#getPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [output,$return]
*
* @param {number} quantity - The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate.
* @param {Phaser.Math.Vector2[]} [output] - An array to insert the Vector2s in. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the circumference of the ellipse.
*/
/**
* Returns a Vector2 object containing the coordinates of a point on the circumference of the Ellipse
* based on the given angle normalized to the range 0 to 1. i.e. a value of 0.5 will give the point
* at 180 degrees around the ellipse.
*
* @function Phaser.Geom.Ellipse.GetPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the circumference point on.
* @param {number} position - A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 degrees around the ellipse.
* @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the return values in. If not given a new Vector2 object will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 object, containing the coordinates of the point around the ellipse.
*/
/**
* Returns an array of Vector2 objects containing the coordinates of the points around the circumference of the Ellipse,
* based on the given quantity or stepRate values.
*
* @function Phaser.Geom.Ellipse.GetPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [out,$return]
*
* @param {Phaser.Geom.Ellipse} ellipse - The Ellipse to get the points from.
* @param {number} quantity - The amount of points to return. If a falsy value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the circumference of the ellipse and dividing it by the stepRate.
* @param {Phaser.Math.Vector2[]} [out] - An array to insert the Vector2 objects into. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the circumference of the ellipse.
*/
/**
* @author Florian Vazelle
* @author Geoffrey Glaive
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @author Richard Davey
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Checks for intersection between the line segment and circle.
*
* Based on code by [Matt DesLauriers](https://github.com/mattdesl/line-circle-collision/blob/master/LICENSE.md).
*
* @function Phaser.Geom.Intersects.LineToCircle
* @since 3.0.0
*
* @param {Phaser.Geom.Line} line - The line segment to check.
* @param {Phaser.Geom.Circle} circle - The circle to check against the line.
* @param {Phaser.Math.Vector2} [nearest] - An optional Vector2 object. If given the closest point on the Line where the circle intersects will be stored in this object.
*
* @return {boolean} `true` if the two objects intersect, otherwise `false`.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Florian Mertens
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Checks if a Point falls between the two end-points of a Line, based on the given line thickness.
*
* Assumes that the line end points are circular, not square.
*
* @function Phaser.Geom.Intersects.PointToLine
* @since 3.0.0
*
* @param {(Phaser.Math.Vector2|any)} point - The point, or point-like object to check.
* @param {Phaser.Geom.Line} line - The line segment to test for intersection on.
* @param {number} [lineThickness=1] - The line thickness. Assumes that the line end points are circular.
*
* @return {boolean} `true` if the Point falls on the Line, otherwise `false`.
*/
/**
* Returns an array of `quantity` Points where each point is taken from the given Line,
* spaced out according to the ease function specified.
*
* ```javascript
* const line = new Phaser.Geom.Line(100, 300, 700, 300);
* const points = Phaser.Geom.Line.GetEasedPoints(line, 'sine.out', 32)
* ```
*
* In the above example, the `points` array will contain 32 points spread-out across
* the length of `line`, where the position of each point is determined by the `Sine.out`
* ease function.
*
* You can optionally provide a collinear threshold. In this case, the resulting points
* are checked against each other, and if they are `< collinearThreshold` distance apart,
* they are dropped from the results. This can help avoid lots of clustered points at
* far ends of the line with tightly-packed eases such as Quartic. Leave the value set
* to zero to skip this check.
*
* Note that if you provide a collinear threshold, the resulting array may not always
* contain `quantity` points.
*
* @function Phaser.Geom.Line.GetEasedPoints
* @since 3.23.0
*
* @generic {Phaser.Math.Vector2[]} O - [out,$return]
*
* @param {Phaser.Geom.Line} line - The Line object.
* @param {(string|function)} ease - The ease to use. This can be either a string from the EaseMap, or a custom function.
* @param {number} quantity - The number of points to return. Note that if you provide a `collinearThreshold`, the resulting array may not always contain this number of points.
* @param {number} [collinearThreshold=0] - An optional threshold. The final array is reduced so that each point is spaced out at least this distance apart. This helps reduce clustering in noisy eases.
* @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease.
*
* @return {Phaser.Math.Vector2[]} An array of Math.Vector2s containing the coordinates of the points on the line.
*/
/**
* Calculates the reflected angle of Line A off the surface represented by Line B. This is the outgoing angle based on the angle of incidence (Line A) and the surface normal of Line B. The result is in radians.
*
* @function Phaser.Geom.Line.ReflectAngle
* @since 3.0.0
*
* @param {Phaser.Geom.Line} lineA - The incident line whose angle of incidence is used.
* @param {Phaser.Geom.Line} lineB - The surface line, used to calculate the normal angle of reflection.
*
* @return {number} The reflected angle of Line A off the surface of Line B, in radians.
*/
/**
* Create a new polygon which is a copy of the specified polygon
*
* @function Phaser.Geom.Polygon.Clone
* @since 3.0.0
*
* @param {Phaser.Geom.Polygon} polygon - The polygon to create a clone of
*
* @return {Phaser.Geom.Polygon} A new separate Polygon cloned from the specified polygon, based on the same points.
*/
/**
* This module implements a modified ear slicing algorithm, optimized by z-order curve hashing and extended to
* handle holes, twisted polygons, degeneracies and self-intersections in a way that doesn't guarantee correctness
* of triangulation, but attempts to always produce acceptable results for practical data.
*
* Example:
*
* ```javascript
* const triangles = Phaser.Geom.Polygon.Earcut([10,0, 0,50, 60,60, 70,10]); // returns [1,0,3, 3,2,1]
* ```
*
* Each group of three vertex indices in the resulting array forms a triangle.
*
* ```javascript
* // triangulating a polygon with a hole
* earcut([0,0, 100,0, 100,100, 0,100, 20,20, 80,20, 80,80, 20,80], [4]);
* // [3,0,4, 5,4,0, 3,4,7, 5,0,1, 2,3,7, 6,5,1, 2,7,6, 6,1,2]
*
* // triangulating a polygon with 3d coords
* earcut([10,0,1, 0,50,2, 60,60,3, 70,10,4], null, 3);
* // [1,0,3, 3,2,1]
* ```
*
* If you pass a single vertex as a hole, Earcut treats it as a Steiner point.
*
* If your input is a multi-dimensional array (e.g. GeoJSON Polygon), you can convert it to the format
* expected by Earcut with `Phaser.Geom.Polygon.Earcut.flatten`:
*
* ```javascript
* var data = earcut.flatten(geojson.geometry.coordinates);
* var triangles = earcut(data.vertices, data.holes, data.dimensions);
* ```
*
* After getting a triangulation, you can verify its correctness with `Phaser.Geom.Polygon.Earcut.deviation`:
*
* ```javascript
* var deviation = earcut.deviation(vertices, holes, dimensions, triangles);
* ```
* Returns the relative difference between the total area of triangles and the area of the input polygon.
* 0 means the triangulation is fully correct.
*
* For more information see https://github.com/mapbox/earcut
*
* @function Phaser.Geom.Polygon.Earcut
* @since 3.50.0
*
* @param {number[]} data - A flat array of vertex coordinates, like [x0,y0, x1,y1, x2,y2, ...]
* @param {number[]} [holeIndices] - An array of hole indices if any (e.g. [5, 8] for a 12-vertex input would mean one hole with vertices 5–7 and another with 8–11).
* @param {number} [dimensions=2] - The number of coordinates per vertex in the input array (2 by default).
*
* @return {number[]} An array of triangulated data.
*/
/*
* ISC License
*
* Copyright (c) 2016, Mapbox
*
* Permission to use, copy, modify, and/or distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright notice
* and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
/**
* Returns an array of Vector2 objects containing the coordinates of the points around the perimeter of the Polygon,
* based on the given quantity or stepRate values.
*
* @function Phaser.Geom.Polygon.GetPoints
* @since 3.12.0
*
* @param {Phaser.Geom.Polygon} polygon - The Polygon to get the points from.
* @param {number} quantity - The amount of points to return. If a falsy value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate.
* @param {array} [output] - An array to insert the points in to. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the perimeter of the Polygon.
*/
/**
* Returns an array of Vector2 objects containing the coordinates of the points around the perimeter of the Polygon,
* based on the given quantity or stepRate values.
*
* @method Phaser.Geom.Polygon#getPoints
* @since 3.12.0
*
* @generic {Phaser.Math.Vector2[]} O - [output,$return]
*
* @param {number} quantity - The amount of points to return. If a falsy value the quantity will be derived from the `stepRate` instead.
* @param {number} [stepRate] - Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate.
* @param {Phaser.Math.Vector2[]} [output] - An array to insert the points in to. If not provided a new array will be created.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 objects pertaining to the points around the perimeter of the Polygon.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Vladimir Agafonkin
* @see Based on Simplify.js mourner.github.io/simplify-js
*/
/**
* Copyright (c) 2017, Vladimir Agafonkin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Igor Ognichenko <ognichenko.igor@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Return an array of Vector2 points from the perimeter of the rectangle, each spaced out based on the quantity or step required.
*
* @function Phaser.Geom.Rectangle.GetPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [out,$return]
*
* @param {Phaser.Geom.Rectangle} rectangle - The Rectangle object to get the points from.
* @param {number} quantity - The number of evenly spaced points from the rectangle's perimeter to return. If falsey, stepRate param will be used to calculate the number of points.
* @param {number} stepRate - Step between points. Used to calculate the number of points to return when quantity is falsey. Ignored if quantity is positive.
* @param {Phaser.Math.Vector2[]} [out] - An optional array to store the points in.
*
* @return {Phaser.Math.Vector2[]} An array of Vector2 points from the perimeter of the rectangle.
*/
/**
* Returns an array of Vector2 points evenly distributed around the perimeter of the Rectangle. This is
* commonly used to create a "marching ants" selection effect, where the returned points are used to
* animate a dashed outline that appears to march around the border of the rectangle.
*
* You can control the spacing of the points either by providing a pixel `step` distance between each
* point, or by specifying the total `quantity` of points to distribute evenly around the full perimeter.
* If both are omitted, an empty array is returned. If `step` is provided, `quantity` is derived from
* the perimeter length divided by the step. If only `quantity` is provided, the step is derived instead.
*
* @function Phaser.Geom.Rectangle.MarchingAnts
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [out,$return]
*
* @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the perimeter points from.
* @param {number} [step] - The distance between each point of the perimeter. Set to `null` if you wish to use the `quantity` parameter instead.
* @param {number} [quantity] - The total number of points to return. The step is then calculated based on the length of the Rectangle, divided by this value.
* @param {Phaser.Math.Vector2[]} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created.
*
* @return {Phaser.Math.Vector2[]} An array containing the perimeter points from the Rectangle.
*/
/**
* Returns a point from the perimeter of a Rectangle based on the given angle, measured in degrees from the center of the Rectangle.
*
* @function Phaser.Geom.Rectangle.PerimeterPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Rectangle} rectangle - The Rectangle to get the perimeter point from.
* @param {number} angle - The angle of the point, in degrees.
* @param {Phaser.Math.Vector2} [out] - The Vector2 object to store the position in. If not given, a new Vector2 instance is created.
*
* @return {Phaser.Math.Vector2} A Vector2 object holding the coordinates of the point on the Rectangle's perimeter.
*/
/**
* Returns an array of points from the perimeter of the Rectangle, each spaced out based on the quantity or step required.
*
* @method Phaser.Geom.Rectangle#getPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2[]} O - [output,$return]
*
* @param {number} quantity - The number of points to return. Set to `false` or 0 to return an arbitrary number of points (`perimeter / stepRate`) evenly spaced around the Rectangle based on the `stepRate`.
* @param {number} [stepRate] - If `quantity` is 0, determines the normalized distance between each returned point.
* @param {Phaser.Math.Vector2[]} [output] - An array to which to append the points.
*
* @return {Phaser.Math.Vector2[]} The modified `output` array, or a new array if none was provided.
*/
/**
* Takes an array of vertex coordinates, and optionally an array of hole indices, then returns an array
* of Triangle instances, where the given vertices have been decomposed into a series of triangles.
*
* @function Phaser.Geom.Triangle.BuildFromPolygon
* @since 3.0.0
*
* @generic {Phaser.Geom.Triangle[]} O - [out,$return]
*
* @param {array} data - A flat array of vertex coordinates like [x0,y0, x1,y1, x2,y2, ...]
* @param {array} [holes=null] - An array of hole indices if any (e.g. [5, 8] for a 12-vertex input would mean one hole with vertices 5–7 and another with 8–11).
* @param {number} [scaleX=1] - Horizontal scale factor to multiply the resulting points by.
* @param {number} [scaleY=1] - Vertical scale factor to multiply the resulting points by.
* @param {(array|Phaser.Geom.Triangle[])} [out] - An array to store the resulting Triangle instances in. If not provided, a new array is created.
*
* @return {(array|Phaser.Geom.Triangle[])} An array of Triangle instances, where each triangle is based on the decomposed vertices data.
*/
/**
* Computes the circumcenter of a triangle. The circumcenter is the centre of
* the circumcircle, the unique circle that passes through all three vertices of
* the triangle. It is also the common intersection point of the perpendicular
* bisectors of the sides of the triangle, and is the only point which has equal
* distance to all three vertices of the triangle.
*
* Adapted from http://bjornharrtell.github.io/jsts/doc/api/jsts_geom_Triangle.js.html
*
* @function Phaser.Geom.Triangle.CircumCenter
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Triangle} triangle - The Triangle to get the circumcenter of.
* @param {Phaser.Math.Vector2} [out] - The Vector2 object to store the position in. If not given, a new Vector2 instance is created.
*
* @return {Phaser.Math.Vector2} A Vector2 object holding the coordinates of the circumcenter of the Triangle.
*/
/**
* Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices.
*
* Adapted from https://gist.github.com/mutoo/5617691
*
* @function Phaser.Geom.Triangle.CircumCircle
* @since 3.0.0
*
* @generic {Phaser.Geom.Circle} O - [out,$return]
*
* @param {Phaser.Geom.Triangle} triangle - The Triangle to use as input.
* @param {Phaser.Geom.Circle} [out] - An optional Circle to store the result in.
*
* @return {Phaser.Geom.Circle} The updated `out` Circle, or a new Circle if none was provided.
*/
/**
* Returns a point along the perimeter of a Triangle as a Vector2, based on a normalized position value.
*
* The `position` parameter is a value between 0 and 1, where 0 and 1 both map to the start of
* line A (the first vertex). The point is calculated by traversing the triangle's perimeter in
* order: line A, then line B, then line C.
*
* @function Phaser.Geom.Triangle.GetPoint
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Triangle} triangle - The Triangle to get the point on its perimeter from.
* @param {number} position - A normalized value between 0 and 1 representing a position along the triangle's perimeter. Both 0 and 1 return the start of line A.
* @param {Phaser.Math.Vector2} [out] - An optional Vector2 point to store the result in. If not given, a new Vector2 will be created.
*
* @return {Phaser.Math.Vector2} A Vector2 point containing the coordinates of the position on the triangle's perimeter.
*/
/**
* Returns an array of evenly spaced points on the perimeter of a Triangle.
*
* The points are placed along the triangle's three edges in order (A, B, then C),
* with their positions calculated proportionally based on the total perimeter length.
*
* @function Phaser.Geom.Triangle.GetPoints
* @since 3.0.0
*
* @generic {Phaser.Math.Vector2} O - [out,$return]
*
* @param {Phaser.Geom.Triangle} triangle - The Triangle to get the points from.
* @param {number} quantity - The number of evenly spaced points to return. Set to 0 to return an arbitrary number of points based on the `stepRate`.
* @param {number} stepRate - If `quantity` is 0, the distance in pixels between each returned point along the perimeter.
* @param {Phaser.Math.Vector2[]} [out] - An array to which the points should be appended.
*
* @return {Phaser.Math.Vector2[]} The modified `out` array, or a new array if none was provided.
*/
/**
* @classdesc
* The Input Manager is responsible for handling the pointer related systems in a single Phaser Game instance.
*
* Based on the Game Config it will create handlers for mouse and touch support.
*
* Keyboard and Gamepad are plugins, handled directly by the InputPlugin class.
*
* It then manages the events, pointer creation and general hit test related operations.
*
* You rarely need to interact with the Input Manager directly, and as such, all of its properties and methods
* should be considered private. Instead, you should use the Input Plugin, which is a Scene level system, responsible
* for dealing with all input events for a Scene.
*
* @class InputManager
* @memberof Phaser.Input
* @constructor
* @since 3.0.0
*
* @param {Phaser.Game} game - The Game instance that owns the Input Manager.
* @param {object} config - The Input Configuration object, as set in the Game Config.
*/
/**
* The most recently active Pointer object.
*
* If you've only 1 Pointer in your game then this will accurately be either the first finger touched, or the mouse.
*
* If your game doesn't need to support multi-touch then you can safely use this property in all of your game
* code and it will adapt to be either the mouse or the touch, based on device.
*
* @name Phaser.Input.InputManager#activePointer
* @type {Phaser.Input.Pointer}
* @since 3.0.0
*/
/**
* Tells the Input system to set a custom cursor.
*
* This cursor will be the default cursor used when interacting with the game canvas.
*
* If an Interactive Object also sets a custom cursor, this is the cursor that is reset after its use.
*
* Any valid CSS cursor value is allowed, including paths to image files, i.e.:
*
* ```javascript
* this.input.setDefaultCursor('url(assets/cursors/sword.cur), pointer');
* ```
*
* Please read about the differences between browsers when it comes to the file formats and sizes they support:
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
* https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_User_Interface/Using_URL_values_for_the_cursor_property
*
* It's up to you to pick a suitable cursor format that works across the range of browsers you need to support.
*
* @method Phaser.Input.InputManager#setDefaultCursor
* @since 3.10.0
*
* @param {string} cursor - The CSS to be used when setting the default cursor.
*/
/**
* Called by the InputPlugin when processing over and out events.
*
* Tells the Input Manager to set a custom cursor during its postUpdate step.
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
*
* @method Phaser.Input.InputManager#setCursor
* @private
* @since 3.10.0
*
* @param {Phaser.Types.Input.InteractiveObject} interactiveObject - The Interactive Object that called this method.
*/
/**
* Sets a custom cursor on the parent canvas element of the game, based on the `cursor`
* setting of the given Interactive Object (i.e. a Sprite).
*
* See the CSS property `cursor` for more information on MDN:
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
*
* @method Phaser.Input.InputPlugin#setCursor
* @since 3.85.0
*
* @param {Phaser.Types.Input.InteractiveObject} interactiveObject - The Interactive Object that will set the cursor on the canvas.
*/
/**
* This is called automatically by the Input Manager.
* It emits events for plugins to listen to and also handles polling updates, if enabled.
*
* @method Phaser.Input.InputPlugin#updatePoll
* @since 3.18.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*
* @return {boolean} `true` if the plugin and the Scene it belongs to is active.
*/
/**
* Enable a Game Object for interaction.
*
* If the Game Object already has an Interactive Object component, it is enabled and returned.
*
* Otherwise, a new Interactive Object component is created and assigned to the Game Object's `input` property.
*
* Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area
* for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced
* input detection.
*
* If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If
* this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific
* shape for it to use.
*
* You can also provide an Input Configuration Object as the only argument to this method.
*
* @method Phaser.Input.InputPlugin#enable
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to be enabled for input.
* @param {(Phaser.Types.Input.InputConfiguration|any)} [hitArea] - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used.
* @param {Phaser.Types.Input.HitAreaCallback} [hitAreaCallback] - The 'contains' function to invoke to check if the pointer is within the hit area.
* @param {boolean} [dropZone=false] - Is this Game Object a drop zone or not?
*
* @return {this} This Input Plugin.
*/
/**
* Checks to see if a Pointer is ready to drag the objects below it, based on either a distance
* or time threshold.
*
* @method Phaser.Input.InputPlugin#processDragThresholdEvent
* @private
* @since 3.18.0
*
* @param {Phaser.Input.Pointer} pointer - The Pointer to check the drag thresholds on.
* @param {number} time - The current time.
*/
/**
* Sets the hit area for the given array of Game Objects.
*
* A hit area is typically one of the geometric shapes Phaser provides, such as a `Phaser.Geom.Rectangle`
* or `Phaser.Geom.Circle`. However, it can be any object as long as it works with the provided callback.
*
* If no hit area is provided a Rectangle is created based on the size of the Game Object, if possible
* to calculate.
*
* The hit area callback is the function that takes an `x` and `y` coordinate and returns a boolean if
* those values fall within the area of the shape or not. All of the Phaser geometry objects provide this,
* such as `Phaser.Geom.Rectangle.Contains`.
*
* A hit area callback can be supplied to the `hitArea` parameter without using the `hitAreaCallback` parameter.
*
* @method Phaser.Input.InputPlugin#setHitArea
* @since 3.0.0
*
* @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set the hit area on.
* @param {(Phaser.Types.Input.InputConfiguration|Phaser.Types.Input.HitAreaCallback|any)} [hitArea] - Either an input configuration object, a geometric shape that defines the hit area or a hit area callback. If not specified a Rectangle hit area will be used.
* @param {Phaser.Types.Input.HitAreaCallback} [hitAreaCallback] - The 'contains' function to invoke to check if the pointer is within the hit area.
*
* @return {this} This InputPlugin object.
*/
/**
* Sets the hit area for an array of Game Objects to be a `Phaser.Geom.Rectangle` shape, using
* the Game Objects texture frame to define the position and size of the hit area.
*
* @method Phaser.Input.InputPlugin#setHitAreaFromTexture
* @since 3.0.0
*
* @param {(Phaser.GameObjects.GameObject|Phaser.GameObjects.GameObject[])} gameObjects - An array of Game Objects to set as having a Rectangle hit area based on their texture frame.
* @param {Phaser.Types.Input.HitAreaCallback} [callback] - The hit area callback. If undefined it uses Rectangle.Contains.
*
* @return {this} This InputPlugin object.
*/
/**
* Tells the Input system to set a custom cursor.
*
* This cursor will be the default cursor used when interacting with the game canvas.
*
* If an Interactive Object also sets a custom cursor, this is the cursor that is reset after its use.
*
* Any valid CSS cursor value is allowed, including paths to image files, i.e.:
*
* ```javascript
* this.input.setDefaultCursor('url(assets/cursors/sword.cur), pointer');
* ```
*
* Please read about the differences between browsers when it comes to the file formats and sizes they support:
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
* https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_User_Interface/Using_URL_values_for_the_cursor_property
*
* It's up to you to pick a suitable cursor format that works across the range of browsers you need to support.
*
* @method Phaser.Input.InputPlugin#setDefaultCursor
* @since 3.10.0
*
* @param {string} cursor - The CSS to be used when setting the default cursor.
*
* @return {this} This Input instance.
*/
/**
* The x coordinate of the ActivePointer based on the first camera in the camera list.
* This is only safe to use if your game has just 1 non-transformed camera and doesn't use multi-touch.
*
* @name Phaser.Input.InputPlugin#x
* @type {number}
* @readonly
* @since 3.0.0
*/
/**
* The y coordinate of the ActivePointer based on the first camera in the camera list.
* This is only safe to use if your game has just 1 non-transformed camera and doesn't use multi-touch.
*
* @name Phaser.Input.InputPlugin#y
* @type {number}
* @readonly
* @since 3.0.0
*/
/**
* Returns the input plugin object from the cache based on the given key.
*
* @function Phaser.Input.InputPluginCache.getPlugin
* @static
* @since 3.10.0
*
* @param {string} key - The key of the input plugin to get.
*
* @return {Phaser.Types.Input.InputPluginContainer} The input plugin object.
*/
/**
* Removes an input plugin based on the given key.
*
* @function Phaser.Input.InputPluginCache.remove
* @static
* @since 3.10.0
*
* @param {string} key - The key of the input plugin to remove.
*/
/**
* The DOM element the Pointer was pressed down on, taken from the DOM event.
* In a default set-up this will be the Canvas that Phaser is rendering to, or the Window element.
*
* @name Phaser.Input.Pointer#downElement
* @type {any}
* @readonly
* @since 3.16.0
*/
/**
* The DOM element the Pointer was released on, taken from the DOM event.
* In a default set-up this will be the Canvas that Phaser is rendering to, or the Window element.
*
* @name Phaser.Input.Pointer#upElement
* @type {any}
* @readonly
* @since 3.16.0
*/
/**
* The current velocity of the Pointer, based on its current and previous positions.
*
* This value is smoothed out each frame, according to the `motionFactor` property.
*
* This property is updated whenever the Pointer moves, regardless of any button states. In other words,
* it changes based on movement alone - a button doesn't have to be pressed first.
*
* @name Phaser.Input.Pointer#velocity
* @type {Phaser.Math.Vector2}
* @readonly
* @since 3.16.0
*/
/**
* The current angle the Pointer is moving, in radians, based on its previous and current position.
*
* The angle is based on the old position facing to the current position.
*
* This property is updated whenever the Pointer moves, regardless of any button states. In other words,
* it changes based on movement alone - a button doesn't have to be pressed first.
*
* @name Phaser.Input.Pointer#angle
* @type {number}
* @readonly
* @since 3.16.0
*/
/**
* The distance the Pointer has moved, based on its previous and current position.
*
* This value is smoothed out each frame, according to the `motionFactor` property.
*
* This property is updated whenever the Pointer moves, regardless of any button states. In other words,
* it changes based on movement alone - a button doesn't have to be pressed first.
*
* If you need the total distance travelled since the primary button was pressed down,
* then use the `Pointer.getDistance` method.
*
* @name Phaser.Input.Pointer#distance
* @type {number}
* @readonly
* @since 3.16.0
*/
/**
* Takes a Camera and returns a Vector2 containing the translated position of this Pointer
* within that Camera. This can be used to convert this Pointers position into camera space.
*
* @method Phaser.Input.Pointer#positionToCamera
* @since 3.0.0
*
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to use for the translation.
* @param {(Phaser.Math.Vector2|object)} [output] - A Vector2-like object in which to store the translated position.
*
* @return {(Phaser.Math.Vector2|object)} A Vector2 containing the translated coordinates of this Pointer, based on the given camera.
*/
/**
* If the Pointer has a button pressed down at the time this method is called, it will return the
* distance between the Pointer's `downX` and `downY` values and the current position.
*
* If no button is held down, it will return the last recorded distance, based on where
* the Pointer was when the button was released.
*
* If you wish to get the distance being travelled currently, based on the velocity of the Pointer,
* then see the `Pointer.distance` property.
*
* @method Phaser.Input.Pointer#getDistance
* @since 3.13.0
*
* @return {number} The distance the Pointer moved.
*/
/**
* If the Pointer has a button pressed down at the time this method is called, it will return the
* horizontal distance between the Pointer's `downX` value and the current `x` position.
*
* If no button is held down, it will return the last recorded horizontal distance, based on where
* the Pointer was when the button was released.
*
* @method Phaser.Input.Pointer#getDistanceX
* @since 3.16.0
*
* @return {number} The horizontal distance the Pointer moved.
*/
/**
* If the Pointer has a button pressed down at the time this method is called, it will return the
* vertical distance between the Pointer's `downY` value and the current `y` position.
*
* If no button is held down, it will return the last recorded vertical distance, based on where
* the Pointer was when the button was released.
*
* @method Phaser.Input.Pointer#getDistanceY
* @since 3.16.0
*
* @return {number} The vertical distance the Pointer moved.
*/
/**
* If the Pointer has a button pressed down at the time this method is called, it will return the
* duration since the button was pressed down.
*
* If no button is held down, it will return the last recorded duration, based on the time
* the last button on the Pointer was released.
*
* @method Phaser.Input.Pointer#getDuration
* @since 3.16.0
*
* @return {number} The duration the Pointer was held down for in milliseconds.
*/
/**
* If the Pointer has a button pressed down at the time this method is called, it will return the
* angle between the Pointer's `downX` and `downY` values and the current position.
*
* If no button is held down, it will return the last recorded angle, based on where
* the Pointer was when the button was released.
*
* The angle is based on the old position facing to the current position.
*
* If you wish to get the current angle, based on the velocity of the Pointer, then
* see the `Pointer.angle` property.
*
* @method Phaser.Input.Pointer#getAngle
* @since 3.16.0
*
* @return {number} The angle between the Pointer's coordinates in radians.
*/
/**
* The Input Manager Process Event.
*
* This internal event is dispatched by the Input Manager when not using the legacy queue system,
* and it wants the Input Plugins to update themselves.
*
* @event Phaser.Input.Events#MANAGER_PROCESS
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* The Input Plugin Update Event.
*
* This internal event is dispatched by the Input Plugin at the start of its `update` method.
* This hook is designed specifically for input plugins, but can also be listened to from user-land code.
*
* @event Phaser.Input.Events#UPDATE
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* A Vector2 containing the most recent values from the Gamepad's left axis stick.
* This is updated automatically as part of the Gamepad.update cycle.
* The H Axis is mapped to the `Vector2.x` property, and the V Axis to the `Vector2.y` property.
* The values are based on the Axis thresholds.
* If the Gamepad does not have a left axis stick, the values will always be zero.
*
* @name Phaser.Input.Gamepad.Gamepad#leftStick
* @type {Phaser.Math.Vector2}
* @since 3.10.0
*/
/**
* A Vector2 containing the most recent values from the Gamepad's right axis stick.
* This is updated automatically as part of the Gamepad.update cycle.
* The H Axis is mapped to the `Vector2.x` property, and the V Axis to the `Vector2.y` property.
* The values are based on the Axis thresholds.
* If the Gamepad does not have a right axis stick, the values will always be zero.
*
* @name Phaser.Input.Gamepad.Gamepad#rightStick
* @type {Phaser.Math.Vector2}
* @since 3.10.0
*/
/**
* Gets the value of an axis based on the given index.
* The index must be valid within the range of axes supported by this Gamepad.
* The return value will be a float between -1 and 1.
*
* @method Phaser.Input.Gamepad.Gamepad#getAxisValue
* @since 3.10.0
*
* @param {number} index - The index of the axes to get the value for.
*
* @return {number} The value of the axis, between -1 and 1.
*/
/**
* Gets the value of a button based on the given index.
* The index must be valid within the range of buttons supported by this Gamepad.
*
* The return value will be either 0 or 1 for a digital button, or a float between 0 and 1
* for a pressure-sensitive analogue button, such as the shoulder buttons on a Dual Shock.
*
* @method Phaser.Input.Gamepad.Gamepad#getButtonValue
* @since 3.10.0
*
* @param {number} index - The index of the button to get the value for.
*
* @return {number} The value of the button, between 0 and 1.
*/
/**
* @classdesc
* The Gamepad Plugin is an input plugin that belongs to the Scene-owned Input system.
*
* Its role is to listen for native DOM Gamepad Events and then process them.
*
* You do not need to create this class directly, the Input system will create an instance of it automatically.
*
* You can access it from within a Scene using `this.input.gamepad`.
*
* To listen for a gamepad being connected:
*
* ```javascript
* this.input.gamepad.once('connected', function (pad) {
* // 'pad' is a reference to the gamepad that was just connected
* });
* ```
*
* Note that the browser may require you to press a button on a gamepad before it will allow you to access it,
* this is for security reasons. However, it may also trust the page already, in which case you won't get the
* 'connected' event and instead should check `GamepadPlugin.total` to see if it thinks there are any gamepads
* already connected.
*
* Once you have received the connected event, or polled the gamepads and found them enabled, you can access
* them via the built-in properties `GamepadPlugin.pad1` to `pad4`, for up to 4 game pads. With a reference
* to the gamepads you can poll its buttons and axis sticks. See the properties and methods available on
* the `Gamepad` class for more details.
*
* As of September 2020 Chrome, and likely other browsers, will soon start to require that games requesting
* access to the Gamepad API are running under SSL. They will actively block API access if they are not.
*
* For more information about Gamepad support in browsers see the following resources:
*
* https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API
* https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
* https://www.smashingmagazine.com/2015/11/gamepad-api-in-web-games/
* http://html5gamepad.com/
*
* @class GamepadPlugin
* @extends Phaser.Events.EventEmitter
* @memberof Phaser.Input.Gamepad
* @constructor
* @since 3.10.0
*
* @param {Phaser.Input.InputPlugin} sceneInputPlugin - A reference to the Scene Input Plugin that the GamepadPlugin belongs to.
*/
/**
* Looks up a single Gamepad based on the given index value.
*
* @method Phaser.Input.Gamepad.GamepadPlugin#getPad
* @since 3.10.0
*
* @param {number} index - The index of the Gamepad to get.
*
* @return {Phaser.Input.Gamepad.Gamepad} The Gamepad matching the given index, or undefined if none were found.
*/
/**
* @classdesc
* The Keyboard Plugin is an input plugin that belongs to the Scene-owned Input system.
*
* Its role is to listen for native DOM Keyboard Events and then process them.
*
* You do not need to create this class directly, the Input system will create an instance of it automatically.
*
* You can access it from within a Scene using `this.input.keyboard`. For example, you can do:
*
* ```javascript
* this.input.keyboard.on('keydown', callback, context);
* ```
*
* Or, to listen for a specific key:
*
* ```javascript
* this.input.keyboard.on('keydown-A', callback, context);
* ```
*
* You can also create Key objects, which you can then poll in your game loop:
*
* ```javascript
* var spaceBar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
* ```
*
* If you have multiple parallel Scenes, each trying to get keyboard input, be sure to disable capture on them to stop them from
* stealing input from another Scene in the list. You can do this with `this.input.keyboard.enabled = false` within the
* Scene to stop all input, or `this.input.keyboard.preventDefault = false` to stop a Scene halting input on another Scene.
*
* _Note_: Many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details
* and use the site https://w3c.github.io/uievents/tools/key-event-viewer.html to test your n-key support in browser.
*
* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling.
* For example the Chrome extension vimium is known to disable Phaser from using the D key, while EverNote disables the backtick key.
* And there are others. So, please check your extensions before opening Phaser issues about keys that don't work.
*
* @class KeyboardPlugin
* @extends Phaser.Events.EventEmitter
* @memberof Phaser.Input.Keyboard
* @constructor
* @since 3.10.0
*
* @param {Phaser.Input.InputPlugin} sceneInputPlugin - A reference to the Scene Input Plugin that the KeyboardPlugin belongs to.
*/
/**
* The Global Key Down Event.
*
* This event is dispatched by the Keyboard Plugin when any key on the keyboard is pressed down.
*
* Listen to this event from within a Scene using: `this.input.keyboard.on('keydown', listener)`.
*
* You can also listen for a specific key being pressed. See [Keyboard.Events.KEY_DOWN]{@linkcode Phaser.Input.Keyboard.Events#event:KEY_DOWN} for details.
*
* Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.DOWN]{@linkcode Phaser.Input.Keyboard.Events#event:DOWN} for details.
*
* _Note_: Many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
* Read [this article on ghosting]{@link http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/} for details.
*
* Also, please be aware that some browser extensions can disable or override Phaser keyboard handling.
* For example, the Chrome extension vimium is known to disable Phaser from using the D key, while EverNote disables the backtick key.
* There are others. So, please check your extensions if you find you have specific keys that don't work.
*
* @event Phaser.Input.Keyboard.Events#ANY_KEY_DOWN
* @type {string}
* @since 3.0.0
*
* @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was pressed, any modifiers, etc.
*/
/**
* The Key Down Event.
*
* This event is dispatched by the Keyboard Plugin when any key on the keyboard is pressed down.
*
* Unlike the `ANY_KEY_DOWN` event, this one has a special dynamic event name. For example, to listen for the `A` key being pressed
* use the following from within a Scene: `this.input.keyboard.on('keydown-A', listener)`. You can replace the `-A` part of the event
* name with any valid [Key Code string]{@link Phaser.Input.Keyboard.KeyCodes}. For example, this will listen for the space bar:
* `this.input.keyboard.on('keydown-SPACE', listener)`.
*
* You can also create a generic 'global' listener. See [Keyboard.Events.ANY_KEY_DOWN]{@linkcode Phaser.Input.Keyboard.Events#event:ANY_KEY_DOWN} for details.
*
* Finally, you can create Key objects, which you can also listen for events from. See [Keyboard.Events.DOWN]{@linkcode Phaser.Input.Keyboard.Events#event:DOWN} for details.
*
* _Note_: Many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
* Read [this article on ghosting]{@link http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/} for details.
*
* Also, please be aware that some browser extensions can disable or override Phaser keyboard handling.
* For example, the Chrome extension vimium is known to disable Phaser from using the D key, while EverNote disables the backtick key.
* There are others. So, please check your extensions if you find you have specific keys that don't work.
*
* @event Phaser.Input.Keyboard.Events#KEY_DOWN
* @type {string}
* @since 3.0.0
*
* @param {KeyboardEvent} event - The native DOM Keyboard Event. You can inspect this to learn more about the key that was pressed, any modifiers, etc.
*/
/**
* Returns `true` if the Key was pressed down within the `duration` value given, based on the current
* game clock time. Or `false` if it either isn't down, or was pressed down longer ago than the given duration.
*
* @function Phaser.Input.Keyboard.DownDuration
* @since 3.0.0
*
* @param {Phaser.Input.Keyboard.Key} key - The Key object to test.
* @param {number} [duration=50] - The duration, in ms, within which the key must have been pressed down.
*
* @return {boolean} `true` if the Key was pressed down within `duration` ms ago, otherwise `false`.
*/
/**
* Returns `true` if the Key was released within the `duration` value given, based on the current
* game clock time. Or returns `false` if it either isn't up, or was released longer ago than the given duration.
*
* @function Phaser.Input.Keyboard.UpDuration
* @since 3.0.0
*
* @param {Phaser.Input.Keyboard.Key} key - The Key object to test.
* @param {number} [duration=50] - The duration, in ms, within which the key must have been released.
*
* @return {boolean} `true` if the Key was released within `duration` ms ago, otherwise `false`.
*/
/**
* If the browser supports it, you can request that the pointer be locked to the browser window.
*
* This is classically known as 'FPS controls', where the pointer can't leave the browser until
* the user presses an exit key.
*
* If the browser successfully enters a locked state, a `POINTER_LOCK_CHANGE_EVENT` will be dispatched,
* from the games Input Manager, with an `isPointerLocked` property.
*
* It is important to note that pointer lock can only be enabled after an 'engagement gesture',
* see: https://w3c.github.io/pointerlock/#dfn-engagement-gesture.
*
* Note for Firefox: There is a bug in certain Firefox releases that cause native DOM events like
* `mousemove` to fire continuously when in pointer lock mode. You can get around this by setting
* `this.preventDefaultMove` to `false` in this class. You may also need to do the same for
* `preventDefaultDown` and/or `preventDefaultUp`. Please test combinations of these if you encounter
* the error.
*
* @method Phaser.Input.Mouse.MouseManager#requestPointerLock
* @since 3.0.0
*/
/**
* Called by the Loader, starts the actual file downloading.
* During the load the methods onLoad, onError and onProgress are called, based on the XHR events.
* You shouldn't normally call this method directly, it's meant to be invoked by the Loader.
*
* @method Phaser.Loader.File#load
* @since 3.0.0
*/
/**
* Given a File and a baseURL value, this returns the URL the File will use to download from.
*
* If the file has no URL, `false` is returned. If the file URL is already absolute (i.e. it
* begins with `blob:`, `data:`, `capacitor://`, `file://`, `http://`, `https://`, or `//`),
* it is returned as-is. Otherwise, the baseURL is prepended to the file URL to form a
* complete URL.
*
* @function Phaser.Loader.GetURL
* @since 3.0.0
*
* @param {Phaser.Loader.File} file - The File object whose URL will be resolved.
* @param {string} baseURL - A default base URL to prepend when the file URL is relative.
*
* @return {string} The resolved URL the File will use to download from, or `false` if the file has no URL.
*/
/**
* The value of `path`, if set, is placed before any _relative_ file path given. For example:
*
* ```javascript
* this.load.path = "images/sprites/";
* this.load.image("ball", "ball.png");
* this.load.image("tree", "level1/oaktree.png");
* this.load.image("boom", "http://server.com/explode.png");
* ```
*
* Would load the `ball` file from `images/sprites/ball.png` and the tree from
* `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL
* given as it's an absolute URL.
*
* Please note that the path is added before the filename but *after* the baseURL (if set.)
*
* If you set this property directly then it _must_ end with a "/". Alternatively, call `setPath()` and it'll do it for you.
*
* @name Phaser.Loader.LoaderPlugin#path
* @type {string}
* @default ''
* @since 3.0.0
*/
/**
* The value of `path`, if set, is placed before any _relative_ file path given. For example:
*
* ```javascript
* this.load.setPath("images/sprites/");
* this.load.image("ball", "ball.png");
* this.load.image("tree", "level1/oaktree.png");
* this.load.image("boom", "http://server.com/explode.png");
* ```
*
* Would load the `ball` file from `images/sprites/ball.png` and the tree from
* `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL
* given as it's an absolute URL.
*
* Please note that the path is added before the filename but *after* the baseURL (if set.)
*
* Once a path is set it will then affect every file added to the Loader from that point on. It does _not_ change any
* file _already_ in the load queue. To reset it, call this method with no arguments.
*
* @method Phaser.Loader.LoaderPlugin#setPath
* @since 3.0.0
*
* @param {string} [path] - The path to use. Leave empty to reset.
*
* @return {this} This Loader object.
*/
/**
* Sets the Cross Origin Resource Sharing value used when loading files.
*
* Files can override this value on a per-file basis by specifying an alternative `crossOrigin` value in their file config.
*
* Once CORs is set it will then affect every file loaded by the Loader from that point on, as long as they don't have
* their own CORs setting. To reset it, call this method with no arguments.
*
* For more details about CORs see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*
* @method Phaser.Loader.LoaderPlugin#setCORS
* @since 3.0.0
*
* @param {string} [crossOrigin] - The value to use for the `crossOrigin` property in the load request.
*
* @return {this} This Loader object.
*/
/**
* Causes the browser to save the given data as a file to its default Downloads folder.
*
* Creates a DOM level anchor link, assigns it as being a `download` anchor, sets the href
* to be an ObjectURL based on the given data, and then invokes a click event.
*
* @method Phaser.Loader.LoaderPlugin#save
* @since 3.0.0
*
* @param {*} data - The data to be saved. Will be passed through URL.createObjectURL.
* @param {string} [filename=file.json] - The filename to save the file as.
* @param {string} [filetype=application/json] - The file type to use when saving the file. Defaults to JSON.
*
* @return {this} This Loader plugin.
*/
/**
* Creates a new XMLHttpRequest (xhr) object based on the given File and XHRSettings
* and starts the download of it. It uses the File's own XHRSettings and merges them
* with the global XHRSettings object to set the xhr values before download.
*
* @function Phaser.Loader.XHRLoader
* @since 3.0.0
*
* @param {Phaser.Loader.File} file - The File to download.
* @param {Phaser.Types.Loader.XHRSettingsObject} globalXHRSettings - The global XHRSettings object.
*
* @return {XMLHttpRequest} The XHR object. For base64 files, `file.onBase64Load` is called directly and this function returns `undefined`.
*/
/**
* Aseprite is a powerful animated sprite editor and pixel art tool.
*
* You can find more details at https://www.aseprite.org/
*
* Adds a JSON based Aseprite Animation, or array of animations, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.aseprite('gladiator', 'images/Gladiator.png', 'images/Gladiator.json');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
* its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
*
* To export a compatible JSON file in Aseprite, please do the following:
*
* 1. Go to "File - Export Sprite Sheet"
*
* 2. On the **Layout** tab:
* 2a. Set the "Sheet type" to "Packed"
* 2b. Set the "Constraints" to "None"
* 2c. Check the "Merge Duplicates" checkbox
*
* 3. On the **Sprite** tab:
* 3a. Set "Layers" to "Visible layers"
* 3b. Set "Frames" to "All frames", unless you only wish to export a sub-set of tags
*
* 4. On the **Borders** tab:
* 4a. Check the "Trim Sprite" and "Trim Cells" options
* 4b. Ensure "Border Padding", "Spacing" and "Inner Padding" are all > 0 (1 is usually enough)
*
* 5. On the **Output** tab:
* 5a. Check "Output File", give your image a name and make sure you choose "png files" as the file type
* 5b. Check "JSON Data" and give your json file a name
* 5c. The JSON Data type can be either a Hash or Array, Phaser doesn't mind.
* 5d. Make sure "Tags" is checked in the Meta options
* 5e. In the "Item Filename" input box, make sure it says just "{frame}" and nothing more.
*
* 6. Click export
*
* This was tested with Aseprite 1.2.25.
*
* This will export a png and json file which you can load using the Aseprite Loader.
*
* The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Texture Manager first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.aseprite({
* key: 'gladiator',
* textureURL: 'images/Gladiator.png',
* atlasURL: 'images/Gladiator.json'
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.AsepriteFileConfig` for more details.
*
* Instead of passing a URL for the JSON data you can also pass in a well formed JSON object instead.
*
* Once loaded, you can call this method from within a Scene with the 'atlas' key:
*
* ```javascript
* this.anims.createFromAseprite('paladin');
* ```
*
* Any animations defined in the JSON will now be available to use in Phaser and you play them
* via their Tag name. For example, if you have an animation called 'War Cry' on your Aseprite timeline,
* you can play it in Phaser using that Tag name:
*
* ```javascript
* this.add.sprite(400, 300).play('War Cry');
* ```
*
* When calling this method you can optionally provide an array of tag names, and only those animations
* will be created. For example:
*
* ```javascript
* this.anims.createFromAseprite('paladin', [ 'step', 'War Cry', 'Magnum Break' ]);
* ```
*
* This will only create the 3 animations defined. Note that the tag names are case-sensitive.
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
* key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
* this is what you would use to retrieve the image from the Texture Manager.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* Note: The ability to load this type of file will only be available if the Aseprite File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#aseprite
* @fires Phaser.Loader.Events#ADD
* @since 3.50.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.AsepriteFileConfig|Phaser.Types.Loader.FileTypes.AsepriteFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string|string[]} [textureURL] - The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
* @param {object|string} [atlasURL] - The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". Or, a well formed JSON object.
* @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings.
* @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* @classdesc
* A single JSON based Texture Atlas File suitable for loading by the Loader.
*
* These are created when you use the Phaser.Loader.LoaderPlugin#atlas method and are not typically created directly.
*
* For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#atlas.
*
* {@link https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm|Texture Packer - How to create sprite sheets for Phaser}
*
* @class AtlasJSONFile
* @extends Phaser.Loader.MultiFile
* @memberof Phaser.Loader.FileTypes
* @constructor
* @since 3.0.0
*
* @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
* @param {(string|Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig)} key - The key to use for this file, or a file configuration object.
* @param {string|string[]} [textureURL] - The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
* @param {object|string} [atlasURL] - The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". Or, a well formed JSON object.
* @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings.
* @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings.
*/
/**
* Adds a JSON based Texture Atlas, or array of atlases, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.atlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.json');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
* its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
*
* Phaser expects the atlas data to be provided in a JSON file, using either the JSON Hash or JSON Array format.
*
* These files are created by software such as:
*
* * [Texture Packer](https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?source=photonstorm)
* * [Shoebox](https://renderhjs.net/shoebox/)
* * [Gamma Texture Packer](https://gammafp.com/tool/atlas-packer/)
* * [Adobe Flash / Animate](https://www.adobe.com/uk/products/animate.html)
* * [Free Texture Packer](http://free-tex-packer.com/)
* * [Leshy SpriteSheet Tool](https://www.leshylabs.com/apps/sstool/)
*
* If you are using Texture Packer and have enabled multi-atlas support, then please use the Phaser Multi Atlas loader
* instead of this one.
*
* Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
*
* The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Texture Manager first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.atlas({
* key: 'mainmenu',
* textureURL: 'images/MainMenu.png',
* atlasURL: 'images/MainMenu.json'
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig` for more details.
*
* Instead of passing a URL for the atlas JSON data you can also pass in a well formed JSON object instead.
*
* Once the atlas has finished loading you can use frames from it as textures for a Game Object by referencing its key:
*
* ```javascript
* this.load.atlas('mainmenu', 'images/MainMenu.png', 'images/MainMenu.json');
* // and later in your game ...
* this.add.image(x, y, 'mainmenu', 'background');
* ```
*
* To get a list of all available frames within an atlas please consult your Texture Atlas software.
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
* key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
* this is what you would use to retrieve the image from the Texture Manager.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* Phaser also supports the automatic loading of associated normal maps. If you have a normal map to go with this image,
* then you can specify it by providing an array as the `url` where the second element is the normal map:
*
* ```javascript
* this.load.atlas('mainmenu', [ 'images/MainMenu.png', 'images/MainMenu-n.png' ], 'images/MainMenu.json');
* ```
*
* Or, if you are using a config object use the `normalMap` property:
*
* ```javascript
* this.load.atlas({
* key: 'mainmenu',
* textureURL: 'images/MainMenu.png',
* normalMap: 'images/MainMenu-n.png',
* atlasURL: 'images/MainMenu.json'
* });
* ```
*
* The normal map file is subject to the same conditions as the image file with regard to the path, baseURL, CORS and XHR Settings.
* Normal maps are a WebGL only feature.
*
* Note: The ability to load this type of file will only be available if the Atlas JSON File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#atlas
* @fires Phaser.Loader.Events#ADD
* @since 3.0.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig|Phaser.Types.Loader.FileTypes.AtlasJSONFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string|string[]} [textureURL] - The absolute or relative URL to load the texture image file from. If undefined or `null` it will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
* @param {object|string} [atlasURL] - The absolute or relative URL to load the texture atlas json data file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json". Or, a well formed JSON object.
* @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - An XHR Settings configuration object for the atlas image file. Used in replacement of the Loaders default XHR Settings.
* @param {Phaser.Types.Loader.XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas json file. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* @classdesc
* A single Audio File suitable for loading by the Loader via the Web Audio API.
*
* This file type loads audio data as an ArrayBuffer over XHR and then decodes it into an AudioBuffer
* using the Web Audio API's `decodeAudioData` method. The resulting AudioBuffer is stored in the
* Phaser Audio Cache, ready for use by the Sound Manager.
*
* If the device does not support the Web Audio API, or if Web Audio has been disabled in the game
* configuration, an `HTML5AudioFile` will be created instead. You do not need to choose between them
* manually — use `Phaser.Loader.LoaderPlugin#audio` and Phaser will select the correct file type
* automatically based on device capabilities.
*
* These are created when you use the Phaser.Loader.LoaderPlugin#audio method and are not typically created directly.
*
* For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audio.
*
* @class AudioFile
* @extends Phaser.Loader.File
* @memberof Phaser.Loader.FileTypes
* @constructor
* @since 3.0.0
*
* @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
* @param {(string|Phaser.Types.Loader.FileTypes.AudioFileConfig)} key - The key to use for this file, or a file configuration object.
* @param {Phaser.Types.Loader.FileTypes.AudioFileURLConfig} [urlConfig] - The absolute or relative URL to load this file from in a config object.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file.
* @param {AudioContext} [audioContext] - The AudioContext this file will use to process itself.
*/
/**
* Takes an array of audio URLs and returns a URL config object for the first entry that
* the current device is capable of playing, based on the audio format indicated by the
* file extension or an explicit `type` property on the URL config object.
*
* Blob and data URIs are always accepted and returned immediately regardless of format.
* For regular URLs, the extension is extracted from the filename and checked against
* `game.device.audio`. If no supported URL is found, `null` is returned.
*
* @function Phaser.Loader.FileTypes.AudioFile.getAudioURL
* @since 3.0.0
*
* @param {Phaser.Game} game - A reference to the Phaser Game instance.
* @param {(string|string[]|Phaser.Types.Loader.FileTypes.AudioFileURLConfig|Phaser.Types.Loader.FileTypes.AudioFileURLConfig[])} urls - One or more audio URLs to test for browser support.
*
* @return {?Phaser.Types.Loader.FileTypes.AudioFileURLConfig} A URL config object with `url` and `type` properties for the first supported audio URL, or `null` if none are supported.
*/
/**
* Adds an Audio or HTML5Audio file, or array of audio files, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.audio('title', [ 'music/Title.ogg', 'music/Title.mp3', 'music/Title.m4a' ]);
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String. It is used to add the file to the global Audio Cache upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Audio Cache.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Audio Cache first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.audio({
* key: 'title',
* url: [ 'music/Title.ogg', 'music/Title.mp3', 'music/Title.m4a' ]
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.AudioFileConfig` for more details.
*
* The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them.
*
* Due to different browsers supporting different audio file types you should usually provide your audio files in a variety of formats.
* ogg, mp3 and m4a are the most common. If you provide an array of URLs then the Loader will determine which _one_ file to load based on
* browser support.
*
* If audio has been disabled in your game, either via the game config, or lack of support from the device, then no audio will be loaded.
*
* Note: The ability to load this type of file will only be available if the Audio File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#audio
* @fires Phaser.Loader.Events#ADD
* @since 3.0.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.AudioFileConfig|Phaser.Types.Loader.FileTypes.AudioFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {(string|string[]|Phaser.Types.Loader.FileTypes.AudioFileURLConfig|Phaser.Types.Loader.FileTypes.AudioFileURLConfig[])} [urls] - The absolute or relative URL to load the audio files from.
* @param {any} [config] - An object containing an `instances` property for HTML5Audio. Defaults to 1.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* Adds a JSON based Audio Sprite, or array of audio sprites, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.audioSprite('kyobi', 'kyobi.json', [
* 'kyobi.ogg',
* 'kyobi.mp3',
* 'kyobi.m4a'
* ]);
* }
* ```
*
* Audio Sprites are a combination of audio files and a JSON configuration.
* The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
*
* If the JSON file includes a 'resource' object then you can let Phaser parse it and load the audio
* files automatically based on its content. To do this exclude the audio URLs from the load:
*
* ```javascript
* function preload ()
* {
* this.load.audioSprite('kyobi', 'kyobi.json');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
* its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
*
* The key must be a unique String. It is used to add the file to the global Audio Cache upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Audio Cache.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Audio Cache first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.audioSprite({
* key: 'kyobi',
* jsonURL: 'audio/Kyobi.json',
* audioURL: [
* 'audio/Kyobi.ogg',
* 'audio/Kyobi.mp3',
* 'audio/Kyobi.m4a'
* ]
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig` for more details.
*
* Instead of passing a URL for the audio JSON data you can also pass in a well formed JSON object instead.
*
* Once the audio has finished loading you can use it create an Audio Sprite by referencing its key:
*
* ```javascript
* this.load.audioSprite('kyobi', 'kyobi.json');
* // and later in your game ...
* var music = this.sound.addAudioSprite('kyobi');
* music.play('title');
* ```
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this file's
* key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
* this is what you would use to retrieve the audio sprite from the Audio Cache.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* Due to different browsers supporting different audio file types you should usually provide your audio files in a variety of formats.
* ogg, mp3 and m4a are the most common. If you provide an array of URLs then the Loader will determine which _one_ file to load based on
* browser support.
*
* If audio has been disabled in your game, either via the game config, or lack of support from the device, then no audio will be loaded.
*
* Note: The ability to load this type of file will only be available if the Audio Sprite File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#audioSprite
* @fires Phaser.Loader.Events#ADD
* @since 3.0.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig|Phaser.Types.Loader.FileTypes.AudioSpriteFileConfig[])} key - The key to use for this file, or a file configuration object, or an array of objects.
* @param {string} jsonURL - The absolute or relative URL to load the json file from. Or a well formed JSON object to use instead.
* @param {(string|string[])} [audioURL] - The absolute or relative URL to load the audio file from. If empty it will be obtained by parsing the JSON file.
* @param {any} [audioConfig] - The audio configuration options.
* @param {Phaser.Types.Loader.XHRSettingsObject} [audioXhrSettings] - An XHR Settings configuration object for the audio file. Used in replacement of the Loaders default XHR Settings.
* @param {Phaser.Types.Loader.XHRSettingsObject} [jsonXhrSettings] - An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader.
*/
/**
* Adds an XML based Bitmap Font, or array of fonts, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.bitmapFont('goldenFont', 'images/GoldFont.png', 'images/GoldFont.xml');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
* its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
*
* Phaser expects the font data to be provided in an XML file format.
* These files are created by software such as the [Angelcode Bitmap Font Generator](http://www.angelcode.com/products/bmfont/),
* [Littera](http://kvazars.com/littera/) or [Glyph Designer](https://71squared.com/glyphdesigner)
*
* Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
*
* The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Texture Manager first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.bitmapFont({
* key: 'goldenFont',
* textureURL: 'images/GoldFont.png',
* fontDataURL: 'images/GoldFont.xml'
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.BitmapFontFileConfig` for more details.
*
* Once the bitmap font has finished loading you can use the key of it when creating a Bitmap Text Game Object:
*
* ```javascript
* this.load.bitmapFont('goldenFont', 'images/GoldFont.png', 'images/GoldFont.xml');
* // and later in your game ...
* this.add.bitmapText(x, y, 'goldenFont', 'Hello World');
* ```
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
* key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
* this is what you would use when creating a Bitmap Text object.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* Phaser also supports the automatic loading of associated normal maps. If you have a normal map to go with this image,
* then you can specify it by providing an array as the `url` where the second element is the normal map:
*
* ```javascript
* this.load.bitmapFont('goldenFont', [ 'images/GoldFont.png', 'images/GoldFont-n.png' ], 'images/GoldFont.xml');
* ```
*
* Or, if you are using a config object use the `normalMap` property:
*
* ```javascript
* this.load.bitmapFont({
* key: 'goldenFont',
* textureURL: 'images/GoldFont.png',
* normalMap: 'images/GoldFont-n.png',
* fontDataURL: 'images/GoldFont.xml'
* });
* ```
*
* The normal map file is subject to the same conditions as the image file with regard to the path, baseURL, CORs and XHR Settings.
* Normal maps are a WebGL only feature.
*
* Note: The ability to load this type of file will only be available if the Bitmap Font File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#bitmapFont
* @fires Phaser.Loader.Events#ADD
* @since 3.0.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.BitmapFontFileConfig|Phaser.Types.Loader.FileTypes.BitmapFontFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string|string[]} [textureURL] - The absolute or relative URL to load the font image file from. If undefined or `null` it will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
* @param {string} [fontDataURL] - The absolute or relative URL to load the font xml data file from. If undefined or `null` it will be set to `<key>.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml".
* @param {Phaser.Types.Loader.XHRSettingsObject} [textureXhrSettings] - An XHR Settings configuration object for the font image file. Used in replacement of the Loaders default XHR Settings.
* @param {Phaser.Types.Loader.XHRSettingsObject} [fontDataXhrSettings] - An XHR Settings configuration object for the font data xml file. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @copyright 2021 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Adds a Compressed Texture file to the current load queue. This feature is WebGL only.
*
* This method takes a key and a configuration object, which lists the different formats
* and files associated with them.
*
* The texture format object should be ordered in GPU priority order, with IMG as the last entry.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* preload ()
* {
* this.load.texture('yourPic', {
* ASTC: { type: 'PVR', textureURL: 'pic-astc-4x4.pvr' },
* PVRTC: { type: 'PVR', textureURL: 'pic-pvrtc-4bpp-rgba.pvr' },
* S3TC: { type: 'PVR', textureURL: 'pic-dxt5.pvr' },
* IMG: { textureURL: 'pic.png' }
* });
* ```
*
* If you wish to load a texture atlas, provide the `atlasURL` property:
*
* ```javascript
* preload ()
* {
* const path = 'assets/compressed';
*
* this.load.texture('yourAtlas', {
* 'ASTC': { type: 'PVR', textureURL: `${path}/textures-astc-4x4.pvr`, atlasURL: `${path}/textures.json` },
* 'PVRTC': { type: 'PVR', textureURL: `${path}/textures-pvrtc-4bpp-rgba.pvr`, atlasURL: `${path}/textures-pvrtc-4bpp-rgba.json` },
* 'S3TC': { type: 'PVR', textureURL: `${path}/textures-dxt5.pvr`, atlasURL: `${path}/textures-dxt5.json` },
* 'IMG': { textureURL: `${path}/textures.png`, atlasURL: `${path}/textures.json` }
* });
* }
* ```
*
* If you wish to load a Multi Atlas, as exported from Texture Packer Pro, use the `multiAtlasURL` property instead:
*
* ```javascript
* preload ()
* {
* const path = 'assets/compressed';
*
* this.load.texture('yourAtlas', {
* 'ASTC': { type: 'PVR', multiAtlasURL: `${path}/textures.json`, multiPath: `${path}` },
* 'PVRTC': { type: 'PVR', multiAtlasURL: `${path}/textures-pvrtc-4bpp-rgba.json`, multiPath: `${path}` },
* 'S3TC': { type: 'PVR', multiAtlasURL: `${path}/textures-dxt5.json`, multiPath: `${path}` },
* 'IMG': { multiAtlasURL: `${path}/textures.json`, multiPath: `${path}` }
* });
* }
* ```
*
* When loading a Multi Atlas you do not need to specify the `textureURL` property as it will be read from the JSON file.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.texture({
* key: 'yourPic',
* url: {
* ASTC: { type: 'PVR', textureURL: 'pic-astc-4x4.pvr' },
* PVRTC: { type: 'PVR', textureURL: 'pic-pvrtc-4bpp-rgba.pvr' },
* S3TC: { type: 'PVR', textureURL: 'pic-dxt5.pvr' },
* IMG: { textureURL: 'pic.png' }
* }
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.CompressedTextureFileConfig` for more details.
*
* The number of formats you provide to this function is up to you, but you should ensure you
* cover the primary platforms where appropriate.
*
* The 'IMG' entry is a fallback to a JPG or PNG, should the browser be unable to load any of the other
* formats presented to this function. You should really always include this, although it is optional.
*
* Phaser supports loading both the PVR and KTX container formats. Within those, it can parse
* the following texture compression formats:
*
* ETC
* ETC1
* ATC
* ASTC
* BPTC
* RGTC
* PVRTC
* S3TC
* S3TCSRGB
*
* For more information about the benefits of compressed textures please see the
* following articles:
*
* Texture Compression in 2020 (https://aras-p.info/blog/2020/12/08/Texture-Compression-in-2020/)
* Compressed GPU Texture Formats (https://themaister.net/blog/2020/08/12/compressed-gpu-texture-formats-a-review-and-compute-shader-decoders-part-1/)
*
* To create compressed texture files use a 3rd party application such as:
*
* Texture Packer (https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3?utm_source=ad&utm_medium=banner&utm_campaign=phaser-2018-10-16)
* PVRTexTool (https://developer.imaginationtech.com/pvrtextool/) - available for Windows, macOS and Linux.
* ASTC Encoder (https://github.com/ARM-software/astc-encoder)
*
* Compressed textures will appear darker than normal textures. This is because
* the Web uses sRGB colorspace, but compressed textures are sampled as linear
* colorspace. You must adjust your textures to be lighter before compression.
* See https://imagemagick.org/Usage/color_basics/#srgb for more details.
* You can do this with ImageMagick (https://imagemagick.org/index.php) using
* the following command:
*
* `magick input.png -set colorspace RGB -colorspace sRGB output.png`
*
* You must ensure that compressed textures meet the following standards for use
* in WebGL and Phaser:
*
* - PVRTC must have a power-of-two width and height.
* - MIPMaps, if present, must have a power-of-two width and height.
* - S3TC, S3TCSRGB, RGTC, and BPTC must have width and height divisible by 4.
* - ASTC must have a Channel Type of Unsigned Normalized Bytes (UNorm). In fact, all compressed textures should be UNorm, but ASTC presents many other options.
*
* If in doubt, a power-of-two resolution is always a safe bet.
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Texture Manager first, before loading a new one.
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this file's
* key. For example, if the prefix was `LEVEL1.` and the key was `Data` the final key will be `LEVEL1.Data` and
* this is what you would use to retrieve the text from the Texture Manager.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* Unlike other file loaders in Phaser, the URLs must include the file extension.
*
* Note: The ability to load this type of file will only be available if the Compressed Texture File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#texture
* @fires Phaser.Loader.Events#ADD
* @since 3.60.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.CompressedTextureFileConfig|Phaser.Types.Loader.FileTypes.CompressedTextureFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {Phaser.Types.Loader.FileTypes.CompressedTextureFileConfig} [url] - The compressed texture configuration object. Not required if passing a config object as the `key` parameter.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* @classdesc
* A single Font File suitable for loading by the Phaser Loader.
*
* This file type loads web fonts using the browser's FontFace API. When processed, it constructs a FontFace
* object from the resolved URL and font format, loads it asynchronously, and registers it with the document's
* fonts collection so it is available to the browser. Once loaded, you can reference the font by its key in
* any Phaser Text object via the `fontFamily` style property.
*
* These are created when you use the Phaser.Loader.LoaderPlugin#font method and are not typically created directly.
*
* For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#font.
*
* @class FontFile
* @extends Phaser.Loader.File
* @memberof Phaser.Loader.FileTypes
* @constructor
* @since 3.87.0
*
* @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
* @param {(string|Phaser.Types.Loader.FileTypes.FontFileConfig)} key - The key to use for this file, or a file configuration object.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.ttf`, i.e. if `key` was "alien" then the URL will be "alien.ttf".
* @param {string} [format='truetype'] - The font type. Should be a string, like 'truetype' or 'opentype'.
* @param {object} [descriptors] - An optional object containing font descriptors for the Font Face. See https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace#descriptors for more details.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file.
*/
/**
* Adds a Font file, or array of Font files, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.font('Nokia', 'assets/nokia.ttf', 'truetype');
* }
* ```
*
* If the font file is open type, you can specify the format:
*
* ```javascript
* function preload ()
* {
* this.load.font('Nokia', 'assets/nokia.otf', 'opentype');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String and not already in-use by another file in the Loader.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.font({
* key: 'Nokia',
* url: 'assets/nokia.ttf',
* format: 'truetype',
* descriptors: { style: 'normal', weight: '400' }
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.FontFileConfig` for more details.
*
* See the MDN documentation at https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace#descriptors for details about the descriptors.
*
* When this file is handled by the Loader, it will create a new Font Face DOM element for it and add it to the document.
*
* You should use the same key given for the font in your Text objects, such as:
*
* ```javascript
* this.add.text(x, y, 'Hello World', { fontFamily: 'Nokia', fontSize: 48 });
* ```
*
* See https://developer.mozilla.org/en-US/docs/Web/API/FontFace for more details.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.ttf". It will always add `.ttf` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* Note: The ability to load this type of file will only be available if the Font File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#font
* @fires Phaser.Loader.Events#ADD
* @since 3.87.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.FontFileConfig|Phaser.Types.Loader.FileTypes.FontFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.ttf`, i.e. if `key` was "alien" then the URL will be "alien.ttf".
* @param {string} [format='truetype'] - The font type. Should be a string, like 'truetype' or 'opentype'.
* @param {object} [descriptors] - An optional object containing font descriptors for the Font Face. See https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace#descriptors for more details.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* Called by the Loader, starts the actual file downloading.
* Creates one or more HTML Audio elements (based on the configured instance count) and assigns the source URL to each.
* During the load the methods onLoad, onError and onProgress are called, based on the Audio element events.
* You shouldn't normally call this method directly, it's meant to be invoked by the Loader.
*
* @method Phaser.Loader.FileTypes.HTML5AudioFile#load
* @since 3.0.0
*/
/**
* Adds an HTML File, or array of HTML Files, to the current load queue. When the files are loaded they
* will be rendered to textures and stored in the Texture Manager.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.htmlTexture('instructions', 'content/intro.html', 256, 512);
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String. It is used to add the file to the global Texture Manager upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Texture Manager.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Texture Manager first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.htmlTexture({
* key: 'instructions',
* url: 'content/intro.html',
* width: 256,
* height: 512
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig` for more details.
*
* Once the file has finished loading you can use it as a texture for a Game Object by referencing its key:
*
* ```javascript
* this.load.htmlTexture('instructions', 'content/intro.html', 256, 512);
* // and later in your game ...
* this.add.image(x, y, 'instructions');
* ```
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
* key. For example, if the prefix was `MENU.` and the key was `Background` the final key will be `MENU.Background` and
* this is what you would use to retrieve the image from the Texture Manager.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.html". It will always add `.html` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* The width and height are the size of the texture to which the HTML will be rendered. It's not possible to determine these
* automatically, so you will need to provide them, either as arguments or in the file config object.
* When the HTML file has loaded a new SVG element is created with a size and viewbox set to the width and height given.
* The SVG file has a body tag added to it, with the HTML file contents included. It then calls `window.Blob` on the SVG,
* and if successful is added to the Texture Manager, otherwise it fails processing. The overall quality of the rendered
* HTML depends on your browser, and some of them may not even support the svg / blob process used. Be aware that there are
* limitations on what HTML can be inside an SVG. You can find out more details in this
* [Mozilla MDN entry](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas).
*
* Note: The ability to load this type of file will only be available if the HTMLTextureFile File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#htmlTexture
* @fires Phaser.Loader.Events#ADD
* @since 3.12.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig|Phaser.Types.Loader.FileTypes.HTMLTextureFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.html`, i.e. if `key` was "alien" then the URL will be "alien.html".
* @param {number} [width=512] - The width of the texture the HTML will be rendered to.
* @param {number} [height=512] - The height of the texture the HTML will be rendered to.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* Adds a JSON File Pack, or array of packs, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.pack('level1', 'data/Level1Files.json');
* }
* ```
*
* A File Pack is a JSON file (or object) that contains details about other files that should be added into the Loader.
* Here is a small example:
*
* ```json
* {
* "test1": {
* "files": [
* {
* "type": "image",
* "key": "taikodrummaster",
* "url": "assets/pics/taikodrummaster.jpg"
* },
* {
* "type": "image",
* "key": "sukasuka-chtholly",
* "url": "assets/pics/sukasuka-chtholly.png"
* }
* ]
* },
* "meta": {
* "generated": "1401380327373",
* "app": "Phaser 3 Asset Packer",
* "url": "https://phaser.io",
* "version": "1.0",
* "copyright": "Photon Storm Ltd. 2018"
* }
* }
* ```
*
* The pack can be split into sections. In the example above you'll see a section called `test1`. You can tell
* the `load.pack` method to parse only a particular section of a pack. The pack is stored in the JSON Cache,
* so you can pass it to the Loader to process additional sections as needed in your game, or you can just load
* them all at once without specifying anything.
*
* The pack file can contain an entry for any type of file that Phaser can load. The object structures exactly
* match that of the file type configs, and all properties available within the file type configs can be used
* in the pack file too. An entry's `type` is the name of the Loader method that will load it, e.g., 'image'.
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* If you call this from outside of `preload` then you are responsible for starting the Loader afterwards and monitoring
* its events to know when it's safe to use the asset. Please see the Phaser.Loader.LoaderPlugin class for more details.
*
* The key must be a unique String. It is used to add the file to the global JSON Cache upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the JSON Cache.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the JSON Cache first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.pack({
* key: 'level1',
* url: 'data/Level1Files.json'
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.PackFileConfig` for more details.
*
* If you have specified a prefix in the loader, via `Loader.setPrefix` then this value will be prepended to this files
* key. For example, if the prefix was `LEVEL1.` and the key was `Waves` the final key will be `LEVEL1.Waves` and
* this is what you would use to retrieve the text from the JSON Cache.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "data"
* and no URL is given then the Loader will set the URL to be "data.json". It will always add `.json` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* You can also optionally provide a `dataKey` to use. This allows you to extract only a part of the JSON and store it in the Cache,
* rather than the whole file. For example, if your JSON data had a structure like this:
*
* ```json
* {
* "level1": {
* "baddies": {
* "aliens": {},
* "boss": {}
* }
* },
* "level2": {},
* "level3": {}
* }
* ```
*
* And you only wanted to store the `boss` data in the Cache, then you could pass `level1.baddies.boss` as the `dataKey`.
*
* Note: The ability to load this type of file will only be available if the Pack File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#pack
* @fires Phaser.Loader.Events#ADD
* @since 3.7.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.PackFileConfig|Phaser.Types.Loader.FileTypes.PackFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
* @param {string} [dataKey] - When the JSON file loads only this property will be stored in the Cache.
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
/**
* Adds a Video file, or array of video files, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.video('intro', [ 'video/level1.mp4', 'video/level1.webm', 'video/level1.mov' ]);
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String. It is used to add the file to the global Video Cache upon a successful load.
* The key should be unique both in terms of files being loaded and files already present in the Video Cache.
* Loading a file using a key that is already taken will result in a warning. If you wish to replace an existing file
* then remove it from the Video Cache first, before loading a new one.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.video({
* key: 'intro',
* url: [ 'video/level1.mp4', 'video/level1.webm', 'video/level1.mov' ],
* noAudio: true
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.VideoFileConfig` for more details.
*
* The URLs can be relative or absolute. If the URLs are relative the `Loader.baseURL` and `Loader.path` values will be prepended to them.
*
* Due to different browsers supporting different video file types you should usually provide your video files in a variety of formats.
* mp4, mov and webm are the most common. If you provide an array of URLs then the Loader will determine which _one_ file to load based on
* browser support, starting with the first in the array and progressing to the end.
*
* Unlike most asset-types, videos do not _need_ to be preloaded. You can create a Video Game Object and then call its `loadURL` method,
* to load a video at run-time, rather than in advance.
*
* Note: The ability to load this type of file will only be available if the Video File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#video
* @fires Phaser.Loader.Events#ADD
* @since 3.20.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.VideoFileConfig|Phaser.Types.Loader.FileTypes.VideoFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {(string|string[]|Phaser.Types.Loader.FileTypes.VideoFileURLConfig|Phaser.Types.Loader.FileTypes.VideoFileURLConfig[])} [urls] - The absolute or relative URL to load the video files from.
* @param {boolean} [noAudio=false] - Does the video have an audio track? If not you can enable auto-playing on it.
*
* @return {this} The Loader instance.
*/
/**
* Returns a value based on the range between `min` and `max` and the percentage given.
*
* @function Phaser.Math.FromPercent
* @since 3.0.0
*
* @param {number} percent - A value representing the percentage, between 0 and 1. Values outside this range are clamped to it.
* @param {number} min - The minimum value.
* @param {number} [max] - The maximum value.
*
* @return {number} The value that is `percent` percent between `min` and `max`.
*/
/**
* Hash a number or list of numbers.
*
* A hash is an unpredictable transformation of an input,
* which always returns the same output from the same input.
* It is useful for generating random data in a predictable way.
*
* For example, you could use a hash to place objects around a scene.
* Given the same inputs, the objects would always appear in the same places,
* even though those places appear random.
*
* This function takes 1-4 numbers as input, and returns a single number from 0-1.
*
* Disclaimer: This function is intended for efficiently generating visual
* variety. It is not intended for cryptographic use. Do not use it for
* security/authentication/encryption purposes. Use a proper tool instead.
*
* Performance note: A 16ms frame has enough time to generate
* tens or hundreds of thousands of hash values, depending on system and other activity.
*
* You can select from different hashing algorithms.
*
* - 0: TRIG. This uses sine functions and dot products to hash the input.
* - 1: PCG. This uses a permuted congruential generator to hash the input,
* but is restricted to integer inputs.
* - 2: PCG_FLOAT. This variant of PCG accepts float inputs.
*
* TRIG is the same algorithm used in Phaser 4's Noise object and relatives.
* It produces decent variety, and accepts any number as input.
* Its precision is 32 bits.
* Its input values may lose distinction if larger than 32 bits (4294967296).
* Its output values cannot differ by more than 1/4294967296.
* This algorithm is designed to work on graphics hardware that lacks
* bitshifting capabilities, and is not state of the art.
*
* PCG is a Permuted Congruential Generator.
* See https://www.pcg-random.org/ for more information on the theory.
* This algorithm is more modern and considered higher quality.
* It runs slightly faster than TRIG.
* It only accepts whole numbers (integers) as input.
* Its precision is 32 bits.
* Its input values may lose distinction if larger than 32 bits (4294967296).
* Its output values cannot differ by more than 1/4294967296.
*
* PCG_FLOAT works just like PCG, but accepts floating-point inputs.
* This conversion process causes it to run slightly slower than TRIG.
* The same precision concerns apply.
*
* If your hash values start clustering, you may be using values
* outside the safe range, where bits available for precision are insufficient.
* You can keep values in a safe range by sampling along circular paths.
* This is why it's useful to have several dimensions of input.
*
* @example
* // Given a `time` value:
* var output = Phaser.Math.Hash([Math.cos(time), Math.sin(time)]);
*
* @function Phaser.Math.Hash
* @since 4.0.0
*
* @param {number|number[]} vector - The number or number list to hash. 1 to 4 numbers.
* @param {number} [algorithm=0] - The algorithm to use. 0 is TRIG. 1 is PCG. 2 is PCG_FLOAT.
*
* @return {number} - A number from 0-1.
*/
/**
* @author Greg McLean <GregDevProjects>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @classdesc
* A 4x4 column-major matrix stored as a Float32Array of 16 values. Used for 3D
* transformations including projection, view, and model matrices. This is the primary
* matrix class for WebGL rendering operations in Phaser, supporting
* perspective/orthographic projection, look-at camera setup, and affine transforms
* (translate, rotate, scale).
*
* Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji
* and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl
*
* @class Matrix4
* @memberof Phaser.Math
* @constructor
* @since 3.0.0
*
* @param {Phaser.Math.Matrix4} [m] - Optional Matrix4 to copy values from.
*/
/**
* Generates a transform matrix based on the given position, scale and rotation.
*
* @method Phaser.Math.Matrix4#transform
* @since 3.50.0
*
* @param {Phaser.Math.Vector3} position - The position vector.
* @param {Phaser.Math.Vector3} scale - The scale vector.
* @param {Phaser.Math.Quaternion} rotation - The rotation quaternion.
*
* @return {this} This Matrix4.
*/
/**
* @author Vladislav Forsh <vlad@robowhale.com>
* @copyright 2021 RoboWhale
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Calculates and sets the w component of this Quaternion based on the current x, y,
* and z components, so that the Quaternion has unit length. Assumes the x, y, and z
* values are already known and that their combined squared length does not exceed 1.
*
* @method Phaser.Math.Quaternion#calculateW
* @since 3.0.0
*
* @return {Phaser.Math.Quaternion} This Quaternion.
*/
/**
* Calculate a smooth interpolation percentage of `x` between `min` and `max`.
*
* The function receives the number `x` as an argument and returns 0 if `x` is less than or equal to the left edge,
* 1 if `x` is greater than or equal to the right edge, and smoothly interpolates, using a Hermite polynomial,
* between 0 and 1 otherwise.
*
* @function Phaser.Math.SmoothStep
* @since 3.0.0
* @see {@link https://en.wikipedia.org/wiki/Smoothstep}
*
* @param {number} x - The input value.
* @param {number} min - The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'.
* @param {number} max - The maximum value, also known as the 'right edge', assumed greater than the 'left edge'.
*
* @return {number} The percentage of interpolation, between 0 and 1.
*/
/**
* Calculate a smoother interpolation percentage of `x` between `min` and `max`.
*
* The function receives the number `x` as an argument and returns 0 if `x` is less than or equal to the left edge,
* 1 if `x` is greater than or equal to the right edge, and smoothly interpolates, using a Hermite polynomial,
* between 0 and 1 otherwise.
*
* Produces an even smoother interpolation than {@link Phaser.Math.SmoothStep}.
*
* @function Phaser.Math.SmootherStep
* @since 3.0.0
* @see {@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
*
* @param {number} x - The input value.
* @param {number} min - The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'.
* @param {number} max - The maximum value, also known as the 'right edge', assumed greater than the 'left edge'.
*
* @return {number} The percentage of interpolation, between 0 and 1.
*/
/**
* Sets the components of this Vector3 from the given array, based on the offset.
*
* Vector3.x = array[offset]
* Vector3.y = array[offset + 1]
* Vector3.z = array[offset + 2]
*
* @method Phaser.Math.Vector3#fromArray
* @since 3.50.0
*
* @param {number[]} array - The array of values to get this Vector from.
* @param {number} [offset=0] - The offset index into the array.
*
* @return {Phaser.Math.Vector3} This Vector3.
*/
/**
* @author samme
* @copyright 2025 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author @samme
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Applies a circular ease-in to the given value. This easing is based on the equation of a circle,
* producing a curve that starts very slowly and then accelerates sharply toward the end. It is the
* complement of `Circular.Out` and is commonly used for animations that need a hesitant start before
* snapping into motion.
*
* @function Phaser.Math.Easing.Circular.In
* @since 3.0.0
*
* @param {number} v - The value to be eased.
*
* @return {number} The eased value.
*/
/**
* Applies a circular ease-out effect to `v`, based on the equation of a unit circle.
* The motion starts at full speed and decelerates smoothly to a stop, following the
* curve of a quarter-circle. `v` should be in the range 0 to 1.
*
* @function Phaser.Math.Easing.Circular.Out
* @since 3.0.0
*
* @param {number} v - The value to be eased, in the range 0 to 1.
*
* @return {number} The eased value, in the range 0 to 1.
*/
/**
* Calculates a cubic bezier interpolated value for a given parameter `t`, based on four
* control points. The curve passes through `p0` at `t=0` and `p3` at `t=1`, while `p1`
* and `p2` act as pull points that shape the curve between those endpoints without
* necessarily being on it. This makes cubic bezier interpolation well-suited for smooth,
* art-directed transitions in animations, camera paths, and procedural movement.
*
* https://medium.com/@adrian_cooney/bezier-interpolation-13b68563313a
*
* @function Phaser.Math.Interpolation.CubicBezier
* @since 3.0.0
*
* @param {number} t - The percentage of interpolation, between 0 and 1.
* @param {number} p0 - The start point.
* @param {number} p1 - The first control point.
* @param {number} p2 - The second control point.
* @param {number} p3 - The end point.
*
* @return {number} The interpolated value.
*/
/**
* Performs linear interpolation across an array of values.
*
* Given an array of values `v` and a progress factor `k` in the range 0 to 1,
* this function maps `k` to a position along the array and returns the linearly
* interpolated value between the two nearest array elements. A `k` of 0 returns
* a value near the first element, while a `k` of 1 returns a value near the last.
* Values of `k` outside the range 0 to 1 are extrapolated beyond the ends of the array.
*
* @function Phaser.Math.Interpolation.Linear
* @since 3.0.0
* @see {@link https://en.wikipedia.org/wiki/Linear_interpolation}
*
* @param {number[]} v - The input array of values to interpolate between.
* @param {!number} k - The percentage of interpolation, between 0 and 1.
*
* @return {!number} The interpolated value.
*/
/**
* A Smooth Step interpolation method that uses the Smoothstep function to produce a smooth, S-shaped
* transition between the `min` and `max` values. Unlike linear interpolation, Smooth Step eases in
* and out at both edges, resulting in a gradual start and end to the transition. This makes it
* well-suited for animations and transitions where abrupt changes at the boundaries would look unnatural.
*
* The interpolation parameter `t` is first remapped via the Smoothstep curve (which clamps and applies
* a cubic Hermite function), and the result is then used to linearly interpolate between `min` and `max`.
*
* @function Phaser.Math.Interpolation.SmoothStep
* @since 3.9.0
* @see {@link https://en.wikipedia.org/wiki/Smoothstep}
*
* @param {number} t - The percentage of interpolation, between 0 and 1.
* @param {number} min - The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'.
* @param {number} max - The maximum value, also known as the 'right edge', assumed greater than the 'left edge'.
*
* @return {number} The interpolated value.
*/
/**
* An interpolation method based on Ken Perlin's Smoother Step function, which is an improved
* variant of the standard Smooth Step curve. Unlike Smooth Step, which has zero first derivatives
* at the endpoints, Smoother Step also has zero second derivatives at the endpoints, resulting in
* an even smoother S-curve transition between `min` and `max`. Use this when you need particularly
* fluid easing with no perceivable acceleration or deceleration artifacts at the start or end of
* the transition.
*
* @function Phaser.Math.Interpolation.SmootherStep
* @since 3.9.0
* @see {@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
*
* @param {number} t - The percentage of interpolation, between 0 and 1.
* @param {number} min - The minimum value, also known as the 'left edge', assumed smaller than the 'right edge'.
* @param {number} max - The maximum value, also known as the 'right edge', assumed greater than the 'left edge'.
*
* @return {number} The interpolated value.
*/
/**
* @classdesc
* A seeded Random Data Generator.
*
* Access via `Phaser.Math.RND` which is an instance of this class pre-defined
* by Phaser. Or, create your own instance to use as you require.
*
* The `Math.RND` generator is seeded by the Game Config property value `seed`.
* If no such config property exists, a random number is used.
*
* If you create your own instance of this class you should provide a seed for it.
* If no seed is given it will use a 'random' one based on Date.now.
*
* @class RandomDataGenerator
* @memberof Phaser.Math
* @constructor
* @since 3.0.0
*
* @param {(string|string[])} [seeds] - The seeds to use for the random number generator.
*/
/**
* Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
*
* @method Phaser.Math.RandomDataGenerator#uuid
* @since 3.0.0
*
* @return {string} A valid RFC4122 version4 ID hex string
*/
/**
* This body's rotation, in degrees, based on its angular acceleration and angular velocity.
* The Body's rotation controls the `angle` of its Game Object.
* It doesn't rotate the Body's own geometry, which is always an axis-aligned rectangle or a circle.
*
* @name Phaser.Physics.Arcade.Body#rotation
* @type {number}
* @since 3.0.0
*/
/**
* Sets whether this Body should calculate its velocity based on its change in
* position every frame. The default, which is to not do this, means that you
* make this Body move by setting the velocity directly. However, if you are
* trying to move this Body via a Tween, or have it follow a Path, then you
* should enable this instead. This will allow it to still collide with other
* bodies, something that isn't possible if you're just changing its position directly.
*
* @method Phaser.Physics.Arcade.Body#setDirectControl
* @since 3.70.0
*
* @param {boolean} [value=true] - `true` if the Body calculate velocity based on changes in position, otherwise `false`.
*
* @return {Phaser.Physics.Arcade.Body} This Body object.
*/
/**
* Executes the vertical separation and velocity exchange for the two bodies, based on
* the collision side determined by the `Check` function. Handles all combinations of
* pushable and non-pushable bodies, distributing overlap and recalculating post-collision
* velocities accordingly.
*
* @function Phaser.Physics.Arcade.ProcessY.Run
* @ignore
* @since 3.50.0
*
* @param {number} side - The side to test. As passed in by the `Check` function.
*
* @return {boolean} Always returns `true`.
*/
/**
* Separates two overlapping bodies on the X-axis (horizontally).
*
* Separation involves moving two overlapping bodies so they don't overlap anymore and adjusting their velocities based on their mass. This is a core part of collision detection.
*
* The bodies won't be separated if there is no horizontal overlap between them, if both are immovable, or if either one uses custom separation logic via `customSeparateX`.
*
* @function Phaser.Physics.Arcade.SeparateX
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - If `true`, the bodies will only have their overlap data set and no separation will take place.
* @param {number} bias - A value to add to the delta value during overlap checking. Used to prevent sprite tunneling.
* @param {number} [overlap] - If given then this value will be used as the overlap and no check will be run.
*
* @return {boolean} `true` if the two bodies overlap horizontally, otherwise `false`.
*/
/**
* Separates two overlapping bodies on the Y-axis (vertically).
*
* Separation involves moving two overlapping bodies so they don't overlap anymore and adjusting their velocities based on their mass. This is a core part of collision detection.
*
* The bodies won't be separated if there is no vertical overlap between them, if they are static, or if either one uses custom logic for its separation.
*
* @function Phaser.Physics.Arcade.SeparateY
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - If `true`, the bodies will only have their overlap data set and no separation will take place.
* @param {number} bias - A value to add to the delta value during overlap checking. Used to prevent sprite tunneling.
* @param {number} [overlap] - If given then this value will be used as the overlap and no check will be run.
*
* @return {boolean} `true` if the two bodies overlap vertically, otherwise `false`.
*/
/**
* Advances the simulation based on the elapsed time and fps rate.
*
* This is called automatically by your Scene and does not need to be invoked directly.
*
* @method Phaser.Physics.Arcade.World#update
* @fires Phaser.Physics.Arcade.Events#WORLD_STEP
* @since 3.0.0
*
* @param {number} time - The current timestamp as generated by the Request Animation Frame or SetTimeout.
* @param {number} delta - The delta time, in ms, elapsed since the last frame.
*/
/**
* Checks if the two given Arcade Physics bodies will collide, or not,
* based on their collision mask and collision categories.
*
* @method Phaser.Physics.Arcade.World#canCollide
* @since 3.70.0
*
* @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} body1 - The first body to check.
* @param {Phaser.Types.Physics.Arcade.ArcadeColliderType} body2 - The second body to check.
*
* @return {boolean} True if the two bodies will collide, otherwise false.
*/
/**
* Sets whether this Body should calculate its velocity based on its change in
* position every frame. The default, which is to not do this, means that you
* make this Body move by setting the velocity directly. However, if you are
* trying to move this Body via a Tween, or have it follow a Path, then you
* should enable this instead. This will allow it to still collide with other
* bodies, something that isn't possible if you're just changing its position directly.
*
* @method Phaser.Physics.Arcade.Components.Enable#setDirectControl
* @since 3.70.0
*
* @param {boolean} [value=true] - `true` if the Body calculates velocity based on changes in position, otherwise `false`.
*
* @return {this} This Game Object.
*/
/**
* Syncs the Body's position and size with its parent Game Object.
* You don't need to call this for Dynamic Bodies, as it happens automatically.
* But for Static bodies it's a useful way of modifying the position of a Static Body
* in the Physics World, based on its Game Object.
*
* @method Phaser.Physics.Arcade.Components.Enable#refreshBody
* @since 3.1.0
*
* @return {this} This Game Object.
*
* @see Phaser.Physics.Arcade.StaticBody#updateFromGameObject
*/
/**
* Internal function to process the horizontal separation of a physics body from a tile.
* It updates the body's left or right blocked flags based on the direction of separation,
* moves the body by the separation amount along the x-axis, updates its center, and then
* either zeroes the horizontal velocity or applies a bounce depending on the body's bounce coefficient.
*
* @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationX
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {number} x - The x-axis separation distance, in pixels. A negative value indicates the body is blocked on the left; a positive value indicates it is blocked on the right.
*/
/**
* Internal function to process the vertical separation of a physics body from a tile.
*
* Updates the body's blocked flags based on the direction of separation, adjusts the
* body's vertical position by the separation amount, and then either zeroes the vertical
* velocity or applies the body's bounce factor to reverse it.
*
* @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationY
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {number} y - The vertical separation amount, in pixels. A negative value indicates the body was blocked from above; a positive value indicates it was blocked from below.
*/
/**
* The core separation function to separate a physics body from a tile, resolving any overlap
* between them. It determines which axis to process first based on the body's current velocity:
* if the body is moving faster horizontally the X axis is checked first, and vice versa. When
* moving diagonally into a tile with colliding faces on both axes, the axis of least overlap is
* prioritized. Separation is performed by calling `TileCheckX` and/or `TileCheckY` as appropriate,
* and the check short-circuits early if the first axis separation is sufficient to fully resolve
* the intersection.
*
* @function Phaser.Physics.Arcade.Tilemap.SeparateTile
* @since 3.0.0
*
* @param {number} i - The index of the tile within the map data.
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {Phaser.Tilemaps.Tile} tile - The tile to collide against.
* @param {Phaser.Geom.Rectangle} tileWorldRect - A rectangle-like object defining the dimensions of the tile.
* @param {Phaser.Tilemaps.TilemapLayer} tilemapLayer - The tilemapLayer to collide against.
* @param {number} tileBias - The tile bias value, defined by the `World.TILE_BIAS` constant. Used to prevent fast-moving bodies from tunneling through thin tiles.
* @param {boolean} isLayer - Is this check coming from a TilemapLayer or an array of tiles?
*
* @return {boolean} `true` if the body was separated, otherwise `false`.
*/
/**
* @classdesc
*
* The Body Bounds class contains methods to help you extract the world coordinates from various points around
* the bounds of a Matter Body. Because Matter bodies are positioned based on their center of mass, and not a
* dimension based center, you often need to get the bounds coordinates in order to properly align them in the world.
*
* You can access this class via the MatterPhysics class from a Scene, i.e.:
*
* ```javascript
* this.matter.bodyBounds.getTopLeft(body);
* ```
*
* See also the `MatterPhysics.alignBody` method.
*
* @class BodyBounds
* @memberof Phaser.Physics.Matter
* @constructor
* @since 3.22.0
*/
/**
* Takes a Body and returns the world coordinates of the top-left of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getTopLeft
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the top-center of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getTopCenter
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the top-right of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getTopRight
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the left-center of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getLeftCenter
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the center of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getCenter
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the right-center of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getRightCenter
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the bottom-left of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getBottomLeft
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the bottom-center of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getBottomCenter
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Takes a Body and returns the world coordinates of the bottom-right of its _bounds_.
*
* Body bounds are updated by Matter each step and factor in scale and rotation.
* This will return the world coordinate based on the body's _current_ position and bounds.
*
* @method Phaser.Physics.Matter.BodyBounds#getBottomRight
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to get the position from.
* @param {number} [x=0] - Optional horizontal offset to add to the returned coordinates.
* @param {number} [y=0] - Optional vertical offset to add to the returned coordinates.
*
* @return {(Phaser.Math.Vector2|false)} A Vector2 containing the coordinates, or `false` if it was unable to parse the body.
*/
/**
* Creates a body using data exported from the application PhysicsEditor (https://www.codeandweb.com/physicseditor)
*
* The PhysicsEditor file should be loaded as JSON:
*
* ```javascript
* preload ()
* {
* this.load.json('vehicles', 'assets/vehicles.json);
* }
*
* create ()
* {
* const vehicleShapes = this.cache.json.get('vehicles');
* this.matter.add.fromPhysicsEditor(400, 300, vehicleShapes.truck);
* }
* ```
*
* Do not pass the entire JSON file to this method, but instead pass one of the shapes contained within it.
*
* If you pass in an `options` object, any settings in there will override those in the PhysicsEditor config object.
*
* @method Phaser.Physics.Matter.Factory#fromPhysicsEditor
* @since 3.22.0
*
* @param {number} x - The horizontal world location of the body.
* @param {number} y - The vertical world location of the body.
* @param {any} config - The JSON data exported from PhysicsEditor.
* @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation.
* @param {boolean} [addToWorld=true] - Should the newly created body be immediately added to the World?
*
* @return {MatterJS.BodyType} A Matter JS Body.
*/
/**
* Creates a body using the path data from an SVG file.
*
* SVG Parsing requires the pathseg polyfill from https://github.com/progers/pathseg
*
* The SVG file should be loaded as XML, as this method requires the ability to extract
* the path data from it. I.e.:
*
* ```javascript
* preload ()
* {
* this.load.xml('face', 'assets/face.svg);
* }
*
* create ()
* {
* this.matter.add.fromSVG(400, 300, this.cache.xml.get('face'));
* }
* ```
*
* @method Phaser.Physics.Matter.Factory#fromSVG
* @since 3.22.0
*
* @param {number} x - The X coordinate of the body.
* @param {number} y - The Y coordinate of the body.
* @param {object} xml - The SVG Path data.
* @param {number} [scale=1] - Scale the vertices by this amount after creation.
* @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation.
* @param {boolean} [addToWorld=true] - Should the newly created body be immediately added to the World?
*
* @return {MatterJS.BodyType} A Matter JS Body.
*/
/**
* Chains all bodies in the given composite together using constraints.
*
* @method Phaser.Physics.Matter.Factory#chain
* @since 3.0.0
*
* @param {MatterJS.CompositeType} composite - The composite in which all bodies will be chained together sequentially.
* @param {number} xOffsetA - The horizontal offset of the BodyA constraint. This is a percentage based on the body size, not a world position.
* @param {number} yOffsetA - The vertical offset of the BodyA constraint. This is a percentage based on the body size, not a world position.
* @param {number} xOffsetB - The horizontal offset of the BodyB constraint. This is a percentage based on the body size, not a world position.
* @param {number} yOffsetB - The vertical offset of the BodyB constraint. This is a percentage based on the body size, not a world position.
* @param {Phaser.Types.Physics.Matter.MatterConstraintConfig} [options] - An optional Constraint configuration object that is used to set initial Constraint properties on creation.
*
* @return {MatterJS.CompositeType} The original composite that was passed to this method.
*/
/**
* @classdesc
* The Phaser Matter plugin provides the ability to use the Matter JS Physics Engine within your Phaser games.
*
* Unlike Arcade Physics, the other physics system provided with Phaser, Matter JS is a full-body physics system.
* It features:
*
* * Rigid bodies
* * Compound bodies
* * Composite bodies
* * Concave and convex hulls
* * Physical properties (mass, area, density etc.)
* * Restitution (elastic and inelastic collisions)
* * Collisions (broad-phase, mid-phase and narrow-phase)
* * Stable stacking and resting
* * Conservation of momentum
* * Friction and resistance
* * Constraints
* * Gravity
* * Sleeping and static bodies
* * Rounded corners (chamfering)
* * Views (translate, zoom)
* * Collision queries (raycasting, region tests)
* * Time scaling (slow-mo, speed-up)
*
* Configuration of Matter is handled via the Matter World Config object, which can be passed in either the
* Phaser Game Config, or Phaser Scene Config. Here is a basic example:
*
* ```js
* physics: {
* default: 'matter',
* matter: {
* enableSleeping: true,
* gravity: {
* y: 0
* },
* debug: {
* showBody: true,
* showStaticBody: true
* }
* }
* }
* ```
*
* This class acts as an interface between a Phaser Scene and a single instance of the Matter Engine.
*
* Use it to access the most common Matter features and helper functions.
*
* You can find details, documentation and examples on the Matter JS website: https://brm.io/matter-js/
*
* @class MatterPhysics
* @memberof Phaser.Physics.Matter
* @constructor
* @since 3.0.0
*
* @param {Phaser.Scene} scene - The Phaser Scene that owns this Matter Physics instance.
*/
/**
* A reference to the `Matter.Svg` module.
*
* The `Matter.Svg` module contains methods for converting SVG images into an array of vector points.
*
* To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg
*
* @name Phaser.Physics.Matter.MatterPhysics#svg
* @type {MatterJS.SvgFactory}
* @since 3.22.0
*/
/**
* Sets the collision filter mask of all given Matter Bodies to the given value.
*
* Two Matter Bodies with different collision groups will only collide if each one includes the others
* category in its mask based on a bitwise AND operation: `(categoryA & maskB) !== 0` and
* `(categoryB & maskA) !== 0` are both true.
*
* @method Phaser.Physics.Matter.MatterPhysics#setCollidesWith
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody[]} bodies - An array of bodies to update. If falsey it will use all bodies in the world.
* @param {(number|number[])} categories - A unique category bitfield, or an array of them.
*
* @return {this} This Matter Physics instance.
*/
/**
* Apply a force to a body based on the given angle and speed.
* If no angle is given, the current body angle is used.
*
* Use very small speed values, such as 0.1, depending on the mass and required velocity.
*
* @method Phaser.Physics.Matter.MatterPhysics#applyForceFromAngle
* @since 3.22.0
*
* @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world.
* @param {number} speed - A speed value to be applied to a directional force.
* @param {number} [angle] - The angle, in radians, to apply the force from. Leave undefined to use the current body angle.
*
* @return {this} This Matter Physics instance.
*/
/**
* Aligns a Body, or Matter Game Object, against the given coordinates.
*
* The alignment takes place using the body bounds, which take into consideration things
* like body scale and rotation.
*
* Although a Body has a `position` property, it is based on the center of mass for the body,
* not a dimension based center. This makes aligning bodies difficult, especially if they have
* rotated or scaled. This method will derive the correct position based on the body bounds and
* its center of mass offset, in order to align the body with the given coordinate.
*
* For example, if you wanted to align a body so it sat in the bottom-center of the
* Scene, and the world was 800 x 600 in size:
*
* ```javascript
* this.matter.alignBody(body, 400, 600, Phaser.Display.Align.BOTTOM_CENTER);
* ```
*
* You pass in 400 for the x coordinate, because that is the center of the world, and 600 for
* the y coordinate, as that is the base of the world.
*
* @method Phaser.Physics.Matter.MatterPhysics#alignBody
* @since 3.22.0
*
* @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to align.
* @param {number} x - The horizontal position to align the body to.
* @param {number} y - The vertical position to align the body to.
* @param {number} align - One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`.
*
* @return {this} This Matter Physics instance.
*/
/**
* @author Joachim Grill <joachim@codeandweb.com>
* @author Richard Davey <rich@phaser.io>
* @copyright 2018 CodeAndWeb GmbH
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* A namespace containing methods for parsing body and fixture data exported from PhysicsEditor
* (https://www.codeandweb.com/physicseditor), a visual collision shape editor for game sprites.
*
* Use `PhysicsEditorParser.parseBody()` to build a compound Matter.js body from a physics data file
* created and exported by PhysicsEditor. The exported JSON describes the body's fixtures (child
* bodies), each of which can be a circle or a set of convex polygon vertices. The parser assembles
* all fixtures into a single compound Matter.js body positioned at the given world coordinates.
*
* @namespace Phaser.Physics.Matter.PhysicsEditorParser
* @since 3.10.0
*/
/**
* The internal update method. This is called automatically by the parent Scene.
*
* Moves the simulation forward in time by delta ms. Uses `World.correction` value as an optional number that
* specifies the time correction factor to apply to the update. This can help improve the accuracy of the
* simulation in cases where delta is changing between updates. The value of correction is defined as `delta / lastDelta`,
* i.e. the percentage change of delta over the last step. Therefore the value is always 1 (no correction) when
* delta is constant (or when no correction is desired, which is the default).
* See the paper on Time Corrected Verlet for more information.
*
* Triggers `beforeUpdate` and `afterUpdate` events. Triggers `collisionStart`, `collisionActive` and `collisionEnd` events.
*
* If the World is paused, `update` is still run, but exits early and does not update the Matter Engine.
*
* @method Phaser.Physics.Matter.World#update
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Sets the restitution (bounciness) of this Game Object's Matter.js physics body.
* This controls how much of the body's kinetic energy is preserved after a collision.
*
* @method Phaser.Physics.Matter.Components.Bounce#setBounce
* @since 3.0.0
*
* @param {number} value - A Number that defines the restitution (elasticity) of the body. The value is always positive and is in the range (0, 1). A value of 0 means collisions may be perfectly inelastic and no bouncing may occur. A value of 0.8 means the body may bounce back with approximately 80% of its kinetic energy. Note that collision response is based on pairs of bodies, and that restitution values are combined with the following formula: `Math.max(bodyA.restitution, bodyB.restitution)`
*
* @return {this} This Game Object instance.
*/
/**
* Sets the collision mask for this Game Object's Matter Body. Two Matter Bodies with different collision groups will only
* collide if each one includes the other's category in its mask based on a bitwise AND, i.e. `(categoryA & maskB) !== 0`
* and `(categoryB & maskA) !== 0` are both true.
*
* @method Phaser.Physics.Matter.Components.Collision#setCollidesWith
* @since 3.0.0
*
* @param {(number|number[])} categories - A unique category bitfield, or an array of them.
*
* @return {this} This Game Object instance.
*/
/**
* Set this Game Object to create and use a new Body based on the configuration object given.
*
* Calling this method resets all previous properties you may have set on the body, including
* plugins, mass, friction, collision categories, etc. So be sure to re-apply these as needed.
*
* @method Phaser.Physics.Matter.Components.SetBody#setBody
* @since 3.0.0
*
* @param {(string|Phaser.Types.Physics.Matter.MatterSetBodyConfig)} config - Either a string, such as `circle`, or a Matter Set Body Configuration object.
* @param {Phaser.Types.Physics.Matter.MatterBodyConfig} [options] - An optional Body configuration object that is used to set initial Body properties on creation.
*
* @return {this} This Game Object instance.
*/
/**
* The `Matter.Body` module contains methods for creating and manipulating body models.
* A `Matter.Body` is a rigid body that can be simulated by a `Matter.Engine`.
* Factories for commonly used body configurations (such as rectangles, circles and other polygons) can be found in the module `Matter.Bodies`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
* @class Body
*/
/**
* Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* Vertices must be specified in clockwise order.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {} options
* @return {body} body
*/
/**
* Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to `body.density`).
* Vertices will be automatically transformed to be orientated around their centre of mass as the origin.
* They are then automatically translated to world space based on `body.position`.
*
* The `vertices` argument should be passed as an array of `Matter.Vector` points (or a `Matter.Vertices` array).
* Vertices must form a convex hull, concave hulls are not supported.
*
* @method setVertices
* @param {body} body
* @param {vector[]} vertices
*/
/**
* A `Number` that defines the density of the body, that is its mass per unit area.
* If you pass the density via `Body.create` the `mass` property is automatically calculated for you based on the size (area) of the object.
* This is generally preferable to simply setting mass and allows for more intuitive definition of materials (e.g. rock has a higher density than wood).
*
* @property density
* @type number
* @default 0.001
*/
/**
* A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`.
* A value of `0` means collisions may be perfectly inelastic and no bouncing may occur.
* A value of `0.8` means the body may bounce back with approximately 80% of its kinetic energy.
* Note that collision response is based on _pairs_ of bodies, and that `restitution` values are _combined_ with the following formula:
*
* Math.max(bodyA.restitution, bodyB.restitution)
*
* @property restitution
* @type number
* @default 0
*/
/**
* A `Number` that defines the friction of the body. The value is always positive and is in the range `(0, 1)`.
* A value of `0` means that the body may slide indefinitely.
* A value of `1` means the body may come to a stop almost instantly after a force is applied.
*
* The effects of the value may be non-linear.
* High values may be unstable depending on the body.
* The engine uses a Coulomb friction model including static and kinetic friction.
* Note that collision response is based on _pairs_ of bodies, and that `friction` values are _combined_ with the following formula:
*
* Math.min(bodyA.friction, bodyB.friction)
*
* @property friction
* @type number
* @default 0.1
*/
/**
* The `Matter.Composite` module contains methods for creating and manipulating composite bodies.
* A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure.
* It is important to use the functions in this module to modify composites, rather than directly modifying their properties.
* Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Composite
*/
/**
* The `Matter.Query` module contains methods for performing collision queries.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Query
*/
/**
* The `Matter.Constraint` module contains methods for creating and manipulating constraints.
* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).
* The stiffness of constraints can be modified to create springs or elastic.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Constraint
*/
/**
* Creates a new constraint.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* To simulate a revolute constraint (or pin joint) set `length: 0` and a high `stiffness` value (e.g. `0.7` or above).
* If the constraint is unstable, try lowering the `stiffness` value and / or increasing `engine.constraintIterations`.
* For compound bodies, constraints must be applied to the parent body (not one of its parts).
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {} options
* @return {constraint} constraint
*/
/**
* A `Number` that specifies the damping of the constraint,
* i.e. the amount of resistance applied to each body based on their velocities to limit the amount of oscillation.
* Damping will only be apparent when the constraint also has a very low `stiffness`.
* A value of `0.1` means the constraint will apply heavy damping, resulting in little to no oscillation.
* A value of `0` means the constraint will apply no damping.
*
* @property damping
* @type number
* @default 0
*/
/**
* Provide the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module to enable
* concave vertex decomposition support when using `Bodies.fromVertices` e.g. `Common.setDecomp(require('poly-decomp'))`.
* @method setDecomp
* @param {} decomp The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module.
*/
/**
* Returns the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module provided through `Common.setDecomp`,
* otherwise returns the global `decomp` if set.
* @method getDecomp
* @return {} The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module if provided.
*/
/**
* The `Matter.Engine` module contains methods for creating and manipulating engines.
* An engine is a controller that manages updating the simulation of the world.
* See `Matter.Runner` for an optional game loop utility.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Engine
*/
/**
* Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {object} [options]
* @return {engine} engine
*/
/**
* The `Matter.Events` module contains methods to fire and listen to events on other objects.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Events
*/
/**
* Parses a version string into its components.
* Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).
* Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.
* Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).
* Only the following range types are supported:
* - Tilde ranges e.g. `~1.2.3`
* - Caret ranges e.g. `^1.2.3`
* - Greater than ranges e.g. `>1.2.3`
* - Greater than or equal ranges e.g. `>=1.2.3`
* - Exact version e.g. `1.2.3`
* - Any version `*`
* @method versionParse
* @param range {string} The version string.
* @return {object} The version range parsed into its components.
*/
/**
* The `Matter.Runner` module is an optional utility which provides a game loop,
* that handles continuously updating a `Matter.Engine` for you within a browser.
* It is intended for development and debugging purposes, but may also be suitable for simple games.
* If you are using your own game loop instead, then you do not need the `Matter.Runner` module.
* Instead just call `Engine.update(engine, delta)` in your own loop.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Runner
*/
/**
* The `Matter.Bodies` module contains factory methods for creating rigid body models
* with commonly used body configurations (such as rectangles, circles and other polygons).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Bodies
*/
/**
* Utility to create a compound body based on set(s) of vertices.
*
* _Note:_ To optionally enable automatic concave vertices decomposition the [poly-decomp](https://github.com/schteppe/poly-decomp.js)
* package must be first installed and provided see `Common.setDecomp`, otherwise the convex hull of each vertex set will be used.
*
* The resulting vertices are reorientated about their centre of mass,
* and offset such that `body.position` corresponds to this point.
*
* The resulting offset may be found if needed by subtracting `body.bounds` from the original input bounds.
* To later move the centre of mass see `Body.setCentre`.
*
* Note that automatic conconcave decomposition results are not always optimal.
* For best results, simplify the input vertices as much as possible first.
* By default this function applies some addtional simplification to help.
*
* Some outputs may also require further manual processing afterwards to be robust.
* In particular some parts may need to be overlapped to avoid collision gaps.
* Thin parts and sharp points should be avoided or removed where possible.
*
* The options parameter object specifies any `Matter.Body` properties you wish to override the defaults.
*
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method fromVertices
* @param {number} x
* @param {number} y
* @param {array} vertexSets One or more arrays of vertex points e.g. `[[{ x: 0, y: 0 }...], ...]`.
* @param {object} [options] The body options.
* @param {bool} [flagInternal=false] Optionally marks internal edges with `isInternal`.
* @param {number} [removeCollinear=0.01] Threshold when simplifying vertices along the same edge.
* @param {number} [minimumArea=10] Threshold when removing small parts.
* @param {number} [removeDuplicatePoints=0.01] Threshold when simplifying nearby vertices.
* @return {body}
*/
/**
* Takes an array of Body objects and flags all internal edges (coincident parts) based on the maxDistance
* value. The array is changed in-place and returned, so you can pass this function a `Body.parts` property.
*
* @method flagCoincidentParts
* @param {body[]} parts - The Body parts, or array of bodies, to flag.
* @param {number} [maxDistance=5]
* @return {body[]} The modified `parts` parameter.
*/
/**
* The `Matter.Composites` module contains factory methods for creating composite bodies
* with commonly used configurations (such as stacks and chains).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Composites
*/
/**
* This has now moved to the [newtonsCradle example](https://github.com/liabru/matter-js/blob/master/examples/newtonsCradle.js), follow that instead as this function is deprecated here.
* @deprecated moved to newtonsCradle example
* @method newtonsCradle
* @param {number} x Starting position in X.
* @param {number} y Starting position in Y.
* @param {number} number
* @param {number} size
* @param {number} length
* @return {composite} A new composite newtonsCradle body
*/
/**
* This has now moved to the [car example](https://github.com/liabru/matter-js/blob/master/examples/car.js), follow that instead as this function is deprecated here.
* @deprecated moved to car example
* @method car
* @param {number} x Starting position in X.
* @param {number} y Starting position in Y.
* @param {number} width
* @param {number} height
* @param {number} wheelSize
* @return {composite} A new composite car body
*/
/**
* This has now moved to the [softBody example](https://github.com/liabru/matter-js/blob/master/examples/softBody.js)
* and the [cloth example](https://github.com/liabru/matter-js/blob/master/examples/cloth.js), follow those instead as this function is deprecated here.
* @deprecated moved to softBody and cloth examples
* @method softBody
* @param {number} x Starting position in X.
* @param {number} y Starting position in Y.
* @param {number} columns
* @param {number} rows
* @param {number} columnGap
* @param {number} rowGap
* @param {boolean} crossBrace
* @param {number} particleRadius
* @param {} particleOptions
* @param {} constraintOptions
* @return {composite} A new composite softBody
*/
/**
* The `Matter.Svg` module contains methods for converting SVG images into an array of vector points.
*
* To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Svg
*/
/**
* The `Matter.Vector` module contains methods for creating and manipulating vectors.
* Vectors are the basis of all the geometry related operations in the engine.
* A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Vector
*/
/**
* The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices.
* A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`.
* A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Vertices
*/
/**
* @author Stefan Hedman <schteppe@gmail.com> (http://steffe.se)
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://github.com/photonstorm/phaser3-plugin-template/blob/master/LICENSE|MIT License}
*/
/**
* Returns the core plugin object from the cache based on the given key.
*
* @method Phaser.Plugins.PluginCache.getCore
* @since 3.8.0
*
* @param {string} key - The key of the core plugin to get.
*
* @return {Phaser.Types.Plugins.CorePluginContainer} The core plugin object.
*/
/**
* Returns the custom plugin object from the cache based on the given key.
*
* @method Phaser.Plugins.PluginCache.getCustom
* @since 3.8.0
*
* @param {string} key - The key of the custom plugin to get.
*
* @return {Phaser.Types.Plugins.CustomPluginContainer} The custom plugin object.
*/
/**
* Returns the plugin constructor function from the custom plugin cache based on the given key,
* or `null` if no entry for that key exists.
*
* @method Phaser.Plugins.PluginCache.getCustomClass
* @since 3.8.0
*
* @param {string} key - The key of the custom plugin to get.
*
* @return {function} The custom plugin object.
*/
/**
* Removes a core plugin based on the given key.
*
* @method Phaser.Plugins.PluginCache.remove
* @since 3.8.0
*
* @param {string} key - The key of the core plugin to remove.
*/
/**
* Removes a custom plugin based on the given key.
*
* @method Phaser.Plugins.PluginCache.removeCustom
* @since 3.8.0
*
* @param {string} key - The key of the custom plugin to remove.
*/
/**
* Gets an index of a global plugin based on the given key.
*
* @method Phaser.Plugins.PluginManager#getIndex
* @protected
* @since 3.8.0
*
* @param {string} key - The unique plugin key.
*
* @return {number} The index of the plugin within the plugins array.
*/
/**
* Gets a global plugin based on the given key.
*
* @method Phaser.Plugins.PluginManager#getEntry
* @protected
* @since 3.8.0
*
* @param {string} key - The unique plugin key.
*
* @return {Phaser.Types.Plugins.GlobalPlugin} The plugin entry.
*/
/**
* Checks if the given global plugin, based on its key, is active or not.
*
* @method Phaser.Plugins.PluginManager#isActive
* @since 3.8.0
*
* @param {string} key - The unique plugin key.
*
* @return {boolean} `true` if the plugin is active, otherwise `false`.
*/
/**
* Gets a global plugin from the Plugin Manager based on the given key and returns it.
*
* If it cannot find an active plugin based on the key, but there is one in the Plugin Cache with the same key,
* then it will create a new instance of the cached plugin and return that.
*
* @method Phaser.Plugins.PluginManager#get
* @since 3.8.0
*
* @param {string} key - The key of the plugin to get.
* @param {boolean} [autoStart=true] - Automatically start a new instance of the plugin if found in the cache, but not actively running.
*
* @return {?(Phaser.Plugins.BasePlugin|function)} The plugin, or `null` if no plugin was found matching the key.
*/
/**
* Takes a reference to the Canvas Renderer, a Canvas Rendering Context, a Game Object, a Camera and a parent matrix
* and then performs the following steps:
*
* 1. Checks the alpha of the source combined with the Camera alpha. If 0 or less it aborts.
* 2. Takes the Camera and Game Object matrix and multiplies them, combined with the parent matrix if given.
* 3. Sets the blend mode of the context to be that used by the Game Object.
* 4. Sets the alpha value of the context to be that used by the Game Object combined with the Camera.
* 5. Saves the context state.
* 6. Sets the final matrix values into the context via setTransform.
* 7. If the Game Object has a texture frame, imageSmoothingEnabled is set based on frame.source.scaleMode.
* 8. If the Game Object does not have a texture frame, imageSmoothingEnabled is set based on Renderer.antialias.
*
* This function is only meant to be used internally. Most of the Canvas Renderer classes use it.
*
* @function Phaser.Renderer.Canvas.SetTransform
* @since 3.12.0
*
* @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer.
* @param {CanvasRenderingContext2D} ctx - The canvas context to set the transform on.
* @param {Phaser.GameObjects.GameObject} src - The Game Object being rendered. Can be any type that extends the base class.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
* @param {Phaser.GameObjects.Components.TransformMatrix} [parentMatrix] - A parent transform matrix to apply to the Game Object before rendering.
*
* @return {boolean} `true` if the Game Object context was set, otherwise `false`.
*/
/**
* Returns a program suite based on the current configuration.
* If the program does not exist, it is created.
*
* The suite contains the following properties:
*
* - `program` (WebGLProgramWrapper) - The compiled shader program.
* - `vao` (WebGLVAOWrapper) - The VAO associated with the program.
* - `config` (object) - The configuration object used to create the program.
*
* If parallel shader compilation is enabled,
* the program may not be available immediately.
* In this case, `null` is returned.
*
* @method Phaser.Renderer.WebGL.ProgramManager#getCurrentProgramSuite
* @since 4.0.0
* @return {?{ program: Phaser.Renderer.WebGL.Wrappers.WebGLProgramWrapper, vao: Phaser.Renderer.WebGL.Wrappers.WebGLVAOWrapper, config: object }} The program suite, or `null` if the program is not available.
*/
/**
* @classdesc
* The ShaderProgramFactory is a utility class used to create and cache
* {@link Phaser.Renderer.WebGL.Wrappers.WebGLProgramWrapper} objects for the
* WebGL renderer. It assembles compiled shader programs from a base shader
* combined with optional additions and feature flags, then stores the result
* under a unique key so that the same combination is never compiled more than
* once. Use this class when you need to obtain a shader program that may vary
* at runtime based on renderer capabilities or pipeline configuration.
*
* @class ShaderProgramFactory
* @memberof Phaser.Renderer.WebGL
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - The WebGLRenderer that owns this ShaderProgramFactory.
*/
/**
* Returns a unique key for a shader program based on the given configuration settings.
*
* The key is made up of the following components:
*
* - The key of the base shader program.
* - The key of each shader addition, in addition order.
* - The key of each enabled shader feature, sorted alphabetically.
*
* @method Phaser.Renderer.WebGL.ShaderProgramFactory#getKey
* @since 4.0.0
* @param {BaseShaderConfig} base - The base shader configuration.
* @param {Phaser.Types.Renderer.WebGL.ShaderAdditionConfig[]} [additions] - An array of shader addition configurations.
* @param {string[]} [features] - An array of enabled shader feature keys.
* @return {string} The unique cache key for this shader configuration.
*/
/**
* Creates a shader program based on the given configuration settings.
*
* @method Phaser.Renderer.WebGL.ShaderProgramFactory#createShaderProgram
* @since 4.0.0
* @param {string} name - The unique key of the shader program.
* @param {BaseShaderConfig} base - The base shader configuration.
* @param {Phaser.Types.Renderer.WebGL.ShaderAdditionConfig[]} [additions] - An array of shader addition configurations.
* @param {string[]} [features] - An array of enabled shader feature keys.
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLProgramWrapper} The newly compiled and cached shader program wrapper.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Felipe Alfonso <@bitnenfer>
* @author Matthew Groves <@doormat>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Internal gl function mapping for uniform and attribute look-up.
*
* https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform
*
* https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer
*
* @name Phaser.Renderer.WebGL.WebGLRenderer#shaderSetters
* @type {Phaser.Renderer.WebGL.Wrappers.WebGLShaderSetterWrapper}
* @since 4.0.0
*/
/**
* The mipmap magFilter to be used when creating textures.
*
* You can specify this as a string in the game config, i.e.:
*
* `render: { mipmapFilter: 'NEAREST_MIPMAP_LINEAR' }`
*
* The 6 options for WebGL1 are, in order from least to most computationally expensive:
*
* NEAREST (for pixel art)
* LINEAR (the default)
* NEAREST_MIPMAP_NEAREST
* LINEAR_MIPMAP_NEAREST
* NEAREST_MIPMAP_LINEAR
* LINEAR_MIPMAP_LINEAR
*
* Mipmaps only work with textures that are fully power-of-two in size.
*
* For more details see https://webglfundamentals.org/webgl/lessons/webgl-3d-textures.html
*
* As of v3.60 no mipmaps will be generated unless a string is given in
* the game config. This saves on VRAM use when it may not be required.
* To obtain the previous result set the property to `LINEAR` in the config.
*
* @name Phaser.Renderer.WebGL.WebGLRenderer#mipmapFilter
* @type {GLenum}
* @since 3.21.0
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method will capture the current WebGL frame and send it to the Spector.js tool for inspection.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#captureFrame
* @since 3.60.0
*
* @param {boolean} [quickCapture=false] - If `true` thumbnails are not captured in order to speed up the capture.
* @param {boolean} [fullCapture=false] - If `true` all details are captured.
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method will capture the next WebGL frame and send it to the Spector.js tool for inspection.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#captureNextFrame
* @since 3.60.0
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method will return the current FPS of the WebGL canvas.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#getFps
* @since 3.60.0
*
* @return {number} The current FPS of the WebGL canvas.
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method adds a command with the name value in the list. This can be filtered in the search.
* All logs can be filtered searching for "LOG".
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#log
* @since 3.60.0
*
* @param {...*} arguments - The arguments to log to Spector.
*
* @return {string} The current log.
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method will start a capture on the Phaser canvas. The capture will stop once it reaches
* the number of commands specified as a parameter, or after 10 seconds. If quick capture is true,
* the thumbnails are not captured in order to speed up the capture.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#startCapture
* @since 3.60.0
*
* @param {number} [commandCount=0] - The number of commands to capture. If zero it will capture for 10 seconds.
* @param {boolean} [quickCapture=false] - If `true` thumbnails are not captured in order to speed up the capture.
* @param {boolean} [fullCapture=false] - If `true` all details are captured.
*/
/**
* This method is only available in the Debug Build of Phaser, or a build with the
* `WEBGL_DEBUG` flag set in the Webpack Config.
*
* Phaser v3.60 Debug has a build of Spector.js embedded in it, which is a WebGL inspector
* that allows for live inspection of your WebGL calls. Although it's easy to add the Spector
* extension to a desktop browser, by embedding it in Phaser we can make it available in mobile
* browsers too, making it a powerful tool for debugging WebGL games on mobile devices where
* extensions are not permitted.
*
* See https://github.com/BabylonJS/Spector.js for more details.
*
* This method will stop the current capture and returns the result in JSON. It displays the
* result if the UI has been displayed. This returns undefined if the capture has not been completed
* or did not find any commands.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#stopCapture
* @since 3.60.0
*
* @return {object} The current capture.
*/
/**
* Returns a compressed texture format GLenum name based on the given format.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#getCompressedTextureName
* @since 3.60.0
*
* @param {string} baseFormat - The Base Format to check.
* @param {GLenum} [format] - An optional GLenum format to check within the base format.
*
* @return {string} The compressed texture format name, as a string.
*/
/**
* Creates a new custom blend mode for the renderer.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Blending_modes
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#addBlendMode
* @since 3.0.0
*
* @param {GLenum[]} func - An array containing the WebGL functions to use for the source and the destination blending factors, respectively. See the possible constants for {@link WebGLRenderingContext#blendFunc()}.
* @param {GLenum} equation - The equation to use for combining the RGB and alpha components of a new pixel with a rendered one. See the possible constants for {@link WebGLRenderingContext#blendEquation()}.
*
* @return {number} The index of the new blend mode, used for referencing it in the future.
*/
/**
* Creates a WebGLProgram instance based on the given vertex and fragment shader source.
*
* Then compiles, attaches and links the program before wrapping and returning it.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#createProgram
* @since 3.0.0
*
* @param {string} vertexShader - The vertex shader source code as a single string.
* @param {string} fragmentShader - The fragment shader source code as a single string.
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLProgramWrapper} The wrapped, linked WebGLProgram created from the given shader source.
*/
/**
* Schedules a snapshot of the given area of the game viewport to be taken after the current frame is rendered.
*
* To capture the whole game viewport see the `snapshot` method. To capture a specific pixel, see `snapshotPixel`.
*
* Only one snapshot can be active _per frame_. If you have already called `snapshotPixel`, for example, then
* calling this method will override it.
*
* Snapshots work by using the WebGL `readPixels` feature to grab every pixel from the frame buffer into an ArrayBufferView.
* It then parses this, copying the contents to a temporary Canvas and finally creating an Image object from it,
* which is the image returned to the callback provided. All in all, this is a computationally expensive and blocking process,
* which gets more expensive the larger the canvas size gets, so please be careful how you employ this in your game.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#snapshotArea
* @since 3.16.0
*
* @param {number} x - The x coordinate to grab from. This is based on the game viewport, not the world.
* @param {number} y - The y coordinate to grab from. This is based on the game viewport, not the world.
* @param {number} width - The width of the area to grab.
* @param {number} height - The height of the area to grab.
* @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot image is created.
* @param {string} [type='image/png'] - The format of the image to create, usually `image/png` or `image/jpeg`.
* @param {number} [encoderOptions=0.92] - The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`.
*
* @return {this} This WebGL Renderer.
*/
/**
* Schedules a snapshot of the given pixel from the game viewport to be taken after the current frame is rendered.
*
* To capture the whole game viewport see the `snapshot` method. To capture a specific area, see `snapshotArea`.
*
* Only one snapshot can be active _per frame_. If you have already called `snapshotArea`, for example, then
* calling this method will override it.
*
* Unlike the other two snapshot methods, this one will return a `Color` object containing the color data for
* the requested pixel. It doesn't need to create an internal Canvas or Image object, so is a lot faster to execute,
* using less memory.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#snapshotPixel
* @since 3.16.0
*
* @param {number} x - The x coordinate of the pixel to get. This is based on the game viewport, not the world.
* @param {number} y - The y coordinate of the pixel to get. This is based on the game viewport, not the world.
* @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot pixel data is extracted.
*
* @return {this} This WebGL Renderer.
*/
/**
* Takes a snapshot of the given area of the given frame buffer.
*
* Unlike the other snapshot methods, this one is processed immediately and doesn't wait for the next render.
*
* Snapshots work by using the WebGL `readPixels` feature to grab every pixel from the frame buffer into an ArrayBufferView.
* It then parses this, copying the contents to a temporary Canvas and finally creating an Image object from it,
* which is the image returned to the callback provided. All in all, this is a computationally expensive and blocking process,
* which gets more expensive the larger the canvas size gets, so please be careful how you employ this in your game.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#snapshotFramebuffer
* @since 3.19.0
*
* @param {Phaser.Renderer.WebGL.Wrappers.WebGLFramebufferWrapper} framebuffer - The framebuffer to grab from.
* @param {number} bufferWidth - The width of the framebuffer.
* @param {number} bufferHeight - The height of the framebuffer.
* @param {Phaser.Types.Renderer.Snapshot.SnapshotCallback} callback - The Function to invoke after the snapshot image is created.
* @param {boolean} [getPixel=false] - Grab a single pixel as a Color object, or an area as an Image object?
* @param {number} [x=0] - The x coordinate to grab from. This is based on the framebuffer, not the world.
* @param {number} [y=0] - The y coordinate to grab from. This is based on the framebuffer, not the world.
* @param {number} [width=bufferWidth] - The width of the area to grab.
* @param {number} [height=bufferHeight] - The height of the area to grab.
* @param {string} [type='image/png'] - The format of the image to create, usually `image/png` or `image/jpeg`.
* @param {number} [encoderOptions=0.92] - The image quality, between 0 and 1. Used for image formats with lossy compression, such as `image/jpeg`.
*
* @return {this} This WebGL Renderer.
*/
/**
* Creates a new WebGL Texture based on the given Canvas Element.
*
* If the `dstTexture` parameter is given, the WebGL Texture is updated, rather than created fresh.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#canvasToTexture
* @since 3.0.0
*
* @param {HTMLCanvasElement} srcCanvas - The Canvas to create the WebGL Texture from
* @param {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} [dstTexture] - The destination WebGLTextureWrapper to set.
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?)
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The newly created, or updated, WebGLTextureWrapper.
*/
/**
* Creates a new WebGL Texture based on the given Canvas Element.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#createCanvasTexture
* @since 3.20.0
*
* @param {HTMLCanvasElement} srcCanvas - The Canvas to create the WebGL Texture from.
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?)
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The newly created WebGLTextureWrapper.
*/
/**
* Updates a WebGL Texture based on the given Canvas Element.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#updateCanvasTexture
* @since 3.20.0
*
* @param {HTMLCanvasElement} srcCanvas - The Canvas to update the WebGL Texture from.
* @param {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} dstTexture - The destination WebGLTextureWrapper to update.
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT` (such as for Text objects?)
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The updated WebGLTextureWrapper. This is the same wrapper object as `dstTexture`.
*/
/**
* Creates or updates a WebGL Texture based on the given HTML Video Element.
*
* If the `dstTexture` parameter is given, the WebGL Texture is updated, rather than created fresh.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#videoToTexture
* @since 4.0.0
*
* @param {HTMLVideoElement} srcVideo - The Video to create the WebGL Texture from
* @param {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} [dstTexture] - The destination WebGLTextureWrapper to set.
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT`?
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The newly created, or updated, WebGLTextureWrapper.
*/
/**
* Creates a new WebGL Texture based on the given HTML Video Element.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#createVideoTexture
* @since 3.20.0
*
* @param {HTMLVideoElement} srcVideo - The Video to create the WebGL Texture from
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT`?
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The newly created WebGLTextureWrapper.
*/
/**
* Updates a WebGL Texture based on the given HTML Video Element.
*
* @method Phaser.Renderer.WebGL.WebGLRenderer#updateVideoTexture
* @since 3.20.0
*
* @param {HTMLVideoElement} srcVideo - The Video to update the WebGL Texture with.
* @param {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} dstTexture - The destination WebGLTextureWrapper to update.
* @param {boolean} [flipY=true] - Should the WebGL Texture set `UNPACK_FLIP_Y_WEBGL`?
* @param {boolean} [noRepeat=false] - Should this canvas be allowed to set `REPEAT`?
*
* @return {Phaser.Renderer.WebGL.Wrappers.WebGLTextureWrapper} The updated WebGLTextureWrapper. This is the same wrapper object as `dstTexture`.
*/
/**
* Copy and complete the configuration object.
* This prevents the original config object from being modified.
*
* Default values are used for any missing properties.
* These defaults are based on the default quad shader and layout.
*
* @method Phaser.Renderer.WebGL.RenderNodes.BatchHandler#_copyAndCompleteConfig
* @since 4.0.0
* @private
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
* @param {Phaser.Types.Renderer.WebGL.RenderNodes.BatchHandlerConfig} config - The configuration object.
* @param {Phaser.Types.Renderer.WebGL.RenderNodes.BatchHandlerConfig} defaultConfig - The default configuration object.
*/
/**
* Update the shader configuration based on render options.
* This is called automatically when the render options change.
*
* @method Phaser.Renderer.WebGL.RenderNodes.BatchHandlerQuad#updateShaderConfig
* @since 4.0.0
*/
/**
* @classdesc
* A RenderNode which fills a closed path with solid color.
*
* It works by taking the array of path data and passing it through
* Earcut, which triangulates the polygon into a list of triangles.
* Each triangle is then submitted to the batch for rendering.
* The first and last points in the path are always preserved; interior
* points may be skipped based on the `detail` threshold.
*
* @class FillPath
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @extends Phaser.Renderer.WebGL.RenderNodes.RenderNode
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
*/
/**
* Renders a quad using the shader program. Transforms the quad vertices
* based on the game object properties, populates the vertex buffer,
* sets up uniforms and textures, and issues a draw call.
*
* @method Phaser.Renderer.WebGL.RenderNodes.ShaderQuad#run
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
* @param {Phaser.GameObjects.Shader} gameObject - The Shader game object being rendered.
* @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - The parent transform matrix.
*/
/**
* Set up the uniforms for this shader, based on the controller.
* Override this method to handle uniform setup.
*
* @method Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader#setupUniforms
* @since 4.0.0
* @param {Phaser.Filters.Controller} controller - The filter controller.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The drawing context in use.
*/
/**
* Runs the Blur filter effect.
*
* The method selects the appropriate blur shader node based on
* `controller.quality`, then executes `controller.steps` iterations of
* axis-separated Gaussian blur. Each iteration consists of a horizontal
* pass followed by a vertical pass. Padding from the controller is applied
* on the first pass only; subsequent passes use an empty rectangle so the
* render area does not grow with each iteration.
*
* @method Phaser.Renderer.WebGL.RenderNodes.FilterBlur#run
* @since 4.0.0
* @param {Phaser.Filters.Blur} controller - The Blur filter controller, supplying quality, steps, strength, color, and axis blur amounts.
* @param {Phaser.Renderer.WebGL.DrawingContext} inputDrawingContext - The drawing context containing the source texture to blur.
* @param {Phaser.Renderer.WebGL.DrawingContext} outputDrawingContext - The drawing context to receive the final blurred output.
* @param {Phaser.Geom.Rectangle} [padding] - Padding to apply around the render area on the first pass. If omitted, it is retrieved from the controller.
* @return {Phaser.Renderer.WebGL.DrawingContext} The drawing context containing the blurred result.
*/
/**
* @classdesc
* A RenderNode that renders the BlurLow filter effect, which applies a
* single-pass Gaussian blur to the input texture using a small sample kernel.
*
* This is the lowest quality tier of the blur filter family. It uses fewer
* texture samples than the medium and high quality variants, making it faster
* to execute on the GPU at the cost of a less smooth result. It is well suited
* to subtle or fast-moving blur effects where visual fidelity is less critical
* than rendering performance.
*
* This node should not be used directly. It is selected and invoked
* automatically by the FilterBlur RenderNode based on the quality setting of
* the blur controller that is currently being processed.
*
* @class FilterBlurLow
* @extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
*/
/**
* @classdesc
* This RenderNode renders the BlurMed filter effect.
* This is a medium quality blur filter.
* It should not be used directly.
* It is intended to be called by the FilterBlur filter
* based on the quality setting of the controller it is running.
*
* @class FilterBlurMed
* @extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
*/
/**
* Updates the shader program's preprocessor defines for glow distance and
* quality based on the current controller values. Because these parameters
* are baked into the shader at compile time, changing them replaces the
* relevant shader additions and triggers a program recompile.
*
* @method Phaser.Renderer.WebGL.RenderNodes.FilterGlow#updateShaderConfig
* @since 4.0.0
* @param {Phaser.Filters.Glow} controller - The Glow filter controller providing the distance and quality values.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
*/
/**
* @classdesc
* A RenderNode that renders the GradientMap filter effect, which maps the
* luminosity of each pixel in the source image to a corresponding color from
* a gradient ramp texture. Darker pixels are mapped to one end of the gradient
* and brighter pixels to the other, replacing the original colors entirely.
* This enables stylistic effects such as thermal imaging, night vision, sepia
* toning, or any arbitrary color grade driven by brightness.
*
* The gradient is defined by a {@link Phaser.Display.ColorRamp} attached to
* the controlling {@link Phaser.Filters.GradientMap} filter. The ramp is
* uploaded as a data texture and sampled in the fragment shader. The shader
* variant is selected dynamically based on the ramp's band tree depth, so the
* program is recompiled when the ramp structure changes.
*
* See {@link Phaser.Filters.GradientMap}.
*
* @class FilterGradientMap
* @extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
*/
/**
* Sets up the shader uniforms for the Key filter based on the current
* state of its controller.
*
* Sends the key color as a `vec4` uniform (`uColor`), and packs the
* isolate flag, threshold, and feather values into a single `vec4`
* uniform (`uIsolateThresholdFeather`) to minimise uniform slots.
*
* @method Phaser.Renderer.WebGL.RenderNodes.FilterKey#setupUniforms
* @since 4.0.0
* @param {Phaser.Filters.Key} controller - The Key filter controller providing the uniform values.
* @param {Phaser.Renderer.WebGL.DrawingContext} _drawingContext - The drawing context in use (unused by this filter).
*/
/**
* Updates the shader program configuration based on the current controller
* settings. Resets the fragment header addition to the base
* `VIEW_MATRIX` define, then conditionally appends the `FACING_POWER`
* and `OUTPUT_RATIO` defines — and adjusts the addition name accordingly —
* so that the correct shader variant is compiled and cached for the active
* combination of features.
*
* @method Phaser.Renderer.WebGL.RenderNodes.FilterNormalTools#updateShaderConfig
* @since 4.0.0
* @param {Phaser.Filters.NormalTools} controller - The filter controller providing the current configuration.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
*/
/**
* Sets the WebGL uniform values for the NormalTools shader based on the
* current controller settings. Always uploads the view matrix as
* `uViewMatrix`. If the controller's `facingPower` differs from the default
* value of `1`, the `uFacingPower` uniform is also uploaded. If
* `outputRatio` is enabled on the controller, the `uRatioVector` (a 3-component
* direction vector) and `uRatioRadius` uniforms are uploaded as well.
*
* @method Phaser.Renderer.WebGL.RenderNodes.FilterNormalTools#setupUniforms
* @since 4.0.0
* @param {Phaser.Filters.NormalTools} controller - The filter controller providing the uniform values.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
*/
/**
* @classdesc
* This RenderNode renders the Threshold filter effect, which converts each
* pixel of a Game Object to either fully opaque or fully transparent based on
* its luminance value relative to a configurable threshold range. Pixels whose
* luminance falls below `edge1` are discarded, those above `edge2` are kept,
* and those in between are smoothly interpolated. The effect can optionally be
* inverted so that bright pixels are discarded instead of dark ones.
* See {@link Phaser.Filters.Threshold}.
*
* @class FilterThreshold
* @extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
*/
/**
* Updates the shader program options based on the current state of the
* SpriteGPULayer game object. Enables or disables lighting shader additions,
* sets the active light count define, configures smooth pixel art rendering,
* and applies any shader features reported by the game object, including
* self-shadowing support.
*
* @method Phaser.Renderer.WebGL.RenderNodes.SubmitterSpriteGPULayer#updateRenderOptions
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
*/
/**
* @author Benjamin D. Richards <benjamindrichards@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license None
*/
/**
* @classdesc
* The SubmitterTilemapGPULayer RenderNode handles GPU-accelerated rendering
* of TilemapGPULayer objects in the WebGL renderer.
*
* Unlike batch-based submitters, this is a Stand Alone Render, meaning each
* layer is drawn in its own draw call. It manages its own shader program
* via a ProgramManager, which supports several optional shader features
* including smooth pixel art upscaling, normal-mapped lighting, animated
* tiles, self-shadowing, and bilinear border filtering. The appropriate
* shader variant is selected each frame based on the layer's configuration.
*
* @class SubmitterTilemapGPULayer
* @extends Phaser.Renderer.WebGL.RenderNodes.RenderNode
* @memberof Phaser.Renderer.WebGL.RenderNodes
* @constructor
* @since 4.0.0
* @param {Phaser.Renderer.WebGL.RenderNodes.RenderNodeManager} manager - The manager that owns this RenderNode.
* @param {Phaser.Types.Renderer.WebGL.RenderNodes.BatchHandlerConfig} [config] - The configuration object for this handler.
*/
/**
* Evaluates the current state of the TilemapGPULayer and updates the
* shader program configuration accordingly. This is called before each
* render and may result in a different shader variant being selected.
*
* Specifically, it configures: the animation length addition (based on the
* tileset's maximum animation frame count), lighting additions (enabled or
* disabled based on the layer's lighting setting, with the light count
* define updated when active), the self-shadow feature flag, the smooth
* pixel art addition, and the border filter feature flag (based on whether
* the tileset texture uses linear magnification filtering).
*
* @method Phaser.Renderer.WebGL.RenderNodes.SubmitterTilemapGPULayer#updateRenderOptions
* @since 4.0.0
* @param {Phaser.Tilemaps.TilemapGPULayer} gameObject - The TilemapGPULayer being rendered.
* @param {Phaser.Renderer.WebGL.DrawingContext} drawingContext - The current drawing context.
*/
/**
* Return a ShaderAdditionConfig for applying an alpha discard strategy
* to the fragment color.
*
* The alpha discard strategy is used to discard fragments based on their alpha value.
* This is useful for stencil operations, where transparent fragments should not be considered for the stencil buffer.
* Retained fragments are increased to alpha 1.0.
*
* Disable this addition to just keep the fragment color as is.
*
* @function Phaser.Renderer.WebGL.ShaderAdditionMakers.MakeApplyAlphaDiscard
* @since 4.2.0
* @param {boolean} [disable=false] - Whether to disable the shader addition on creation.
* @param {boolean} [dither=false] - Whether to use a dithering strategy to discard fragments.
* @param {number} [threshold] - The threshold value to use when using a thresholding strategy to discard fragments. If defined, and dither is false, the threshold will be used to discard fragments.
* @returns {Phaser.Types.Renderer.WebGL.ShaderAdditionConfig} The shader addition configuration.
*/
/**
* Creates a ShaderAdditionConfig for multi-texture sampling in a WebGL shader.
* The returned config injects a `getTexture` GLSL function into the fragment
* shader header, built as an if...else chain that selects from up to
* `maxTextures` texture units based on the texture ID. It also injects a
* single-line process that samples the current fragment color via that function.
*
* @function Phaser.Renderer.WebGL.ShaderAdditionMakers.MakeGetTexture
* @since 4.0.0
* @param {number} [maxTextures=1] - The number of texture units to support. Determines how many branches are generated in the texture-selection if...else chain.
* @param {boolean} [disable=false] - Whether to disable the shader addition on creation.
* @return {Phaser.Types.Renderer.WebGL.ShaderAdditionConfig} The shader addition configuration.
*/
/**
* @classdesc
* The Scale Manager handles the scaling, resizing and alignment of the game canvas.
*
* The way scaling is handled is by setting the game canvas to a fixed size, which is defined in the
* game configuration. You also define the parent container in the game config. If no parent is given,
* it will default to using the document body. The Scale Manager will then look at the available space
* within the _parent_ and scale the canvas accordingly. Scaling is handled by setting the canvas CSS
* width and height properties, leaving the width and height of the canvas element itself untouched.
* Scaling is therefore achieved by keeping the core canvas the same size and 'stretching'
* it via its CSS properties. This gives the same result and speed as using the `transform-scale` CSS
* property, without the need for browser prefix handling.
*
* The calculations for the scale are heavily influenced by the bounding parent size, which is the computed
* dimensions of the canvas's parent. The CSS rules of the parent element play an important role in the
* operation of the Scale Manager. For example, if the parent has no defined width or height, then actions
* like auto-centering will fail to achieve the required result. The Scale Manager works in tandem with the
* CSS you set-up on the page hosting your game, rather than taking control of it.
*
* #### Parent and Display canvas containment guidelines:
*
* - Style the Parent element (of the game canvas) to control the Parent size and thus the games size and layout.
*
* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior.
*
* - The Parent element should _not_ apply a padding as this is not accounted for.
* If a padding is required apply it to the Parent's parent or apply a margin to the Parent.
* If you need to add a border, margin or any other CSS around your game container, then use a parent element and
* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container.
*
* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered / specified as
* they may be updated by the Scale Manager.
*
* #### Scale Modes
*
* The way the scaling is handled is determined by the `scaleMode` property. The default is `NONE`,
* which prevents Phaser from scaling or touching the canvas, or its parent, at all. In this mode, you are
* responsible for all scaling. The other scaling modes afford you automatic scaling.
*
* If you wish to scale your game so that it always fits into the available space within the parent, you
* should use the scale mode `FIT`. Look at the documentation for other scale modes to see what options are
* available. Here is a basic config showing how to set this scale mode:
*
* ```javascript
* scale: {
* parent: 'yourgamediv',
* mode: Phaser.Scale.FIT,
* width: 800,
* height: 600
* }
* ```
*
* Place the `scale` config object within your game config.
*
* If you wish for the canvas to be resized directly, so that the canvas itself fills the available space
* (i.e. it isn't scaled, it's resized) then use the `RESIZE` scale mode. This will give you a 1:1 mapping
* of canvas pixels to game size. In this mode CSS isn't used to scale the canvas, it's literally adjusted
* to fill all available space within the parent. You should be extremely careful about the size of the
* canvas you're creating when doing this, as the larger the area, the more work the GPU has to do and it's
* very easy to hit fill-rate limits quickly.
*
* For complex, custom-scaling requirements, you should probably consider using the `RESIZE` scale mode,
* with your own limitations in place re: canvas dimensions and managing the scaling with the game scenes
* yourself. For the vast majority of games, however, the `FIT` mode is likely to be the most used.
*
* Please appreciate that the Scale Manager cannot perform miracles. All it does is scale your game canvas
* as best it can, based on what it can infer from its surrounding area. There are all kinds of environments
* where it's up to you to guide and help the canvas position itself, especially when built into rendering
* frameworks like React and Vue. If your page requires meta tags to prevent user scaling gestures, or such
* like, then it's up to you to ensure they are present in the html.
*
* #### Centering
*
* You can also have the game canvas automatically centered. Again, this relies heavily on the parent being
* properly configured and styled, as the centering offsets are based entirely on the available space
* within the parent element. Centering is disabled by default, or can be applied horizontally, vertically,
* or both. Here's an example:
*
* ```javascript
* scale: {
* parent: 'yourgamediv',
* autoCenter: Phaser.Scale.CENTER_BOTH,
* width: 800,
* height: 600
* }
* ```
*
* #### Fullscreen API
*
* If the browser supports it, you can send your game into fullscreen mode. In this mode, the game will fill
* the entire display, removing all browser UI and anything else present on the screen. It will remain in this
* mode until your game either disables it, or until the user tabs out or presses ESCape if on desktop. It's a
* great way to achieve a desktop-game like experience from the browser, but it does require a modern browser
* to handle it. Some mobile browsers also support this.
*
* @class ScaleManager
* @memberof Phaser.Scale
* @extends Phaser.Events.EventEmitter
* @constructor
* @since 3.16.0
*
* @param {Phaser.Game} game - A reference to the Phaser.Game instance.
*/
/**
* How many milliseconds should elapse before checking if the browser size has changed?
*
* Most modern browsers dispatch a 'resize' event, which the Scale Manager will listen for.
* However, older browsers fail to do this, or do it consistently, so we fall back to a
* more traditional 'size check' based on a time interval. You can control how often it is
* checked here.
*
* @name Phaser.Scale.ScaleManager#resizeInterval
* @type {number}
* @since 3.16.0
*/
/**
* Determines the parent element of the game canvas, if any, based on the game configuration.
*
* @method Phaser.Scale.ScaleManager#getParent
* @since 3.16.0
*
* @param {Phaser.Types.Core.GameConfig} config - The Game configuration object.
*/
/**
* Attempts to lock the orientation of the web browser using the Screen Orientation API.
*
* This API is only available on modern mobile browsers.
* See https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation for details.
*
* @method Phaser.Scale.ScaleManager#lockOrientation
* @since 3.16.0
*
* @param {string} orientation - The orientation you'd like to lock the browser in. Should be an API string such as 'landscape', 'landscape-primary', 'portrait', etc.
*
* @return {boolean} `true` if the orientation was successfully locked, otherwise `false`.
*/
/**
* Call this to modify the size of the Phaser canvas element directly.
* You should only use this if you are using the `NONE` scale mode,
* it will update all internal components completely.
*
* If all you want to do is change the size of the parent, see the `setParentSize` method.
*
* If all you want is to change the base size of the game, but still have the Scale Manager
* manage all the scaling (i.e. you're **not** using `NONE`), then see the `setGameSize` method.
*
* This method will set the `gameSize`, `baseSize` and `displaySize` components to the given
* dimensions. It will then resize the canvas width and height to the values given, by
* directly setting the properties. Finally, if you have set the Scale Manager zoom value
* to anything other than 1 (the default), it will set the canvas CSS width and height to
* be the given size multiplied by the zoom factor (the canvas pixel size remains untouched).
*
* If you have enabled `autoCenter`, it is then passed to the `updateCenter` method and
* the margins are set, allowing the canvas to be centered based on its parent element
* alone. Finally, the `displayScale` is adjusted and the RESIZE event dispatched.
*
* @method Phaser.Scale.ScaleManager#resize
* @fires Phaser.Scale.Events#RESIZE
* @since 3.16.0
*
* @param {number} width - The new width of the game.
* @param {number} height - The new height of the game.
*
* @return {this} The Scale Manager instance.
*/
/**
* Sets the zoom to be the maximum possible based on the _current_ parent size.
*
* @method Phaser.Scale.ScaleManager#setMaxZoom
* @fires Phaser.Scale.Events#RESIZE
* @since 3.16.0
*
* @return {this} The Scale Manager instance.
*/
/**
* Internal method that manages updating the size components based on the scale mode.
*
* @method Phaser.Scale.ScaleManager#updateScale
* @since 3.16.0
*/
/**
* Calculates and returns the largest possible zoom factor, based on the current
* parent and game sizes. If the parent has no dimensions (i.e. an unstyled div),
* or is smaller than the un-zoomed game, then this will return a value of 1 (no zoom)
*
* @method Phaser.Scale.ScaleManager#getMaxZoom
* @since 3.16.0
*
* @return {number} The maximum possible zoom factor. At a minimum this value is always at least 1.
*/
/**
* Sends a request to the browser to ask it to go in to full screen mode, using the {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API}.
*
* If the browser does not support this, a `FULLSCREEN_UNSUPPORTED` event will be emitted.
*
* This method _must_ be called from a `pointerup` user-input gesture (**not** `pointerdown`). You cannot launch
* games fullscreen without this, as most browsers block it. Games within an iframe will also be blocked
* from fullscreen unless the iframe has the `allowfullscreen` attribute.
*
* On touch devices, such as Android and iOS Safari, you should always use `pointerup` and NOT `pointerdown`,
* otherwise the request will fail unless the document in which your game is embedded has already received
* some form of touch input, which you cannot guarantee. Activating fullscreen via `pointerup` circumvents
* this issue.
*
* Performing an action that navigates to another page, or opens another tab, will automatically cancel
* fullscreen mode, as will the user pressing the ESC key. To cancel fullscreen mode directly from your game,
* i.e. by clicking an icon, call the `stopFullscreen` method.
*
* A browser can only send one DOM element into fullscreen. You can control which element this is by
* setting the `fullscreenTarget` property in your game config, or changing the property in the Scale Manager.
* Note that the game canvas _must_ be a child of the target. If you do not give a target, Phaser will
* automatically create a blank `<div>` element and move the canvas into it, before going fullscreen.
* When it leaves fullscreen, the div will be removed.
*
* @method Phaser.Scale.ScaleManager#startFullscreen
* @fires Phaser.Scale.Events#ENTER_FULLSCREEN
* @fires Phaser.Scale.Events#FULLSCREEN_FAILED
* @fires Phaser.Scale.Events#FULLSCREEN_UNSUPPORTED
* @fires Phaser.Scale.Events#RESIZE
* @since 3.16.0
*
* @param {object} [fullscreenOptions] - The FullscreenOptions dictionary is used to provide configuration options when entering full screen.
*/
/**
* The height is automatically adjusted based on the width.
*
* @name Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT
* @type {number}
* @const
* @since 3.16.0
*/
/**
* The width is automatically adjusted based on the height.
*
* @name Phaser.Scale.ScaleModes.HEIGHT_CONTROLS_WIDTH
* @type {number}
* @const
* @since 3.16.0
*/
/**
* Calculate the zoom value based on the maximum multiplied game size that will
* fit into the parent, or browser window if no parent is set.
*
* @name Phaser.Scale.Zoom.MAX_ZOOM
* @type {number}
* @const
* @since 3.16.0
*/
/**
* Override this method in your own Scene subclass to implement per-frame game logic.
*
* This method is called automatically once per game step while the scene is running.
* It is empty by default and is the primary place to put logic that needs to run every frame,
* such as updating game object positions, checking collisions, or reading input state.
*
* @method Phaser.Scene#update
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Retrieves a Scene based on the given key.
*
* If an actual Scene is passed to this method, it can be used to check if
* its currently within the Scene Manager, or not.
*
* @method Phaser.Scenes.SceneManager#getScene
* @since 3.0.0
*
* @generic {Phaser.Scene} T
* @genericUse {(T|string)} - [key]
* @genericUse {T} - [$return]
*
* @param {(string|Phaser.Scene)} key - The key of the Scene to retrieve.
*
* @return {?Phaser.Scene} The Scene, or `null` if no matching Scene was found.
*/
/**
* A single game step. This is only called if the parent Scene is transitioning
* out to another Scene.
*
* @method Phaser.Scenes.ScenePlugin#step
* @private
* @since 3.5.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Retrieves a Scene based on the given key.
*
* If an actual Scene is passed to this method, it can be used to check if
* its currently within the Scene Manager, or not.
*
* @generic {Phaser.Scene} T
* @genericUse {(T|string)} - [key]
* @genericUse {T} - [$return]
*
* @method Phaser.Scenes.ScenePlugin#get
* @since 3.0.0
*
* @param {(string|Phaser.Scene)} key - The Scene to retrieve.
*
* @return {Phaser.Scene} The Scene.
*/
/**
* The Scene Settings. This is the parsed output based on the Scene configuration.
*
* @name Phaser.Scenes.Systems#settings
* @type {Phaser.Types.Scenes.SettingsObject}
* @since 3.0.0
*/
/**
* The Scene Systems Post Update Event.
*
* This event is dispatched by a Scene during the main game loop step.
*
* The event flow for a single step of a Scene is as follows:
*
* 1. [PRE_UPDATE]{@linkcode Phaser.Scenes.Events#event:PRE_UPDATE}
* 2. [UPDATE]{@linkcode Phaser.Scenes.Events#event:UPDATE}
* 3. The `Scene.update` method is called, if it exists
* 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE}
* 5. [PRE_RENDER]{@linkcode Phaser.Scenes.Events#event:PRE_RENDER}
* 6. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER}
*
* Listen to it from a Scene using `this.events.on('postupdate', listener)`.
*
* A Scene will only run its step if it is active.
*
* @event Phaser.Scenes.Events#POST_UPDATE
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* @author samme
* @copyright 2021 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* The Scene Systems Pre Update Event.
*
* This event is dispatched by a Scene during the main game loop step.
*
* The event flow for a single step of a Scene is as follows:
*
* 1. [PRE_UPDATE]{@linkcode Phaser.Scenes.Events#event:PRE_UPDATE}
* 2. [UPDATE]{@linkcode Phaser.Scenes.Events#event:UPDATE}
* 3. The `Scene.update` method is called, if it exists
* 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE}
* 5. [PRE_RENDER]{@linkcode Phaser.Scenes.Events#event:PRE_RENDER}
* 6. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER}
*
* Listen to it from a Scene using `this.events.on('preupdate', listener)`.
*
* A Scene will only run its step if it is active.
*
* @event Phaser.Scenes.Events#PRE_UPDATE
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* The Scene Systems Update Event.
*
* This event is dispatched by a Scene during the main game loop step.
*
* The event flow for a single step of a Scene is as follows:
*
* 1. [PRE_UPDATE]{@linkcode Phaser.Scenes.Events#event:PRE_UPDATE}
* 2. [UPDATE]{@linkcode Phaser.Scenes.Events#event:UPDATE}
* 3. The `Scene.update` method is called, if it exists and the Scene is in a Running state, otherwise this is skipped.
* 4. [POST_UPDATE]{@linkcode Phaser.Scenes.Events#event:POST_UPDATE}
* 5. [PRE_RENDER]{@linkcode Phaser.Scenes.Events#event:PRE_RENDER}
* 6. [RENDER]{@linkcode Phaser.Scenes.Events#event:RENDER}
*
* Listen to it from a Scene using `this.events.on('update', listener)`.
*
* A Scene will only run its step if it is active.
*
* @event Phaser.Scenes.Events#UPDATE
* @type {string}
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Adds a new audio sprite sound into the sound manager.
* Audio Sprites are a combination of audio files and a JSON configuration.
* The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
*
* @method Phaser.Sound.BaseSoundManager#addAudioSprite
* @since 3.0.0
*
* @param {string} key - Asset key for the sound.
* @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings.
*
* @return {(Phaser.Sound.NoAudioSound|Phaser.Sound.HTML5AudioSound|Phaser.Sound.WebAudioSound)} The new audio sprite sound instance.
*/
/**
* Method used internally for unlocking audio playback on devices that
* require user interaction before any sound can be played on a web page.
*
* Read more about how this issue is handled here in [this article](https://medium.com/@pgoloskokovic/unlocking-web-audio-the-smarter-way-8858218c0e09).
*
* @method Phaser.Sound.BaseSoundManager#unlock
* @override
* @protected
* @since 3.0.0
*/
/**
* Sets the global detuning of all sounds in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend keeping it within a reasonable range for musical purposes.
*
* @method Phaser.Sound.BaseSoundManager#setDetune
* @fires Phaser.Sound.Events#GLOBAL_DETUNE
* @since 3.3.0
*
* @param {number} value - The detuning value in cents. The range is -1200 to 1200, but we recommend keeping it within a reasonable range for musical purposes.
*
* @return {this} This Sound Manager.
*/
/**
* Global detuning of all sounds in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend keeping it within a reasonable range for musical purposes.
*
* @name Phaser.Sound.BaseSoundManager#detune
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* Creates a Web Audio, HTML5 Audio or No Audio Sound Manager based on config and device settings.
*
* Be aware of https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
*
* @namespace Phaser.Sound.SoundManagerCreator
* @since 3.0.0
*/
/**
* Determines the most appropriate Sound Manager to use based on the game configuration
* and the audio capabilities of the current device, then creates and returns an instance
* of it.
*
* If the game config has `audio.noAudio` set to `true`, or if the device supports neither
* Web Audio nor HTML5 Audio, a `NoAudioSoundManager` is returned, which silently stubs all
* sound calls. If Web Audio is supported and not explicitly disabled via
* `audio.disableWebAudio`, a `WebAudioSoundManager` is returned. Otherwise, an
* `HTML5AudioSoundManager` is returned as a fallback.
*
* Be aware of https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
*
* @method Phaser.Sound.SoundManagerCreator.create
* @since 3.0.0
*
* @param {Phaser.Game} game - Reference to the current game instance.
*
* @return {(Phaser.Sound.HTML5AudioSoundManager|Phaser.Sound.WebAudioSoundManager|Phaser.Sound.NoAudioSoundManager)} The Sound Manager instance that was created.
*/
/**
* @author pi-kei
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @classdesc
* HTML5AudioSound is the HTML5 Audio API implementation of a sound within Phaser.
*
* It is used automatically by the HTML5AudioSoundManager when the Web Audio API is unavailable,
* typically in environments that do not support it or where it has been disabled. Unlike the
* WebAudioSound class, HTML5AudioSound relies on native `<audio>` elements for playback, which
* means it has more limited capabilities, such as no support for audio panning.
*
* Each sound maintains a pool of `HTMLAudioElement` tags loaded via `Loader.audio`. Because HTML5
* Audio cannot share a single element across simultaneous playbacks, you must load multiple
* instances of the asset if you want to play the same sound more than once at the same time.
*
* You do not create instances of this class directly. Instead, use
* `this.sound.add(key)` from within a Scene, which will return the correct sound type based on
* the audio system in use.
*
* @class HTML5AudioSound
* @extends Phaser.Sound.BaseSound
* @memberof Phaser.Sound
* @constructor
* @since 3.0.0
*
* @param {Phaser.Sound.HTML5AudioSoundManager} manager - Reference to the current sound manager instance.
* @param {string} key - Asset key for the sound.
* @param {Phaser.Types.Sound.SoundConfig} [config={}] - An optional config object containing default sound settings.
*/
/**
* This method performs the audio tag pooling logic. It first looks for
* unused audio tag to assign to this sound object. If there are no unused
* audio tags, based on HTML5AudioSoundManager#override property value, it
* looks for sound with most advanced playback and hijacks its audio tag or
* does nothing.
*
* @method Phaser.Sound.HTML5AudioSound#pickAudioTag
* @since 3.0.0
*
* @return {boolean} Whether the sound was assigned an audio tag successfully.
*/
/**
* The detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @name Phaser.Sound.HTML5AudioSound#detune
* @type {number}
* @default 0
* @fires Phaser.Sound.Events#DETUNE
* @since 3.0.0
*/
/**
* Sets the detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @method Phaser.Sound.HTML5AudioSound#setDetune
* @fires Phaser.Sound.Events#DETUNE
* @since 3.3.0
*
* @param {number} value - The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @return {this} This Sound instance.
*/
/**
* HTML5 Audio implementation of the Sound Manager.
*
* To play multiple instances of the same HTML5 Audio sound, you need to provide an `instances` value when
* loading the sound with the Loader:
*
* ```javascript
* this.load.audio('explosion', 'explosion.mp3', {
* instances: 2
* });
* ```
*
* Not all browsers can play all audio formats.
*
* There is a good guide to what's supported: [Cross-browser audio basics: Audio codec support](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support).
*
* @class HTML5AudioSoundManager
* @extends Phaser.Sound.BaseSoundManager
* @memberof Phaser.Sound
* @constructor
* @since 3.0.0
*
* @param {Phaser.Game} game - Reference to the current game instance.
*/
/**
* The detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @name Phaser.Sound.NoAudioSound#detune
* @type {number}
* @default 0
* @fires Phaser.Sound.Events#DETUNE
* @since 3.0.0
*/
/**
* Sets the detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @method Phaser.Sound.NoAudioSound#setDetune
* @since 3.3.0
*
* @param {number} value - The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @return {this} This Sound instance.
*/
/**
* Adds a new audio sprite sound into the sound manager.
* Audio Sprites are a combination of audio files and a JSON configuration.
* The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
*
* @method Phaser.Sound.NoAudioSoundManager#addAudioSprite
* @since 3.60.0
*
* @param {string} key - Asset key for the sound.
* @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings.
*
* @return {Phaser.Sound.NoAudioSound} The new audio sprite sound instance.
*/
/**
* The time at which the sound should have started playback from the beginning.
*
* Treat this property as read-only.
*
* Based on `BaseAudioContext.currentTime` value.
*
* @name Phaser.Sound.WebAudioSound#playTime
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* The time at which the sound source should have actually started playback.
*
* Treat this property as read-only.
*
* Based on `BaseAudioContext.currentTime` value.
*
* @name Phaser.Sound.WebAudioSound#startTime
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* The time at which the sound loop source should actually start playback.
*
* Based on `BaseAudioContext.currentTime` value.
*
* @name Phaser.Sound.WebAudioSound#loopTime
* @type {number}
* @default 0
* @since 3.0.0
*/
/**
* The detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @name Phaser.Sound.WebAudioSound#detune
* @type {number}
* @default 0
* @fires Phaser.Sound.Events#DETUNE
* @since 3.0.0
*/
/**
* Sets the detune value of this Sound, given in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
* The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @method Phaser.Sound.WebAudioSound#setDetune
* @fires Phaser.Sound.Events#DETUNE
* @since 3.3.0
*
* @param {number} value - The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
*
* @return {this} This Sound instance.
*/
/**
* @classdesc
* The Web Audio API implementation of the Phaser Sound Manager.
*
* This is the default Sound Manager used in Phaser when the browser supports the Web Audio API.
* It creates and manages an `AudioContext`, routes all sounds through a master gain node chain
* for global mute and volume control, and handles the browser autoplay policy by unlocking
* audio on the first user interaction.
*
* Use this manager to add, play, and control sounds in your game. It is accessed via
* `this.sound` from within a Scene. If the browser does not support the Web Audio API,
* Phaser will fall back to the `HTML5AudioSoundManager` instead.
*
* Not all browsers can play all audio formats.
*
* There is a good guide to what's supported: [Cross-browser audio basics: Audio codec support](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support).
*
* @class WebAudioSoundManager
* @extends Phaser.Sound.BaseSoundManager
* @memberof Phaser.Sound
* @constructor
* @since 3.0.0
*
* @param {Phaser.Game} game - Reference to the current game instance.
*/
/**
* Internal handler for Phaser.Core.Events#VISIBLE.
*
* Needed to handle resuming audio on iOS17/iOS18+ if you hide the browser, press
* the home button, etc. See https://github.com/phaserjs/phaser/issues/6829
*
* @method Phaser.Sound.WebAudioSoundManager#onGameVisible
* @private
* @since 3.88.0
*/
/**
* Unlocks Web Audio API on the initial input event.
*
* Read more about how this issue is handled here in [this article](https://medium.com/@pgoloskokovic/unlocking-web-audio-the-smarter-way-8858218c0e09).
*
* @method Phaser.Sound.WebAudioSoundManager#unlock
* @since 3.0.0
*/
/**
* Sort the contents of this List so the items are in order based on the given property.
* For example, `sort('alpha')` would sort the List contents based on the value of their `alpha` property.
*
* @method Phaser.Structs.List#sort
* @since 3.0.0
*
* @genericUse {T[]} - [children,$return]
*
* @param {string} property - The property to lexically sort by.
* @param {function} [handler] - Provide your own custom handler function. Will receive 2 children which it should compare and return a number (negative if the first should come before the second, positive if after, zero if equal).
*
* @return {Phaser.Structs.List} This List object.
*/
/**
* @author Vladimir Agafonkin
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @classdesc
* RBush is a high-performance JavaScript library for 2D spatial indexing of points and rectangles.
* It's based on an optimized R-tree data structure with bulk insertion support.
*
* Spatial index is a special data structure for points and rectangles that allows you to perform queries like
* "all items within this bounding box" very efficiently (e.g. hundreds of times faster than looping over all items).
*
* This version of RBush uses a fixed min/max accessor structure of `[ '.left', '.top', '.right', '.bottom' ]`.
* This is to avoid the eval-like function creation that the original library used, which caused CSP policy violations.
*
* rbush is forked from https://github.com/mourner/rbush by Vladimir Agafonkin
*
* @class RTree
* @memberof Phaser.Structs
* @constructor
* @since 3.0.0
*/
/**
* @classdesc
* The Size component allows you to set `width` and `height` properties and define the relationship between them.
*
* The component can automatically maintain the aspect ratios between the two values, and clamp them
* to a defined min-max range. You can also control the dominant axis. When dimensions are given to the Size component
* that would cause it to exceed its min-max range, the dimensions are adjusted based on the dominant axis.
*
* @class Size
* @memberof Phaser.Structs
* @constructor
* @since 3.16.0
*
* @param {number} [width=0] - The width of the Size component.
* @param {number} [height=width] - The height of the Size component. If not given, it will use the `width`.
* @param {number} [aspectMode=0] - The aspect mode of the Size component. Defaults to 0, no mode.
* @param {any} [parent=null] - The parent of this Size component. Can be any object with public `width` and `height` properties. Dimensions are clamped to keep them within the parent bounds where possible.
*/
/**
* Sets the aspect mode of this Size component.
*
* The aspect mode controls what happens when you modify the `width` or `height` properties, or call `setSize`.
*
* It can be a number from 0 to 4, or a Size constant:
*
* 0. NONE = Do not make the size fit the aspect ratio. Change the ratio when the size changes.
* 1. WIDTH_CONTROLS_HEIGHT = The height is automatically adjusted based on the width.
* 2. HEIGHT_CONTROLS_WIDTH = The width is automatically adjusted based on the height.
* 3. FIT = The width and height are automatically adjusted to fit inside the given target area, while keeping the aspect ratio. Depending on the aspect ratio there may be some space inside the area which is not covered.
* 4. ENVELOP = The width and height are automatically adjusted to make the size cover the entire target area while keeping the aspect ratio. This may extend further out than the target size.
*
* Calling this method automatically recalculates the `width` and the `height`, if required.
*
* @method Phaser.Structs.Size#setAspectMode
* @since 3.16.0
*
* @param {number} [value=0] - The aspect mode value.
*
* @return {this} This Size component instance.
*/
/**
* Sets, or clears, the parent of this Size component.
*
* To clear the parent call this method with no arguments.
*
* The parent influences the maximum extents to which this Size component can expand,
* based on the aspect mode:
*
* NONE - The parent clamps both the width and height.
* WIDTH_CONTROLS_HEIGHT - The parent clamps just the width.
* HEIGHT_CONTROLS_WIDTH - The parent clamps just the height.
* FIT - The parent clamps whichever axis is required to ensure the size fits within it.
* ENVELOP - The parent is used to ensure the size fully envelops the parent.
*
* Calling this method automatically calls `setSize`.
*
* @method Phaser.Structs.Size#setParent
* @since 3.16.0
*
* @param {any} [parent] - Sets the parent of this Size component. Don't provide a value to clear an existing parent.
*
* @return {this} This Size component instance.
*/
/**
* Set the minimum width and height values this Size component will allow.
*
* The minimum values can never be below zero, or greater than the maximum values.
*
* Setting this will automatically adjust both the `width` and `height` properties to ensure they are within range.
*
* Note that based on the aspect mode, and if this Size component has a parent set or not, the minimums set here
* _can_ be exceeded in some situations.
*
* @method Phaser.Structs.Size#setMin
* @since 3.16.0
*
* @param {number} [width=0] - The minimum allowed width of the Size component.
* @param {number} [height=width] - The minimum allowed height of the Size component. If not given, it will use the `width`.
*
* @return {this} This Size component instance.
*/
/**
* Set the maximum width and height values this Size component will allow.
*
* Setting this will automatically adjust both the `width` and `height` properties to ensure they are within range.
*
* Note that based on the aspect mode, and if this Size component has a parent set or not, the maximums set here
* _can_ be exceeded in some situations.
*
* @method Phaser.Structs.Size#setMax
* @since 3.16.0
*
* @param {number} [width=Number.MAX_VALUE] - The maximum allowed width of the Size component.
* @param {number} [height=width] - The maximum allowed height of the Size component. If not given, it will use the `width`.
*
* @return {this} This Size component instance.
*/
/**
* Sets the width and height of this Size component based on the aspect mode.
*
* If the aspect mode is 'none' then calling this method will change the aspect ratio, otherwise the current
* aspect ratio is honored across all other modes.
*
* If snapTo values have been set then the given width and height are snapped first, prior to any further
* adjustment via min/max values, or a parent.
*
* If minimum and/or maximum dimensions have been specified, the values given to this method will be clamped into
* that range prior to adjustment, but may still exceed them depending on the aspect mode.
*
* If this Size component has a parent set, and the aspect mode is `fit` or `envelop`, then the given sizes will
* be clamped to the range specified by the parent.
*
* @method Phaser.Structs.Size#setSize
* @since 3.16.0
*
* @param {number} [width=0] - The new width of the Size component.
* @param {number} [height=width] - The new height of the Size component. If not given, it will use the `width`.
*
* @return {this} This Size component instance.
*/
/**
* Sets a new width and height for this Size component and updates the aspect ratio based on them.
*
* It _doesn't_ change the `aspectMode` and still factors in size limits such as the min max and parent bounds.
*
* @method Phaser.Structs.Size#resize
* @since 3.16.0
*
* @param {number} width - The new width of the Size component.
* @param {number} [height=width] - The new height of the Size component. If not given, it will use the `width`.
*
* @return {this} This Size component instance.
*/
/**
* The height is automatically adjusted based on the width.
*
* @name Phaser.Structs.Size.WIDTH_CONTROLS_HEIGHT
* @constant
* @type {number}
* @since 3.16.0
*/
/**
* The width is automatically adjusted based on the height.
*
* @name Phaser.Structs.Size.HEIGHT_CONTROLS_WIDTH
* @constant
* @type {number}
* @since 3.16.0
*/
/**
* Takes the given texture key and frame and then stamps it at the given
* x and y coordinates. You can use the optional 'config' argument to provide
* lots more options about how the stamp is applied, including the alpha,
* tint, angle, scale and origin.
*
* By default, the frame will stamp on the x/y coordinates based on its center.
*
* If you wish to stamp from the top-left, set the config `originX` and
* `originY` properties both to zero.
*
* This method ignores the `camera` property of the Dynamic Texture.
*
* @method Phaser.Textures.DynamicTexture#stamp
* @since 3.60.0
*
* @param {string} key - The key of the texture to be used, as stored in the Texture Manager.
* @param {(string|number)} [frame] - The name or index of the frame within the Texture. Set to `null` to skip this argument if not required.
* @param {number} [x=0] - The x position to draw the frame at.
* @param {number} [y=0] - The y position to draw the frame at.
* @param {Phaser.Types.Textures.StampConfig} [config] - The stamp configuration object, allowing you to set the alpha, tint, angle, scale and origin of the stamp.
*
* @return {this} This Dynamic Texture instance.
*/
/**
* Draws the given object, or an array of objects, to this Dynamic Texture.
*
* It can accept any of the following:
*
* * Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
* * Tilemap Layers.
* * A Group. The contents of which will be iterated and drawn in turn.
* * A Container. The contents of which will be iterated fully, and drawn in turn.
* * A Scene Display List. Pass in `Scene.children` to draw the whole list.
* * Another Dynamic Texture, or a Render Texture.
* * A Texture Frame instance.
* * A string. This is used to look-up the texture from the Texture Manager.
*
* Note 1: You cannot draw a Dynamic Texture to itself.
*
* Note 2: GameObjects will use the camera, while textures and frames will not.
* Textures and frames are drawn using the `stamp` method.
*
* If passing in a Group or Container it will only draw children that return `true`
* when their `willRender()` method is called. I.e. a Container with 10 children,
* 5 of which have `visible=false` will only draw the 5 visible ones.
*
* If passing in an array of Game Objects it will draw them all, regardless if
* they pass a `willRender` check or not.
*
* You can pass in a string in which case it will look for a texture in the Texture
* Manager matching that string, and draw the base frame. If you need to specify
* exactly which frame to draw then use the method `drawFrame` instead.
*
* You can pass in the `x` and `y` coordinates to draw the objects at. The use of
* the coordinates differ based on what objects are being drawn. If the object is
* a Group, Container or Display List, the coordinates are _added_ to the positions
* of the children. For all other types of object, the coordinates are exact.
* For textures and frames, the `x` and `y` values are the middle of the texture.
*
* The `alpha` and `tint` values are only used by Texture Frames.
* Game Objects use their own alpha and tint values when being drawn.
*
* @method Phaser.Textures.DynamicTexture#draw
* @since 3.2.0
*
* @param {any} entries - Any renderable Game Object, or Group, Container, Display List, other Render Texture, Texture Frame or an array of any of these.
* @param {number} [x=0] - The x position to draw the Frame at, or the offset applied to the object.
* @param {number} [y=0] - The y position to draw the Frame at, or the offset applied to the object.
* @param {number} [alpha=1] - The alpha value. Only used when drawing Texture Frames to this texture. Game Objects use their own alpha.
* @param {number} [tint=0xffffff] - The tint color value. Only used when drawing Texture Frames to this texture. Game Objects use their own tint. WebGL only.
*
* @return {this} This Dynamic Texture instance.
*/
/**
* Takes the given Texture Frame and draws it to this Dynamic Texture as a fill pattern,
* i.e. in a grid-layout based on the frame dimensions.
* It uses a `TileSprite` internally to draw the frame repeatedly.
*
* Textures are referenced by their string-based keys, as stored in the Texture Manager.
*
* You can optionally provide a position, width, height, alpha and tint value to apply to
* the frames before they are drawn. The position controls the top-left where the repeating
* fill will start from. The width and height control the size of the filled area.
*
* The position can be negative if required, but the dimensions cannot.
*
* This method respects the camera settings of the Dynamic Texture.
*
* @method Phaser.Textures.DynamicTexture#repeat
* @since 3.60.0
*
* @param {string} key - The key of the texture to be used, as stored in the Texture Manager.
* @param {(string|number)} [frame] - The name or index of the frame within the Texture. Set to `null` to skip this argument if not required.
* @param {number} [x=0] - The x position to start drawing the frames from (can be negative to offset).
* @param {number} [y=0] - The y position to start drawing the frames from (can be negative to offset).
* @param {number} [width=this.width] - The width of the area to repeat the frame within. Defaults to the width of this Dynamic Texture.
* @param {number} [height=this.height] - The height of the area to repeat the frame within. Defaults to the height of this Dynamic Texture.
* @param {Phaser.Types.GameObjects.TileSprite.TileSpriteConfig} [config] - The configuration object for the TileSprite which repeats the texture, allowing you to set further properties on it.
*
* @return {this} This Dynamic Texture instance.
*/
/**
* Takes a crop data object and, based on the rectangular region given, calculates the
* required UV coordinates in order to crop this Frame for WebGL and Canvas rendering.
*
* The crop size as well as coordinates can not exceed the size of the frame.
*
* This is called directly by the Game Object Texture Components `setCrop` method.
* Please use that method to crop a Game Object.
*
* @method Phaser.Textures.Frame#setCropUVs
* @since 3.11.0
*
* @param {object} crop - The crop data object. This is the `GameObject._crop` property.
* @param {number} x - The x coordinate to start the crop from. Cannot be negative or exceed the Frame width.
* @param {number} y - The y coordinate to start the crop from. Cannot be negative or exceed the Frame height.
* @param {number} width - The width of the crop rectangle. Cannot exceed the Frame width.
* @param {number} height - The height of the crop rectangle. Cannot exceed the Frame height.
* @param {boolean} flipX - Does the parent Game Object have flipX set?
* @param {boolean} flipY - Does the parent Game Object have flipY set?
*
* @return {object} The updated crop data object.
*/
/**
* Takes a crop data object and recalculates the UVs based on the dimensions inside the crop object.
* Called automatically by `setFrame`.
*
* @method Phaser.Textures.Frame#updateCropUVs
* @since 3.11.0
*
* @param {object} crop - The crop data object. This is the `GameObject._crop` property.
* @param {boolean} flipX - Does the parent Game Object have flipX set?
* @param {boolean} flipY - Does the parent Game Object have flipY set?
*
* @return {object} The updated crop data object.
*/
/**
* Gets a Frame from this Texture based on either the key or the index of the Frame.
*
* In a Texture Atlas Frames are typically referenced by a key.
* In a Sprite Sheet Frames are referenced by an index.
* Passing no value for the name returns the base texture.
*
* @method Phaser.Textures.Texture#get
* @since 3.0.0
*
* @param {(string|number)} [name] - The string-based name, or integer based index, of the Frame to get from this Texture.
*
* @return {Phaser.Textures.Frame} The Texture Frame.
*/
/**
* Based on the given Texture Source Index, this method will get all of the Frames using
* that source and then work out the bounds that they encompass, returning them in an object.
*
* This is useful if this Texture is, for example, a sprite sheet within an Atlas, and you
* need to know the total bounds of the sprite sheet.
*
* @method Phaser.Textures.Texture#getFrameBounds
* @since 3.80.0
*
* @param {number} [sourceIndex=0] - The index of the TextureSource to get the Frame bounds from.
*
* @return {Phaser.Types.Math.RectangleLike} An object containing the bounds of the Frames using the given Texture Source Index.
*/
/**
* Parses a Unity YAML File and creates Frames in the Texture.
* For more details about Sprite Meta Data see https://docs.unity3d.com/ScriptReference/SpriteMetaData.html
*
* @function Phaser.Textures.Parsers.UnityYAML
* @memberof Phaser.Textures.Parsers
* @private
* @since 3.0.0
*
* @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to.
* @param {number} sourceIndex - The index of the TextureSource.
* @param {object} yaml - The YAML data.
*
* @return {Phaser.Textures.Texture} The Texture modified by this parser.
*/
/**
* @author Ben Richards <benjamindrichards@gmail.com>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Checks whether this tile is considered "interesting" based on the provided criteria. A tile
* is interesting if it has active collision flags on any side, if it has an interesting face,
* or both, depending on the arguments passed. This is used internally by the tilemap collision
* system to quickly filter tiles that need further processing.
*
* @method Phaser.Tilemaps.Tile#isInteresting
* @since 3.0.0
*
* @param {boolean} collides - If true, will consider the tile interesting if it collides on any side.
* @param {boolean} faces - If true, will consider the tile interesting if it has an interesting face.
*
* @return {boolean} True if the Tile is interesting, otherwise false.
*/
/**
* Used internally. Updates the tile's world XY position based on the current tile size.
*
* @method Phaser.Tilemaps.Tile#updatePixelXY
* @since 3.0.0
*
* @return {this} This Tile object instance.
*/
/**
* @classdesc
* A Tilemap is a container for Tilemap data. This isn't a display object, rather, it holds data
* about the map and allows you to add tilesets and tilemap layers to it. A map can have one or
* more tilemap layers, which are the display objects that actually render the tiles.
*
* The Tilemap data can be parsed from a Tiled JSON file, a CSV file or a 2D array. Tiled is a free
* software package specifically for creating tile maps, and is available from:
* http://www.mapeditor.org
*
* The Tilemap API supports the following types of map:
*
* 1) Orthogonal
* 2) Isometric
* 3) Hexagonal
* 4) Staggered
*
* All map types use the unified `TilemapLayer` class, which combines the capabilities of the
* former Static and Dynamic layers into a single, simplified API.
*
* A Tilemap has handy methods for getting and manipulating the tiles within a layer, allowing
* you to build or modify the tilemap data at runtime.
*
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a
* TilemapLayer may have its own unique tile size that overrides this.
*
* If your tilemap includes layer groups (a feature of Tiled 1.2.0+) these
* will be traversed and the following properties will impact children:
*
* - Opacity (blended with parent) and visibility (parent overrides child)
* - Vertical and horizontal offset
*
* The grouping hierarchy is not preserved and all layers will be flattened into a single array.
*
* Group layers are parsed during Tilemap construction but are discarded after parsing so dynamic
* layers will NOT continue to be affected by a parent.
*
* To avoid duplicate layer names, a layer that is a child of a group layer will have its parent
* group name prepended with a '/'. For example, consider a group called 'ParentGroup' with a
* child called 'Layer 1'. In the Tilemap object, 'Layer 1' will have the name
* 'ParentGroup/Layer 1'.
*
* The Phaser Tiled Parser does **not** support the 'Collection of Images' feature for a Tileset.
* You must ensure all of your tiles are contained in a single tileset image file (per layer)
* and have this 'embedded' in the exported Tiled JSON map data.
*
* @class Tilemap
* @memberof Phaser.Tilemaps
* @constructor
* @since 3.0.0
*
* @param {Phaser.Scene} scene - The Scene to which this Tilemap belongs.
* @param {Phaser.Tilemaps.MapData} mapData - A MapData instance containing Tilemap data.
*/
/**
* The width of the map in pixels based on width * tileWidth.
*
* @name Phaser.Tilemaps.Tilemap#widthInPixels
* @type {number}
* @since 3.0.0
*/
/**
* The height of the map in pixels based on height * tileHeight.
*
* @name Phaser.Tilemaps.Tilemap#heightInPixels
* @type {number}
* @since 3.0.0
*/
/**
* This method will iterate through all of the objects defined in a Tiled Object Layer and then
* convert the matching results into Phaser Game Objects (by default, Sprites)
*
* Objects are matched on one of 4 criteria: The Object ID, the Object GID, the Object Name, or the Object Type.
*
* Within Tiled, Object IDs are unique per Object. Object GIDs, however, are shared by all objects
* using the same image. Finally, Object Names and Types are strings and the same name can be used on multiple
* Objects in Tiled, they do not have to be unique; Names are specific to Objects while Types can be inherited
* from Object GIDs using the same image.
*
* You set the configuration parameter accordingly, based on which type of criteria you wish
* to match against. For example, to convert all items on an Object Layer with a `gid` of 26:
*
* ```javascript
* createFromObjects(layerName, {
* gid: 26
* });
* ```
*
* Or, to convert objects with the name 'bonus':
*
* ```javascript
* createFromObjects(layerName, {
* name: 'bonus'
* });
* ```
*
* Or, to convert an object with a specific id:
*
* ```javascript
* createFromObjects(layerName, {
* id: 9
* });
* ```
*
* You should only specify either `id`, `gid`, `name`, `type`, or none of them. Do not add more than
* one criteria to your config. If you do not specify any criteria, then _all_ objects in the
* Object Layer will be converted.
*
* By default this method will convert Objects into {@link Phaser.GameObjects.Sprite} instances, but you can override
* this by providing your own class type:
*
* ```javascript
* createFromObjects(layerName, {
* gid: 26,
* classType: Coin
* });
* ```
*
* This will convert all Objects with a gid of 26 into your custom `Coin` class. You can pass
* any class type here, but it _must_ extend {@link Phaser.GameObjects.GameObject} as its base class.
* Your class will always be passed 1 parameter: `scene`, which is a reference to either the Scene
* specified in the config object or, if not given, the Scene to which this Tilemap belongs. The
* class must have {@link Phaser.GameObjects.Components.Transform#setPosition setPosition} and
* {@link Phaser.GameObjects.Components.Texture#setTexture setTexture} methods.
*
* This method will set the following Tiled Object properties on the new Game Object:
*
* - `flippedHorizontal` as `flipX`
* - `flippedVertical` as `flipY`
* - `height` as `displayHeight`
* - `name`
* - `rotation`
* - `visible`
* - `width` as `displayWidth`
* - `x`, adjusted for origin
* - `y`, adjusted for origin
*
* Additionally, this method will set Tiled Object custom properties
*
* - on the Game Object, if it has the same property name and a value that isn't `undefined`; or
* - on the Game Object's {@link Phaser.GameObjects.GameObject#data data store} otherwise.
*
* For example, a Tiled Object with custom properties `{ alpha: 0.5, gold: 1 }` will be created as a Game
* Object with an `alpha` value of 0.5 and a `data.values.gold` value of 1.
*
* When `useTileset` is `true` (the default), Tile Objects will inherit the texture and any tile properties
* from the tileset, and the local tile ID will be used as the texture frame. For the frame selection to work
* you need to load the tileset texture as a spritesheet so its frame names match the local tile IDs.
*
* For instance, a tileset tile
*
* ```
* { id: 3, type: 'treadmill', speed: 4 }
* ```
*
* with gid 19 and an object
*
* ```
* { id: 7, gid: 19, speed: 5, rotation: 90 }
* ```
*
* will be interpreted as
*
* ```
* { id: 7, gid: 19, speed: 5, rotation: 90, type: 'treadmill', texture: '[the tileset texture]', frame: 3 }
* ```
*
* You can suppress this behavior by setting the boolean `ignoreTileset` for each `config` that should ignore
* object gid tilesets.
*
* You can set a `container` property in the config. If given, the new Game Object will be added to
* the Container or Layer instance instead of the Scene.
*
* You can set named texture-`key` and texture-`frame` properties, which will be set on the new Game Object.
*
* Finally, you can provide an array of config objects, to convert multiple types of object in
* a single call:
*
* ```javascript
* createFromObjects(layerName, [
* {
* gid: 26,
* classType: Coin
* },
* {
* id: 9,
* classType: BossMonster
* },
* {
* name: 'lava',
* classType: LavaTile
* },
* {
* type: 'endzone',
* classType: Phaser.GameObjects.Zone
* }
* ]);
* ```
*
* The signature of this method changed significantly in v3.60.0. Prior to this, it did not take config objects.
*
* @method Phaser.Tilemaps.Tilemap#createFromObjects
* @since 3.0.0
*
* @param {string} objectLayerName - The name of the Tiled object layer to create the Game Objects from.
* @param {Phaser.Types.Tilemaps.CreateFromObjectLayerConfig|Phaser.Types.Tilemaps.CreateFromObjectLayerConfig[]} config - A CreateFromObjects configuration object, or an array of them.
* @param {boolean} [useTileset=true] - True if objects that set gids should also search the underlying tile for properties and data.
*
* @return {Phaser.GameObjects.GameObject[]} An array containing the Game Objects that were created. Empty if invalid object layer, or no matching id/gid/name was found.
*/
/**
* Gets the image layer index based on its name.
*
* @method Phaser.Tilemaps.Tilemap#getImageIndex
* @since 3.0.0
*
* @param {string} name - The name of the image to get.
*
* @return {number} The index of the image in this tilemap, or null if not found.
*/
/**
* Returns an array of Vector2s where each entry corresponds to the corner of the requested tile.
*
* The `tileX` and `tileY` parameters are in tile coordinates, not world coordinates.
*
* The corner coordinates are in world space, having factored in TilemapLayer scale, position
* and the camera, if given.
*
* The size of the array will vary based on the orientation of the map. For example an
* orthographic map will return an array of 4 vectors, where-as a hexagonal map will,
* of course, return an array of 6 corner vectors.
*
* If no layer is specified, the maps current layer is used.
*
* @method Phaser.Tilemaps.Tilemap#getTileCorners
* @since 3.60.0
*
* @param {number} tileX - The x coordinate, in tiles, not pixels.
* @param {number} tileY - The y coordinate, in tiles, not pixels.
* @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use when calculating the tile index from the world values.
* @param {(string|number|Phaser.Tilemaps.TilemapLayer)} [layer] - The tile layer to use. If not given the current layer is used.
*
* @return {?Phaser.Math.Vector2[]} Returns an array of Vector2s, or null if the layer given was invalid.
*/
/**
* The callback that is invoked when the tiles are culled.
*
* It will call a different function based on the map orientation:
*
* Orthogonal (the default) is `TilemapComponents.CullTiles`
* Isometric is `TilemapComponents.IsometricCullTiles`
* Hexagonal is `TilemapComponents.HexagonalCullTiles`
* Staggered is `TilemapComponents.StaggeredCullTiles`
*
* However, you can override this to call any function you like.
*
* It will be sent 4 arguments:
*
* 1. The Phaser.Tilemaps.LayerData object for this Layer
* 2. The Camera that is culling the layer. You can check its `dirty` property to see if it has changed since the last cull.
* 3. A reference to the `culledTiles` array, which should be used to store the tiles you want rendered.
* 4. The Render Order constant.
*
* See the `TilemapComponents.CullTiles` source code for details on implementing your own culling system.
*
* @name Phaser.Tilemaps.TilemapLayer#cullCallback
* @type {function}
* @since 3.50.0
*/
/**
* Returns an array of Vector2s where each entry corresponds to the corner of the requested tile.
*
* The `tileX` and `tileY` parameters are in tile coordinates, not world coordinates.
*
* The corner coordinates are in world space, having factored in TilemapLayer scale, position
* and the camera, if given.
*
* The size of the array will vary based on the orientation of the map. For example an
* orthographic map will return an array of 4 vectors, where-as a hexagonal map will,
* of course, return an array of 6 corner vectors.
*
* @method Phaser.Tilemaps.TilemapLayerBase#getTileCorners
* @since 3.60.0
*
* @param {number} tileX - The x coordinate, in tiles, not pixels.
* @param {number} tileY - The y coordinate, in tiles, not pixels.
* @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use when calculating the tile index from the world values.
*
* @return {?Phaser.Math.Vector2[]} Returns an array of Vector2s, or null if the layer given was invalid.
*/
/**
* Converts from world X coordinates (pixels) to tile X coordinates (tile units), factoring in the
* layers position, scale and scroll.
*
* You cannot call this method for Isometric or Hexagonal tilemaps as they require
* both `worldX` and `worldY` values to determine the correct tile, instead you
* should use the `worldToTileXY` method.
*
* @method Phaser.Tilemaps.TilemapLayerBase#worldToTileX
* @since 3.50.0
*
* @param {number} worldX - The x coordinate to be converted, in pixels, not tiles.
* @param {boolean} [snapToFloor] - Whether or not to round the tile coordinate down to the nearest integer.
* @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use when calculating the tile index from the world values.
*
* @return {number} The tile X coordinate based on the world value.
*/
/**
* Converts from world Y coordinates (pixels) to tile Y coordinates (tile units), factoring in the
* layers position, scale and scroll.
*
* You cannot call this method for Isometric or Hexagonal tilemaps as they require
* both `worldX` and `worldY` values to determine the correct tile, instead you
* should use the `worldToTileXY` method.
*
* @method Phaser.Tilemaps.TilemapLayerBase#worldToTileY
* @since 3.50.0
*
* @param {number} worldY - The y coordinate to be converted, in pixels, not tiles.
* @param {boolean} [snapToFloor] - Whether or not to round the tile coordinate down to the nearest integer.
* @param {Phaser.Cameras.Scene2D.Camera} [camera] - The Camera to use when calculating the tile index from the world values.
*
* @return {number} The tile Y coordinate based on the world value.
*/
/**
* Gets the correct function to use to cull tiles, based on the map orientation.
*
* @function Phaser.Tilemaps.Components.GetCullTilesFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to cull tiles for the given map type.
*/
/**
* Gets the correct function to use to get the tile corners, based on the map orientation.
*
* @function Phaser.Tilemaps.Components.GetTileCornersFunction
* @since 3.60.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to get the tile corners for the given map orientation.
*/
/**
* Returns the correct function to use for converting a tile X coordinate to a world X pixel
* coordinate, based on the map orientation. For orthogonal maps, this returns the `TileToWorldX`
* function. For all other orientations, a NOOP function is returned, as non-orthogonal maps
* do not support this conversion.
*
* @function Phaser.Tilemaps.Components.GetTileToWorldXFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to convert tile X coordinates to world X pixel coordinates for the given map orientation.
*/
/**
* Gets the correct function to use to translate tiles, based on the map orientation.
*
* @function Phaser.Tilemaps.Components.GetTileToWorldXYFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to translate tiles for the given map type.
*/
/**
* Gets the correct function to use to translate tiles, based on the map orientation.
*
* @function Phaser.Tilemaps.Components.GetTileToWorldYFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to translate tiles for the given map type.
*/
/**
* Returns the correct function to use for converting a world pixel X coordinate to a tile X
* (column) index, based on the map orientation. Only orthogonal maps support this conversion;
* for all other orientations a NULL function is returned.
*
* @function Phaser.Tilemaps.Components.GetWorldToTileXFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to convert a world X coordinate to a tile X index for the given map orientation, or a NULL function if the orientation is unsupported.
*/
/**
* Returns the correct function to use for converting a world Y coordinate to a tile Y coordinate,
* based on the map orientation. Returns `WorldToTileY` for orthogonal maps, `StaggeredWorldToTileY`
* for staggered maps, and a NULL function for all other orientations.
*
* @function Phaser.Tilemaps.Components.GetWorldToTileYFunction
* @since 3.50.0
*
* @param {number} orientation - The Tilemap orientation constant.
*
* @return {function} The function to use to convert a world Y coordinate to a tile Y coordinate for the given map orientation.
*/
/**
* An array of all objects on this Object Layer.
*
* Each Tiled object corresponds to a JavaScript object in this array. It has an `id` (unique),
* `name` (as assigned in Tiled), `type` (as assigned in Tiled), `rotation` (in clockwise degrees),
* `properties` (if any), `visible` state (`true` if visible, `false` otherwise),
* `x` and `y` coordinates (in pixels, relative to the tilemap), and a `width` and `height` (in pixels).
*
* An object tile has a `gid` property (GID of the represented tile), a `flippedHorizontal` property,
* a `flippedVertical` property, and `flippedAntiDiagonal` property.
* The {@link http://docs.mapeditor.org/en/latest/reference/tmx-map-format/|Tiled documentation} contains
* information on flipping and rotation.
*
* Polylines have a `polyline` property, which is an array of objects corresponding to points,
* where each point has an `x` property and a `y` property. Polygons have an identically structured
* array in their `polygon` property. Text objects have a `text` property with the text's properties.
*
* Rectangles and ellipses have a `rectangle` or `ellipse` property set to `true`.
*
* @name Phaser.Tilemaps.ObjectLayer#objects
* @type {Phaser.Types.Tilemaps.TiledObject[]}
* @since 3.0.0
*/
/**
* @author Seth Berrier <berriers@uwstout.edu>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Parses a Tiled Global Tile ID (GID), extracting the tile index and any flip flags encoded
* in the high bits of the value. In the Tiled TMX format, the top three bits of a GID are used
* to indicate horizontal flip, vertical flip, and anti-diagonal flip (i.e. 90-degree rotation).
*
* This function strips those flag bits from the GID to recover the raw tile index, then
* interprets all eight possible combinations of the three flags and converts them into a
* rotation value (in radians) and a boolean `flipped` state that Phaser can apply directly
* to a tile when rendering.
*
* See the Tiled documentation on tile flipping for the full flag specification:
* http://docs.mapeditor.org/en/latest/reference/tmx-map-format/
*
* @function Phaser.Tilemaps.Parsers.Tiled.ParseGID
* @since 3.0.0
*
* @param {number} gid - A Tiled GID, potentially with flip flags encoded in the high bits.
*
* @return {Phaser.Types.Tilemaps.GIDData} A GIDData object containing the raw tile index, the three individual flip flags, and the derived rotation (in radians) and flipped state.
*/
/**
* Parses a Tiled JSON object into a new MapData object. The source JSON is deep copied before
* processing. This function handles orthogonal, isometric, staggered, and hexagonal map
* orientations. For hexagonal maps it also calculates the pixel dimensions based on the hex side
* length and stagger axis. It parses all tile layers, image layers, object layers, and tilesets
* found in the JSON, builds the tileset index, and assigns custom tile properties before returning
* the fully populated MapData instance.
*
* @function Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled
* @since 3.0.0
*
* @param {string} name - The name of the tilemap, used to set the name on the MapData.
* @param {object} source - The original Tiled JSON object. This is deep copied by this function.
* @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map
* data are handled. If `true`, empty locations will get a value of `null`. If `false`, empty
* location will get a Tile object with an index of -1. If you have a large sparsely populated map and
* the tile data doesn't need to change then setting this value to `true` will help with memory
* consumption. However if your map is small or you need to update the tiles dynamically, then leave
* the default value set.
*
* @return {?Phaser.Tilemaps.MapData} The created MapData object, or `null` if the data can't be parsed.
*/
/**
* Parses out the Wangset information from Tiled 1.1.5+ map data, if present.
*
* Since a given tile can be in more than one wangset, the resulting properties
* are nested. `tile.data.wangid[someWangsetName]` will return the array-based wang id in
* this implementation.
*
* Note that we're not guaranteed that there will be any 'normal' tiles if the only
* things in the tileset are wangtile definitions, so this has to be parsed separately.
*
* See https://doc.mapeditor.org/en/latest/manual/using-wang-tiles/ for more information.
*
* @function Phaser.Tilemaps.Parsers.Tiled.ParseWangsets
* @since 3.53.0
*
* @param {Array.<object>} wangsets - The array of wangset objects (parsed from JSON)
* @param {object} datas - The object into which wangset data from Tiled is stored, keyed by tile ID.
*/
/**
* Updates the Clock's internal time and all of its Timer Events.
*
* @method Phaser.Time.Clock#update
* @since 3.0.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Updates the elapsed time counter, if this Timeline is not paused.
*
* @method Phaser.Time.Timeline#preUpdate
* @since 3.60.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Called automatically by the Scene update step.
*
* Iterates through all of the Timeline Events and checks to see if they should be run.
*
* If they should be run, then the event's callbacks and actions are invoked.
*
* If the `TimelineEvent.once` property is `true` then the event is removed from the Timeline.
*
* If the `TimelineEvent.event` property is set then the Timeline emits that event.
*
* If the `TimelineEvent.run` property is set then the Timeline invokes that method.
*
* If the `TimelineEvent.loop` property is set then the Timeline invokes that method when repeated.
*
* If the `TimelineEvent.target` property is set then the Timeline invokes the `run` method on that target.
*
* @method Phaser.Time.Timeline#update
* @fires Phaser.Time.Events#COMPLETE
* @since 3.60.0
*
* @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Returns a number between 0 and 1 representing the progress of this Timeline.
*
* A value of 0 means the Timeline has just started, 0.5 means it's half way through,
* and 1 means it's complete.
*
* If the Timeline has no events, or all events have been removed, this will return `NaN`.
*
* If the Timeline is paused, this will return the progress value at the time it was paused.
*
* Note that the value returned is based on the number of events that have been completed,
* not the 'duration' of the events (as this is unknown to the Timeline).
*
* @method Phaser.Time.Timeline#getProgress
* @since 3.60.0
*
* @return {number} A number between 0 and 1 representing the progress of this Timeline.
*/
/**
* @classdesc
* A Timer Event represents a delayed function call. It's managed by a Scene's {@link Clock} and will call its function after a set amount of time has passed. The Timer Event can optionally repeat - i.e. call its function multiple times before finishing, or loop indefinitely.
*
* Because it's managed by a Clock, a Timer Event is based on game time, will be affected by its Clock's time scale, and will pause if its Clock pauses.
*
* @class TimerEvent
* @memberof Phaser.Time
* @constructor
* @since 3.0.0
*
* @param {Phaser.Types.Time.TimerEventConfig} config - The configuration for the Timer Event, including its delay and callback.
*/
/**
* Returns `getActive`, `getStart` and `getEnd` functions for a TweenData based on a target property and end value.
*
* `getActive` if not null, is invoked _immediately_ as soon as the TweenData is running, and is set on the target property.
* `getEnd` is invoked once any start delays have expired and returns what the value should tween to.
* `getStart` is invoked when the tween reaches the end and needs to either repeat or yoyo, it returns the value to go back to.
*
* If the end value is a number, it will be treated as an absolute value and the property will be tweened to it.
* A string can be provided to specify a relative end value which consists of an operation
* (`+=` to add to the current value, `-=` to subtract from the current value, `*=` to multiply the current
* value, or `/=` to divide the current value) followed by its operand.
*
* A function can be provided to allow greater control over the end value; it will receive the target
* object being tweened, the name of the property being tweened, and the current value of the property
* as its arguments and must return a value.
*
* If both the starting and the ending values need to be controlled, an object with `getStart` and `getEnd`
* callbacks, which will receive the same arguments, can be provided instead. If an object with a `value`
* property is provided, the property will be used as the effective value under the same rules described here.
*
* @function Phaser.Tweens.Builders.GetValueOp
* @since 3.0.0
*
* @param {string} key - The name of the property to modify.
* @param {*} propertyValue - The ending value of the property, as described above.
*
* @return {function} An object containing `getActive`, `getStart`, and `getEnd` functions, which return the active, starting, and ending values of the property based on the provided value.
*/
/**
* Creates a Stagger function to be used by a Tween property.
*
* The stagger function will allow you to stagger changes to the value of the property across all targets of the tween.
*
* This is only worth using if the tween has multiple targets.
*
* The following will stagger the delay by 100ms across all targets of the tween, causing them to scale down to 0.2
* over the duration specified:
*
* ```javascript
* this.tweens.add({
* targets: [ ... ],
* scale: 0.2,
* ease: 'linear',
* duration: 1000,
* delay: this.tweens.stagger(100)
* });
* ```
*
* The following will stagger the delay by 500ms across all targets of the tween using a 10 x 6 grid, staggering
* from the center out, using a cubic ease.
*
* ```javascript
* this.tweens.add({
* targets: [ ... ],
* scale: 0.2,
* ease: 'linear',
* duration: 1000,
* delay: this.tweens.stagger(500, { grid: [ 10, 6 ], from: 'center', ease: 'cubic.out' })
* });
* ```
*
* @function Phaser.Tweens.Builders.StaggerBuilder
* @since 3.19.0
*
* @param {(number|number[])} value - The amount to stagger by, or an array containing two elements representing the min and max values to stagger between.
* @param {Phaser.Types.Tweens.StaggerConfig} [options] - A Stagger Configuration object.
*
* @return {function} A stagger function that, when invoked by the Tween system for each target, calculates and returns the staggered property value for that target based on its index, the total number of targets, and the stagger configuration provided.
*/
/**
* Internal method that handles the processing of the loop delay countdown timer and
* the dispatch of related events. Called automatically by `Tween.update`.
*
* @method Phaser.Tweens.BaseTween#updateLoopCountdown
* @since 3.60.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Internal method that handles the processing of the start delay countdown timer and
* the dispatch of related events. Called automatically by `Tween.update`.
*
* @method Phaser.Tweens.BaseTween#updateStartCountdown
* @since 3.60.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Internal method that handles the processing of the complete delay countdown timer and
* the dispatch of related events. Called automatically by `Tween.update`.
*
* @method Phaser.Tweens.BaseTween#updateCompleteDelay
* @since 3.60.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
/**
* Seeks to a specific point in the Tween.
*
* The given amount is a value in milliseconds that represents how far into the Tween
* you wish to seek, based on the start of the Tween.
*
* Note that the seek amount takes the entire duration of the Tween into account, including delays, loops and repeats.
* For example, a Tween that lasts for 2 seconds, but that loops 3 times, would have a total duration of 6 seconds,
* so seeking to 3000 ms would seek to the Tweens half-way point based on its _entire_ duration.
*
* Prior to Phaser 3.60 this value was given as a number between 0 and 1 and didn't
* work for Tweens that had an infinite repeat. This new method works for all Tweens.
*
* Seeking works by resetting the Tween to its initial values and then iterating through the Tween at `delta`
* jumps per step. The longer the Tween, the longer this can take. If you need more precision you can
* reduce the delta value. If you need a faster seek, you can increase it. When the Tween is
* reset it will refresh the starting and ending values. If these are coming from a dynamic function,
* or a random array, it will be called for each seek.
*
* While seeking the Tween will _not_ emit any of its events or callbacks unless
* the 3rd parameter is set to `true`.
*
* If this Tween is paused, seeking will not change this fact. It will advance the Tween
* to the desired point and then pause it again.
*
* @method Phaser.Tweens.Tween#seek
* @since 3.0.0
*
* @param {number} [amount=0] - The number of milliseconds to seek into the Tween from the beginning.
* @param {number} [delta=16.6] - The size of each step when seeking through the Tween. A higher value completes faster but at the cost of less precision.
* @param {boolean} [emit=false] - While seeking, should the Tween emit any of its events or callbacks? The default is 'false', i.e. to seek silently.
*
* @return {this} This Tween instance.
*/
/**
* Internal method that advances the Tween based on the time values.
*
* @method Phaser.Tweens.Tween#update
* @fires Phaser.Tweens.Events#TWEEN_COMPLETE
* @fires Phaser.Tweens.Events#TWEEN_LOOP
* @fires Phaser.Tweens.Events#TWEEN_START
* @since 3.0.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*
* @return {boolean} Returns `true` if this Tween has finished and should be removed from the Tween Manager, otherwise returns `false`.
*/
/**
* Internal method that advances the TweenChain based on the time values.
*
* @method Phaser.Tweens.TweenChain#update
* @fires Phaser.Tweens.Events#TWEEN_COMPLETE
* @fires Phaser.Tweens.Events#TWEEN_LOOP
* @fires Phaser.Tweens.Events#TWEEN_START
* @since 3.60.0
*
* @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*
* @return {boolean} Returns `true` if this TweenChain has finished and should be removed from the Tween Manager, otherwise returns `false`.
*/
/**
* Sets the current active Tween to the given index, based on its
* entry in the TweenChain data array.
*
* @method Phaser.Tweens.TweenChain#setCurrentTween
* @since 3.60.0
*
* @param {number} index - The index of the Tween to be made current.
*/
/**
* Internal method that advances this TweenData based on the delta value given.
*
* @method Phaser.Tweens.TweenData#update
* @fires Phaser.Tweens.Events#TWEEN_UPDATE
* @fires Phaser.Tweens.Events#TWEEN_REPEAT
* @since 3.60.0
*
* @param {number} delta - The elapsed delta time in ms.
*
* @return {boolean} `true` if this TweenData is still playing, or `false` if it has finished entirely.
*/
/**
* Internal method that advances this TweenData based on the delta value given.
*
* @method Phaser.Tweens.TweenFrameData#update
* @fires Phaser.Tweens.Events#TWEEN_UPDATE
* @fires Phaser.Tweens.Events#TWEEN_REPEAT
* @since 3.60.0
*
* @param {number} delta - The elapsed delta time in ms.
*
* @return {boolean} `true` if this TweenData is still playing, or `false` if it has finished entirely.
*/
/**
* A [Floyd-Rivest](https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm) quick selection algorithm.
*
* Rearranges the array items so that all items in the [left, k] range are smaller than all items in [k, right];
* The k-th element will have the (k - left + 1)th smallest value in [left, right].
*
* The array is modified in-place.
*
* Based on code by [Vladimir Agafonkin](https://www.npmjs.com/~mourner)
*
* @function Phaser.Utils.Array.QuickSelect
* @since 3.0.0
*
* @param {array} arr - The array to rearrange in-place.
* @param {number} k - The k-th element index.
* @param {number} [left=0] - The index of the left part of the range.
* @param {number} [right] - The index of the right part of the range.
* @param {function} [compare] - An optional comparison function. Is passed two elements and should return a negative number if the first is less than the second, zero if they are equal, or a positive number if the first is greater.
*/
/**
* Creates an array populated with a range of values, based on the given arguments and configuration object.
*
* Range ([a,b,c], [1,2,3]) =
* a1, a2, a3, b1, b2, b3, c1, c2, c3
*
* Range ([a,b], [1,2,3], qty = 3) =
* a1, a1, a1, a2, a2, a2, a3, a3, a3, b1, b1, b1, b2, b2, b2, b3, b3, b3
*
* Range ([a,b,c], [1,2,3], repeat x1) =
* a1, a2, a3, b1, b2, b3, c1, c2, c3, a1, a2, a3, b1, b2, b3, c1, c2, c3
*
* Range ([a,b], [1,2], repeat -1 = endless, max = 14) =
* a1, a2, b1, b2, a1, a2, b1, b2, a1, a2, b1, b2, a1, a2 (capped at 14 elements)
*
* Range ([a], [1,2,3,4,5], random = true) =
* a4, a1, a5, a2, a3
*
* Range ([a, b], [1,2,3], random = true) =
* b3, a2, a1, b1, a3, b2
*
* Range ([a, b, c], [1,2,3], randomB = true) =
* a3, a1, a2, b2, b3, b1, c1, c3, c2
*
* Range ([a], [1,2,3,4,5], yoyo = true) =
* a1, a2, a3, a4, a5, a5, a4, a3, a2, a1
*
* Range ([a, b], [1,2,3], yoyo = true) =
* a1, a2, a3, b1, b2, b3, b3, b2, b1, a3, a2, a1
*
* @function Phaser.Utils.Array.Range
* @since 3.0.0
*
* @param {array} a - The first array of range elements.
* @param {array} b - The second array of range elements.
* @param {object} [options] - A range configuration object. Supports the following properties: `qty` (number of times each pair is duplicated, default 1), `repeat` (number of times the entire range is repeated, use -1 for endless), `random` (shuffle the full output array), `randomB` (shuffle array `b` before building pairs), `yoyo` (append the range in reverse after the forward pass), `max` (cap the total number of elements in the output).
*
* @return {array} An array of `{ a, b }` pair objects built from the cartesian product of the two input arrays, arranged according to the given options.
*/
/**
* Removes a single item from an array and returns it without creating gc, like the native splice does.
* Based on code by Mike Reinstein.
*
* @function Phaser.Utils.Array.SpliceOne
* @since 3.0.0
*
* @param {array} array - The array to splice from.
* @param {number} index - The index of the item which should be spliced.
*
* @return {*} The item which was spliced (removed).
*/
/**
* @author Richard Davey <rich@phaser.io>
* @author Angry Bytes (and contributors)
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* An in-place stable array sort, because `Array#sort()` is not guaranteed stable.
*
* This is an implementation of merge sort, without recursion.
*
* Function based on the Two-Screen/stable sort 0.1.8 from https://github.com/Two-Screen/stable
*
* @function Phaser.Utils.Array.StableSort
* @since 3.0.0
*
* @param {array} array - The input array to be sorted.
* @param {function} [compare] - The comparison function.
*
* @return {array} The sorted result.
*/
/**
* Rotates the array matrix based on the given rotation value.
*
* The value can be given in degrees: 90, -90, 270, -270, 180 or -180,
* or a string command: `rotateLeft`, `rotateRight` or `rotate180`.
*
* Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
*
* A matrix is a two-dimensional array (array of arrays), where all sub-arrays (rows)
* have the same length. There must be at least two rows. This is an example matrix:
*
* ```
* [
* [ 1, 1, 1, 1, 1, 1 ],
* [ 2, 0, 0, 0, 0, 4 ],
* [ 2, 0, 1, 2, 0, 4 ],
* [ 2, 0, 3, 4, 0, 4 ],
* [ 2, 0, 0, 0, 0, 4 ],
* [ 3, 3, 3, 3, 3, 3 ]
* ]
* ```
*
* @function Phaser.Utils.Array.Matrix.RotateMatrix
* @since 3.0.0
*
* @generic T
* @genericUse {T[][]} - [matrix,$return]
*
* @param {T[][]} [matrix] - The array to rotate.
* @param {(number|string)} [direction=90] - The amount to rotate the matrix by. Must be a degree value of 90, -90, 270, -270, 180 or -180, or a string command of `rotateLeft`, `rotateRight` or `rotate180`. If an unrecognized value is given the matrix will not be rotated.
*
* @return {T[][]} The rotated matrix array. The source matrix should be discarded for the returned matrix.
*/
/**
* @author Niklas von Hertzen (https://github.com/niklasvh/base64-arraybuffer)
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2026 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Converts an ArrayBuffer into a base64 string.
*
* The resulting string can optionally be a data uri if the `mediaType` argument is provided.
*
* See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs for more details.
*
* @function Phaser.Utils.Base64.ArrayBufferToBase64
* @since 3.18.0
*
* @param {ArrayBuffer} arrayBuffer - The Array Buffer to encode.
* @param {string} [mediaType] - An optional media type, i.e. `audio/ogg` or `image/jpeg`. If included the resulting string will be a data URI.
*
* @return {string} The base64 encoded Array Buffer.
*/
/**
* Merges the properties of one or more source objects into a target object, returning the modified target.
* This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/ jQuery.extend}.
*
* The function accepts a variadic argument list. If the first argument is a boolean `true`, a deep (recursive)
* copy is performed, and the second argument is treated as the target. Otherwise, the first argument is the target
* and all subsequent arguments are source objects. Properties from each source object are copied onto the target in
* order; later sources overwrite earlier ones for the same key. Nested plain objects and arrays are cloned rather
* than referenced during a deep copy, preventing mutation of the originals. `undefined` values on a source are
* never copied to the target.
*
* @function Phaser.Utils.Objects.Extend
* @since 3.0.0
*
* @param {...*} [args] - An optional leading boolean for deep-copy mode, followed by the target object, then one or more source objects whose properties will be merged into the target.
*
* @return {object} The extended object.
*/
/**
* Retrieves a value from an object, or an alternative object, falling to a back-up default value if not found.
*
* The key is a string, which can be split based on the use of the period character.
*
* For example:
*
* ```javascript
* const source = {
* lives: 3,
* render: {
* screen: {
* width: 1024
* }
* }
* }
*
* const lives = GetValue(source, 'lives', 1);
* const width = GetValue(source, 'render.screen.width', 800);
* const height = GetValue(source, 'render.screen.height', 600);
* ```
*
* In the code above, `lives` will be 3 because it's defined at the top level of `source`.
* The `width` value will be 1024 because it can be found inside the `render.screen` object.
* The `height` value will be 600, the default value, because it is missing from the `render.screen` object.
*
* @function Phaser.Utils.Objects.GetValue
* @since 3.0.0
*
* @param {object} source - The primary object to try to retrieve the value from. If not found in here, `altSource` is checked.
* @param {string} key - The name of the property to retrieve from the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) - `banner.hideBanner` would return the value of the `hideBanner` property from the object stored in the `banner` property of the `source` object.
* @param {*} defaultValue - The value to return if the `key` isn't found in the `source` object.
* @param {object} [altSource] - An alternative object to retrieve the value from. If the property exists in `source` then `altSource` will not be used.
*
* @return {*} The value of the requested key.
*/
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
//
// Reset the array, or remove it completely if we have no more listeners.
//
// Alias methods names because people roll like that.
// Expose the prefix.
// Allow `EventEmitter` to be imported as module namespace.
// Expose the module.
// Bottom-left start
// Bottom-right start
// Top-right start
// Create Gradient object.
// Create displacement effect.
// Create DynamicTexture.
// Create Tween.
// Enable filters on target.
// Combine gradient texture with target.
// Set up tidy-up.
// Gradient is only referenced from the tween, and will self-dispose.
// Filters will self-dispose.
// Tween and dynamic texture must be removed if the target is destroyed.
// Return relevant objects.
// Create a shape to use as a mask.
// Remove shape from scene, as we don't need to display it,
// and it will be garbage collected once the Mask is destroyed.
// Apply padding.
// Transform shape to fit to target.
// Optionally, blur shape.
// Apply mask.
// Reposition item.
// Compute relative scales.
// Scale to fit the inside of the region.
// Scale both axes independently to match the region.
// Scale to envelop the outside of the region.
// We keep laying them out horizontally until we've done them all
// We keep laying them out vertically until we've done them all
// We keep laying them out until we hit the column limit
// We've hit the column limit, so return, even if there are items left
// Remove overlaps
// Start to End
// End to Start
// There's nothing to do
// Update the head item to the new x/y coordinates
// Current item
// Get current item x/y, to be passed to the next item in the list
// Set current item to the previous items x/y
// Set current as previous
// Return the final set of coordinates as they're effectively lost from the shift and may be needed
// No duration or frameRate given, use default frameRate of 24fps
// Duration given but no frameRate, so set the frameRate based on duration
// I.e. 12 frames in the animation, duration = 4000 ms
// So frameRate is 12 / (4000 / 1000) = 3 fps
// frameRate given, derive duration from it (even if duration also specified)
// I.e. 15 frames in the animation, frameRate = 30 fps
// So duration is 15 / 30 = 0.5 * 1000 (half a second, or 500ms)
// When is the first update due?
// if frames is a string, we'll get all the frames from the texture manager as if it's a sprite sheet
// Could be an integer or a string
// The actual texture frame
// The previously created animationFrame
// Link them end-to-end, so they loop
// Generate the progress data
// We're at the end of the animation
// Yoyo? (happens before repeat)
// Repeat (happens before complete)
// We're at the start of the animation
// Repeat (happens before complete)
// Remove just this pairing
// Remove everything for animA
// Skip if no name
// Get all the frames for this tag and calculate the total duration in milliseconds.
// Create the animation
// Do we have a String (i.e. from JSON, or an Object?)
// Array of animations, or a single animation?
// Use every frame in the atlas
// No 'frames' array? Then generate one automatically
// -1 because of __BASE, which we don't want in our results
// and -1 because frames are zero based
// Get the animation, first from the local map and, if not found, from the Animation Manager
// And now override the animation values, if set in the config.
// If we've got a nextAnim, move it to the queue
// Must be either an Animation instance, or a PlayAnimationConfig object
// Are we mixing?
// Should give us 9,007,199,254,740,991 safe repeats
// Add any delay the animation itself may have had as well
// We have a delay, but still need to set the frame
// Set this to `true` if there is no delay to include, so it skips the `hasStarted` check in `update`.
// Process one frame advance as standard
// And only do more if we're skipping frames and have time left
// Invert Matrix
// Apply transform to point
// NOOP
// We need a custom viewport for this Camera
// We're turning off a custom viewport for this Camera
// Values are in pixels and not impacted by zooming the Camera
// The center of the camera, in world space, so taking zoom into account
// Basically the pixel value of what it's looking at in the middle of the cam
// Game Object filter camera
// Regular camera
// Apply view transforms in order ITRS.
// We have cameras to create
// Make one
// Create a default camera
// We have cameras to create
// Make one
// Find the first free camera ID we can use
// Direct properties
// Background Color
// Bounds
// So the top-most camera is at the top of the search array
// if camera is at 0x0 and was the size of the previous game size, then we can safely assume it
// should be updated to match the new game size too
// Starting from
// Destination
// Zoom factored version
// Using this ease
// Zooming to
// Camera zoom
// Apply Deceleration
// Check for keys
// Apply to Camera
// Scale Manager - Anything set in here over-rides anything set in the core game config
// DOM Element Container
// Input
// If you do: { banner: false } it won't display any banner at all
// Render Settings - Anything set in here over-rides anything set in the core game config
// On iOS, Capacitor often runs on a capacitor:// protocol, meaning local files are served from capacitor:// rather than file://
// See: https://github.com/photonstorm/phaser/issues/5685
// Old 3.7 array format?
// Default / Missing Images
// Not a custom environment, didn't provide their own canvas and not headless, so determine the renderer:
// Pixel Art mode?
// Does the game config provide its own canvas element to use?
// Does the game config provide some canvas css styles to use?
// Nothing more to do here
// Let the config pick the renderer type, as both are included
// removed by dead control flow
// linear-gradient requires at least two color stops, so duplicate if there's only one
// URL link background color (always transparent to support different browser themes)
// Inject the new string back into the args array
// Wait for the DOM Ready event, then call boot.
// The Texture Manager has to wait on a couple of non-blocking events before it's fully ready.
// So it will emit this internal event when done:
// removed by dead control flow
// Start all the other systems
// Global Managers like Input and Sound update in the prestep
// This is mostly meant for user-land code and plugins
// Update the Scene Manager and all active Scenes
// Our final event before rendering starts
// Run the Pre-render (clearing the canvas, setting background colors, etc)
// The main render loop. Iterates all Scenes and all Cameras in those scenes, rendering to the renderer instance.
// The Post-Render call. Tidies up loose end, takes snapshots, etc.
// The final event before the step repeats. Your last chance to do anything to the canvas before it all starts again.
// Render
// http://www.testufo.com/#test=animation-time-graph
// Pre-populate smoothing array
// Probably super bad start time or browser tab context loss,
// so use the last 'sane' delta value
// Clamp delta to min (in case history has become corrupted somehow)
// Smooth out the delta over the previous X frames
// add the delta to the smoothing array
// adjusts the delta history array index based on the smoothing count
// this stops the array growing beyond the size of deltaSmoothingMax
// Loop the history array, adding the delta values together
// Then divide by the array length to get the average delta
// delta time (time is in ms)
// Math.max because Chrome will sometimes give negative deltas
// Real-world timer advance
// Set as the world delta value (after smoothing, if applied)
// Shift time value over
// Automatically give the window focus unless config says otherwise
// Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog)
// So you can chain graphics calls
// The length of the curve in pixels
// So we'll have 1 spaced point per 'accuracy' pixels
// Get point at relative position in curve according to arc length
// - u [0 .. 1]
// Get sequence of points using getPoint( t )
// If divisions is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead.
// Get sequence of points using getPointAt( u )
// Capping in case of danger
// Cannot overshoot the curve
// binary search for the index with largest value smaller than target u distance
// we could get finer grain at lengths, or use simple interpolation between two points
// determine where we are between the 'before' and 'after' points
// add that fractional amount to t
// Center point
// Radians
// ensures that deltaAngle is 0 .. 2 PI
// Rotate the point about the center of the ellipse.
// vec2s or array
// Override default Curve.arcLengthDivisions
// Line curve is linear, so we can overwrite default getPointAt
// Cannot overshoot the curve
// Override default Curve.draw because this is better than calling getPoints on a line!
// An array of arrays?
// Add a line curve if start and end of lines are not connected
// This will copy a reference to the vectors, which probably isn't sensible
// Assume they're all Vector2s
// Creates a quadratic bezier curve starting at the previous end point and ending at p2, using p1 as a control point
// Calculate where to center the ellipse
// data should be an object matching the Path.toJSON object structure.
// We use cache values if curves and cache array are same length
// Get length of sub-curve
// Push sums into cached array
// To get accurate point with reference to
// entire path distance at time t,
// following has to be done:
// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')
// loop where sum != 0, sum > d , sum+1 <d
// If divisions and stepRate are falsey values (false, null, 0, undefined, etc) then we use the default divisions value.
// ensures no consecutive points are duplicates
// When registering a factory function 'this' refers to the GameObjectFactory context.
// There are several properties available to use:
// this.scene - a reference to the Scene that owns the GameObjectFactory
// this.displayList - a reference to the Display List the Scene owns
// this.updateList - a reference to the Update List the Scene owns
// Hit the key getter, which will in turn emit the events.
// Merge data from another component into this one
// wav Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// Nothing to do here
// Silk gets its own if clause because its ua also contains 'Safari'
// Draw a single pixel
// Get the color values
// Plot them to x2
// Get those values
// Compare and return
// Check Little or Big Endian system.
// @author Matt DesLauriers (@mattdesl)
// Could not determine endianness
// Can't be done on a webgl context
// Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray.
// @author Matt DesLauriers (@mattdesl)
// Older versions of firefox (< 21) apparently claim support but user media does not actually work
// Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it
// is safer to not try and use the fast copy-over method.
// Known not to work
// Keyboard Input?
// Safari 5.1 says it supports fullscreen keyboard, but is lying.
// See https://developer.mozilla.org/en-US/docs/Web/Events/wheel
// DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+
// Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7.
// FF prior to 17. This should probably be scrubbed.
// Because iOS 13 identifies as Mac OS:
// This will NOT detect early generations of Kindle Fire, I think there is no reliable way...
// E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true"
// Windows Phone / Tablet reset
// WebApp mode in iOS
// Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
// Nothing to do
// Apply middle gamma curve.
// Apply interpolation mode.
// CURVED
// SINUSOIDAL or circular
// CURVE_START
// CURVE_END
// Duplicate _matrix into c
// copy _matrix to tempMatrox
// R
// G
// B
// A
// `band` must be a config object.
// Binary tree nodes necessary to hold all bands symmetrically
// Encode start and end as RG.BA
// Encode tree nodes.
// Each tree node is a split point in RG.BA form.
// We are beginning the band encoding region.
// Each band is encoded as colorStart, colorEnd,
// and a composite value of colorMode, interpolationMode, middle.
// Encode colors so they'll appear correct in the texture.
// Encode other data as a composite in RG.BA form.
// Merge in the consts
// The pool into which the canvas elements are placed.
// Automatically apply smoothing(false) to created Canvas elements
// Check to see if the parent is a canvas object
// If we export the called function here, it'll only be invoked once (not every time it's required).
// Browser specific prefix, so not going to change between contexts, only between browsers
// Red to Yellow
// Yellow to Green
// Green to Blue
// Blue to Red
// achromatic by default
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
// The color value has an alpha component
// Nearest hue.
// Strictly increase hue.
// Hopefully an element ID
// Quick test for a HTMLElement
// Fallback, covers an invalid ID and a non HTMLElement object
// DOM Element Container
// Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready
// Screen Orientation API specification
// moz / ms-orientation are strings
// Do this check first, as iOS supports this, but also has an incomplete window.screen implementation
// This may change by device based on "natural" orientation.
// Fallback to the document body. Covers an invalid ID and a non HTMLElement object.
// Use the full window
// Make the next request before the callback, so that timing is maintained
// Ramp is a config. Construct it.
// This should never happen.
// Draw the GameObject to the DynamicTexture.
// `_dynamicTexture` will be generated at render time,
// using the camera of the current context.
// The camera which owns this filter is only the correct camera
// if this filter is being used as an internal filter.
// To eliminate a circular dependency,
// addParallelFilters is defined and injected here.
// Never get smaller, only larger.
// Position
// Flip
// Scale
// Either: { scale: 2 } or { scale: { x: 2, y: 2 }}
// ScrollFactor
// Either: { scrollFactor: 2 } or { scrollFactor: { x: 2, y: 2 }}
// Rotation
// Alpha
// Origin
// Either: { origin: 0.5 } or { origin: { x: 0.5, y: 0.5 }}
// BlendMode
// Visible
// Add to Scene
// { anims: 'key' }
// { anims: {
// key: string
// startFrame: [string|number]
// delay: [float]
// repeat: [integer]
// repeatDelay: [float]
// yoyo: [boolean]
// play: [boolean]
// delayedPlay: [boolean]
// }
// }
// Set the List callbacks
// Initialize RenderSteps mixin.
// Tell the Scene to re-sort the children
// eslint-disable-next-line consistent-this
// Don't repeat if it's already on this list
// This Game Object has already been destroyed
// For when custom objects have overridden `preUpdate` but don't hook into the ADDED_TO_SCENE event:
// Adding to the list multiple times is safe, as it won't add duplicates into the list anyway.
// No duplicates in this list
// Measure the width of the text
// Scan for breach of maxWidth and insert carriage-returns
// Split the text into lines
// Loop through each line
// Loop through each character in a line
// White space or end of line?
// If the current word is too long to fit on a line, wrap it
// Remove trailing word wrap char to keep text length the same
// We're starting a new word, recording the starting index, etc
// Last word
// Adjust all of the character positions based on alignment
// Handle frame trim issues
// Update the bounds - skipped internally if not dirty
// Reset the scale (in case the callback changed it)
// Nothing to render or a space? Then skip to the next glyph
// When registering a factory function 'this' refers to the GameObjectCreator context.
// In case the method above changed it (word wrapping)
// Carriage-return
// local = The BitmapText based on fontSize and 0x0 coords
// global = The BitmapText, taking into account scale and world position
// lines = The BitmapText line data
// Extra data is added here
// Nothing to see, so abort early
// Blend Mode + Scale Mode
// Render bobs
// Optional normal map parameters.
// This method does not use BuildGameObject, because most of the properties
// are not settable on a CaptureFrame, and it doesn't render.
// We can't derive a texture from the canvas.
// Ensure capture drawing context is the same size as the current drawing context.
// Draw current FBO to capture frame.
// Texture.
// Transformed quad in order TL, BL, TR, BR.
// Texture coordinates in X, Y, Width, Height.
// Tint color:
// Tint colors in order TL, BL, TR, BR.
// Render options:
// bitmask flag for GameObject.renderMask
// Treat as if there is only one alpha value for the whole Game Object
// For technical reasons, addParallelFilters is not coded here.
// ParallelFilters has a circular reference to FilterList.
// It registers its own `addParallelFilters` method to fix this,
// which is documented as a part of FilterList.
// Lazy load the camera class to avoid circular dependencies.
// Set up the filter camera to compute an inverse matrix for the object.
// Check whether the object is poorly bounded, and needs to focus on the context.
// Add filters as a render step,
// immediately prior to the main renderWebGL step.
// Ordinarily, we would add the game object to the camera's render list here.
// But because child objects are added to the filter camera's render list,
// we wait for the object to be rendered,
// and then take its filter camera's render list
// and add it to the drawingContext's render list.
// Set the camera roundPixels property to reflect desired rounding.
// This is necessary to avoid blurring from antialiasing
// if coordinates are not integer.
// Apply the game object's parent world transform to the filter camera.
// Get transform.
// Offset origin.
// Set object scrollFactor to default.
// We can't accurately focus the camera on the object if it has a scrollFactor,
// because the camera needs to be set further away,
// going to infinity at scrollFactor 0.
// The scroll factor is baked into the transformMatrix, above.
// Now we have the transform for the game object.
// Render game object to framebuffer.
// Restore scrollFactor.
// Restore camera roundPixels.
// Add the game object's filter camera's render list
// to the drawingContext's render list.
// Handle flip.
// Set the filter camera size to match the object.
// Set the filter camera to match the object.
// Maintain size.
// Default to center.
// Stop automatic focus.
// Sanitize inputs.
// We can use the output object to temporarily store the x/y coords in:
// Instead of doing a check if parent container is
// defined per corner we only do it once.
// eslint-disable-next-line consistent-this
// private + read only
// Override in case they've been specified in the config
// This works, but it's not an ideal way of doing it as the follower jumps position
// The starting point of the path, relative to this follower
// Set the rotation now (in case the tween has a delay on it, etc)
// If delayed, etc then bail out
// Bail out early
// We've changed direction, so don't do a rotate this frame
// Do nothing
// eslint-disable-next-line no-console
// global bitmask flag for GameObject.renderMask (used by Scale)
// value is in degrees
// value is in radians
// Normalize origin
// var r = Math.sqrt(a * a + b * b);
// var s = Math.sqrt(c * c + d * d);
// using old way for old browser compatibility #6965
// a = scale X (1)
// b = shear Y (0)
// c = shear X (0)
// d = scale Y (1)
// Translate
// Rotate and Scale
// No need to loadIdentity because applyITRS overwrites every value anyway
// If Container is SKIP_TEST then set blend mode to be Normal
// If Container doesn't have its own blend mode, then a child can have one
// Set parent values
// Restore original values
// Release any remaining context.
// hash?
// Already got an element? Remove it first
// style can be empty, a string or a plain object
// Add / Override the values we need
// Node handler
// InnerText
// Already got an element? Remove it first
// `camera` is really a DrawingContext object, used in WebGL rendering.
// https://developer.mozilla.org/en-US/docs/Web/CSS/transform
// override this!
// Arguments: time, delta
// Arguments: renderer, drawingContext, calcMatrix, displayList, displayListIndex
// Key is a string, it DOES exist in the Texture Manager AND is a canvas, so draw to it
// Key is a string and doesn't exist in the Texture Manager, so generate and save it
// Key is a Canvas, so draw to it
// var GraphicsCanvasRenderer = function (renderer, src, camera, parentMatrix, renderTargetCtx, allowClip)
// Reset any currently active paths
// +7 because overshoot is the 7th value, not used in Canvas
// Restore the context saved in SetTransform
// Needed for Graphics.generateTexture
// They can pass in any of the following as the first argument:
// 1) A single child
// 2) An array of children
// 3) A config object
// 4) An array of config objects
// Or they can pass in a child, or array of children AND a config object
// config has been set, are the children an array?
// No config, so let's check the children argument
// It's an array of plain config objects
// Children isn't an array. Is it a config object though?
// Pool?
// Can't do anything without at least a key
// Build an array of key frame pairs to loop through
// If a quantity value is set we use that to override the frameQuantity
// Post-creation options (applied only to those items created in this call):
// Got this far? We need to create or bail
// This Game Object had already been destroyed
// Shapes
// Game Object Factories
// Shapes
// WebGL only Game Objects
// --------------
// Append type declarations from List, which won't otherwise be picked up by the type build system.
// --------------
// If Layer is SKIP_TEST then set blend mode to be Normal
// If Layer doesn't have its own blend mode, then a child can have one
// We've got too many lights, so sort by distance from camera and cull those far away
// This isn't ideal because it doesn't factor in the radius of the lights, but it'll do for now
// and is significantly better than we had before!
// The multiplier used to canonicalize an edge into a single numeric
// key. It must exceed the largest vertex index, so we use the vertex
// count.
// The output list, built up below.
// Skip the consumed partner.
// Map from a canonical edge key to the list of triangles which contain
// that edge. Each entry records the partner triangle, the texture page,
// and the vertex opposite the shared edge.
// Each edge of this triangle, with the vertex opposite it.
// Canonical edge keys, with the vertex opposite each edge.
// p = first triangle's opposite corner,
// q, r = shared edge, s = second triangle's opposite corner.
// Render each triangle individually, rather than combining triangles
// into quads. Suitable for dynamic topology which cannot be optimized.
// Resolve render options (lighting, smooth pixel art, etc.) using the
// submitter, then hand the raw vertex and index arrays to the triangle
// batch handler.
// if (width === undefined) { width = 256; }
// if (height === undefined) { height = 256; }
// if (leftWidth === undefined) { leftWidth = 10; }
// if (rightWidth === undefined) { rightWidth = 10; }
// if (topHeight === undefined) { topHeight = 0; }
// if (bottomHeight === undefined) { bottomHeight = 0; }
// If we're using the scale9 data from the frame, override the values from above
// Key positions in normalized coordinates (-0.5 to 0.5)
// Adjust for frame offset
// Incoming values will always be in the range 0-1
// adjust horizontal
// adjust vertical
// Of the 6 vertices, we only need these 2 to define a quad.
// They are the top-left and bottom-right.
// Transformed quad in order TL, BL, TR, BR:
// Texture coordinates in X, Y, Width, Height:
// Tint colors in order TL, BL, TR, BR:
// Render options:
// Populate the r,g,b arrays
// in hex format 0xff0000
// Reset it back again
// Number
// Custom Callback (onEmit only)
// Custom onEmit and/or onUpdate callbacks
// Random Array
// Stepped start/end
// Eased start/end
// min/max (random float or int)
// Random object (random integer)
// Interpolation
// `moveToX` and `moveToY` are null by default
// Random Array
// Custom Callback
// Stepped start/end
// Eased start/end
// min/max
// Random object
// Custom onEmit onUpdate
// Interpolation
// Custom Callback (onEmit only)
// min/max (random float or int)
// Random object (random integer)
// Custom onEmit and/or onUpdate callbacks
// Add step to the current value
// Down
// Updates particle.x and particle.y during this call
// EmitterOp is stepped but x was forced (follower?) so use it
// EmitterOp is stepped but y was forced (follower?) so use it
// Check we didn't spawn in the middle of a DeathZone
// Particle is dead via `Particle.kill` method, or being held
// How far along in life is this particle? (t = 0 to 1)
// No need to go any further, particle has been killed
// Integrate back in to the position
// Apply any additional processors (these can update velocity and/or position)
// Only update properties from their current state if they exist in the given config
// Special 'speed' override
// If you specify speedX, speedY or moveTo then it changes the emitter from radial to a point emitter
// Special 'scale' override
// special handlers
// If you specify speedX and Y then it changes the emitter from radial to a point emitter
// Where source = Geom like Circle, or a Path or Curve
// emitZone: { type: 'random', source: X }
// emitZone: { type: 'edge', source: X, quantity: 32, [stepRate=0], [yoyo=false], [seamless=true], [total=1] }
// Clear any previously set callback
// Sends the Particle and the Emitter
// Scale the delta
// Any particle processors?
// update returns `true` if the particle is now dead (lifeCurrent <= 0)
// Move dead particles to the dead array
// Remove from particles array
// Add to dead array
// Callback
// Emits the 'quantity' number of particles
// counter = frequency - remainder from previous delta
// Duration or stopAfter set?
// elapsed
// Multiply by the particle matrix, store result in calcMatrix
// Optional normal map overrides
// Remove ends?
// Adjust counter if we now have less points than before
// read only:
// Top / Bottom alpha pair
// If there are exactly the same number of alphas as points, we'll combine the alphas
// If there are exactly the same number of colors as points, we'll combine the colors
// Generate an array based on the points
// updateVertices during next render
// Get smooth pixel art option.
// Render at least once, so our texture isn't blank on the first update
// NOOP
// This is very similar to the FillPath RenderNode, but it already
// has access to the Earcut indexes, so it doesn't need to calculate them.
// Transform the point.
// Prevent Shape stroke from being cut off in filters.
// Don't add the last point to open paths.
// Duplicate point, skip it
// Restore the context saved in SetTransform
// Update the bounds in case the underlying data has changed
// Note use of _curveBounds, unlike other path-based Shape objects.
// Work out the grid size
// Render remaining outer strokes.
// Work out the grid size
// Render remaining outer strokes.
// Top Face
// Left Face
// Right Face
// Top Face
// Left Face
// Right Face
// Limit max radius to half the smallest dimension
// Ensure minimum smoothness for small radii while preventing excessive tessellation
// Create points going clockwise from top-left
// Top-left corner
// Top edge and top-right corner
// Right edge and bottom-right corner
// Bottom edge and bottom-left corner
// Left edge (connects back to first point)
// Limit radius to half of the smaller dimension
// Fall back to normal rectangle if radius is 0
// Start at top-left, after the corner
// Top edge and top-right corner
// Right edge and bottom-right corner
// Bottom edge and bottom-left corner
// Left edge and top-left corner
// So origin 0.5 = the center of the star
// Sprite specific config options:
// // Elastic requires extra parameters, so we skip it.
// Elastic: 80,
// 'Elastic.easeOut': 80,
// 'Elastic.easeIn': 81,
// 'Elastic.easeInOut': 82,
// Stepped could require extra parameters, but we assume just 2.
// Add enabled animations.
// Animation frames will start after the texture frames.
// This is a Phaser.Animations.Animation class.
// Add frame indexing data.
// Store animation.
// Get the frame data.
// Update the frame data indices.
// Append frames from animations.
// Generate a Uint8Array with the frame data.
// animFrame comes from a SetAnimation object.
// animFrame is an AnimationFrame object.
// Position
// Size
// Pivot offset
// Multiplied by the size to convert to pixels.
// Offset by 32768 to effectively store as a 16-bit signed integer.
// Create or update a texture with the frame data.
// Copy data from the old buffer to the new buffer.
// Use frame animation.
// Bad data; fall back to first animation.
// Use single frame.
// Determine frame or animation values.
// Get name from frame index.
// Get name from animation index.
// Mark segments for update.
// Update layer properties.
// Move the data after the insertion point.
// Target
// Source
// End
// Insert members.
// Enable the chosen animation type.
// We encode the factor as a fraction, so we can't encode 1.
// The shader decodes 0 as 1 if Gravity is used.
// This means a value of 0 will be wrongly interpreted, but why set 0?
// Map gravityFactor range [-1,1] to [0,1].
// Encode values into amplitude.
// Normalize delay.
// We double the range of the delay to allow for yoyo.
// Add an integer to encode the type.
// Encode yoyo in the sign of duration, which must be positive.
// Encode loop in the sign of delay, which must be positive.
// Negate ease after duration, so duration has the correct sign.
// Check for Gravity mode.
// TODO: Destroy the Submitter RenderNode.
// Blend Mode
// Visible
// The Stamp inherits WebGL rendering properties from the Image class.
// Add the stencil render step as the first render step.
// If the tree of child game objects has any stencil children,
// activate forced composite mode on `gameObject`.
// Set up the drawing context to render to the stencil buffer.
// Invert the stencil area if needed.
// Invert the stencil operation.
// Render the children.
// Cache the stencil options.
// Edit the stencil properties.
// Get the parent transform of the Stencil, not the StencilReference.
// Render the stencil.
// Restore the stencil options.
// Text Width
// Adjust for wrapped text
// Text Height
// Adjust for line spacing
// ascent. scan from top to bottom until we find a non red pixel
// descent. scan from bottom to top until we find a non red pixel
// If resolution wasn't set, force it to 1
// Create a Texture for this Text object
// Set the context to be the CanvasTexture context
// Get the frame
// Set the resolution
// Clear the default 1x1 glTexture, as we override it later
// Here is where the crazy starts.
//
// Due to browser implementation issues, you cannot fillText BiDi text to a canvas
// that is not part of the DOM. It just completely ignores the direction property.
// Experimental atm, but one day ...
// Add it to the DOM, but hidden within the parent canvas.
// And finally we set the x origin
// Condense consecutive spaces and split into lines
// Trim whitespace
// If entire line is less than wordWrapWidth append the entire line and exit early
// Otherwise, calculate new lines
// Split into words
// Break word
// Shave off letters from word until it's small enough
// If wordWrapWidth is too small for even a single letter, shame user
// failure with a fatal error
// Replace current word in array with remainder
// Append first piece to output
// If existing word length is 0, don't include it
// Collapse rest of sentence and remove any trailing white space
// Prepend remainder to next line
// Append word with space to output
// Append processed line to output
// Trim the end of the string
// Skip printing the newline if it's the first word of the line that is greater
// than the word wrap width.
// If they specify x and/or y this applies to all
// Split text into lines
// Resizing the canvas changes the size of the texture source.
// Because this is a dedicated texture for this Text object,
// we know this is a simple resize.
// Because resizing the canvas resets the context
// Apply padding
// Draw text line by line
// To justify text line its width must be no less than 85% of defined width
// Apply stroke to the whole line only if there's no custom letter spacing
// Looping fillText could be an expensive operation, we should ignore it if it is not needed
// Draw text letter by letter
// removed by dead control flow
// Extra Text data is added here
// style Object = {
// font: [ 'font', '16px Courier' ],
// backgroundColor: [ 'backgroundColor', null ],
// fill: [ 'fill', '#fff' ],
// stroke: [ 'stroke', '#fff' ],
// strokeThickness: [ 'strokeThickness', 0 ],
// shadowOffsetX: [ 'shadow.offsetX', 0 ],
// shadowOffsetY: [ 'shadow.offsetY', 0 ],
// shadowColor: [ 'shadow.color', '#000' ],
// shadowBlur: [ 'shadow.blur', 0 ],
// shadowStroke: [ 'shadow.stroke', false ],
// shadowFill: [ 'shadow.fill', false ],
// align: [ 'align', 'left' ],
// maxLines: [ 'maxLines', 0 ],
// fixedWidth: [ 'fixedWidth', false ],
// fixedHeight: [ 'fixedHeight', false ],
// rtl: [ 'rtl', false ]
// }
// Padding
// { padding: 2 }
// { padding: { x: , y: }}
// { padding: { left: , top: }}
// { padding: { left: , right: , top: , bottom: }}
// Text specific config options:
// Key: [ Object Key, Default Value ]
// Set to defaults + user style
// Callback & scope should be set without processing the values
// Allow for 'font' override
// Allow for 'fill' to be used in place of 'color'
// Provide optional TextMetrics in the style object to avoid the canvas look-up / scanning
// Doing this is reset if you then change the font of this TextStyle after creation
// Reset the stroke to zero (disabling it)
// Draw the texture to our fillCanvas
// Re-use the existing video element
// First frame of a new video
// Re-use the existing texture
// Resize base frame
// We can reset these each time play is called, even if the video hasn't started yet
// But we go no further if play has already been called
// Set these _after_ calling `video.play` or they don't fire
// (really useful, thanks browsers!)
// Old-school fallback here for pre-2019 browsers
// The stop method has been called but the Promise has resolved
// after this, so we need to just abort.
// Mute will be set based on the global mute state of the Sound Manager (if there is one)
// Check if x/y are within the bounds first
// If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead.
// units squared
// Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
// Add co-linear check
// Make sure there is not a division by zero - this also indicates that the lines are parallel.
// If numA and numB were both equal to zero the lines would be on top of each other (coincidental).
// This check is not done because it is not necessary for this implementation (the parallel check accounts for this).
// Intersects?
// Temp calculation segment
// Temp vec3
// Reset our vec3s
// Reset our vec4s
// +- 0.00001 rads to catch lines behind segment corners
// project lc onto d, resulting in vector p
// len2 of p
// This is based off an explanation and expanded math presented by Paul Bourke:
// See http://paulbourke.net/geometry/pointlineplane/
// Check that none of the lines are length zero
// Lines are parallel
// Calculate the intermediate fractional point that the lines potentially intersect.
// The fractional point will be between 0 and 1 inclusive if the lines intersect.
// If the fractional calculation is larger than 1 or smaller than 0 the lines would need to be longer to intersect.
// If the start or end of the line is inside the rect then we assume
// collision, as rects are solid for our use-case.
// Left edge
// Right edge
// Top edge
// Bottom edge
// Assume line thickness is circular
// Outside line1
// On the line segment
// Outside line2
// First the cheapest ones:
// Are any of the triangle points within the rectangle?
// Cheap tests over, now to see if any of the lines intersect ...
// None of the lines intersect, so are any rectangle points within the triangle?
// If the Triangle contains either the start or end point of the line, it intersects
// Now check the line against each line of the Triangle
// Now check the lines against each line of TriangleB
// Nope, so check to see if any of the points of triangleA are within triangleB
// Finally check to see if any of the points of triangleB are within triangleA
// Always include the end of the line
// Remove collinear parts
// Store the new results here
// Top and tail
// Checks whether the x and y coordinates are contained within this polygon.
// Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva
// Earcut 2.2.4 (July 5th 2022)
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
// minX, minY and invSize are later used to transform coords into integers for z-order calculation
// create a circular doubly linked list from polygon points in the specified winding order
// eliminate colinear or duplicate points
// main ear slicing loop which triangulates a polygon (given as a linked list)
// interlink polygon nodes in z-order
// iterate through ears, slicing them one by one
// cut off the triangle
// skipping the next vertex leads to less sliver triangles
// if we looped through the whole remaining polygon and can't find any more ears
// try filtering points and slicing again
// if this didn't work, try curing all small self-intersections locally
// as a last resort, try splitting the remaining polygon into two
// check whether a polygon node forms a valid ear with adjacent nodes
// now make sure we don't have other points inside the potential ear
// triangle bbox; min & max are calculated like this for speed
// z-order range for the current triangle bbox;
// look for points inside the triangle in both directions
// look for remaining points in decreasing z-order
// look for remaining points in increasing z-order
// go through all polygon nodes and cure small local self-intersections
// remove two nodes involved
// try splitting polygon into two and triangulate them independently
// look for a valid diagonal that divides the polygon into two
// split the polygon in two by the diagonal
// filter colinear points around the cuts
// run earcut on each half
// link every hole into the outer loop, producing a single-ring polygon without holes
// process holes from left to right
// find a bridge between vertices that connects hole with an outer ring and and link it
// filter collinear points around the cuts
// David Eberly's algorithm for finding a bridge between hole and outer polygon
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
// whether sector in vertex m contains sector in vertex p in the same coordinates
// interlink polygon nodes in z-order
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
// z-order of a point given coords and inverse of the longer side of data bbox
// coords are transformed into non-negative 15-bit integer range
// find the leftmost node of a polygon ring
// check if a point lies within a convex triangle
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
// signed area of a triangle
// check if two points are equal
// check if two segments intersect
// for collinear points p, q, r, check if point q lies on segment pr
// check if a polygon diagonal intersects any polygon segments
// check if a polygon diagonal is locally inside the polygon
// check if the middle point of a polygon diagonal is inside the polygon
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
// create a node and optionally link it with previous one (in a circular doubly linked list)
// vertex index in coordinates array
// vertex coordinates
// previous and next vertex nodes in a polygon ring
// z-order curve value
// previous and next nodes in z-order
// indicates whether this is a steiner point
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
// Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ]
// The points argument is an array, so iterate through it
// Volume check (if rectB volume > rectA then rectA cannot contain it)
// Taller than Wide
// Wider than Tall
// Face 3
// Face 4
// Face 1
// Face 2
// Bail out
// If step is a falsey value (false, null, 0, undefined, etc) then we calculate
// it based on the quantity instead, otherwise we always use the step value
// Loop across each face of the rectangle
// Top face
// Right face
// Bottom face
// Left face
// Pick a random quadrant
// The quadrants don't extend the full widths / heights of the outer rect to give
// us a better uniformed distribution, otherwise you get clumping in the corners where
// the 4 quads would overlap
// Cache vars so we can use one of the input rects as the output rect
// The 2D area of a triangle. The area value is always non-negative.
// Builds a right triangle, with one 90 degree angle and two acute angles
// The x/y is the coordinate of the 90 degree angle (and will map to x1/y1 in the resulting Triangle)
// w/h can be positive or negative and represent the length of each side
// 90 degree angle
// Get the center of the triangle
// Difference
// A
// B
// C
// If the points of the triangle are collinear, then just find the
// extremes and use the midpoint as the center of the circumcircle.
// http://www.blackpawn.com/texts/pointinpoly/
// Compute barycentric coordinates
// Which line is it on?
// Line 1
// Line 3
// Line 2
// Which line is it on?
// Line 1
// Line 3
// Line 2
// The three angle bisectors of a triangle meet in one point called the incenter.
// It is the center of the incircle, the circle inscribed in the triangle.
// Basis vectors
// Random point within the unit square
// Point outside the triangle? Remap it.
// Has the dev specified their own shape, or is this bound to the texture size?
// 0 = Not being dragged
// 1 = Being checked for dragging
// 2 = Being dragged
// If the Scene returns true, it means it captured some input that no other Scene should get, so we bail out
// If the Scene returns true, or called stopPropagation, it means it captured some input that no other Scene should get, so we bail out
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
// For touch end its a list of the touch points that have been removed from the surface
// https://developer.mozilla.org/en-US/docs/DOM/TouchList
// Stores the world point inside of tempPoint
// Checks if the Game Object can receive input (isn't being ignored by the camera, invisible, etc)
// and also checks all of its parents, if any
// Normalize the origin
// Normalize the origin
// Store previous position
// Translate coordinates
// Set immediately
// Apply smoothing
// Inject the available input plugins into this class
// Registered input plugins listen for this
// Populate the pointer drag states
// Registered input plugins listen for this
// Quick bail
// Delete old gameObjects
// Clear the removal list
// Move pendingInsertion to list (also clears pendingInsertion at the same time)
// The plugins should update every frame, regardless if there has been
// any DOM input events or not (such as the Gamepad and Keyboard)
// We can leave now if we've already updated once this frame via the immediate DOM event handlers
// No point going any further if there aren't any interactive objects
// Discard timer diff, we're ready to poll again
// Not enough time has elapsed since the last poll, so abort now
// We got this far? Then we should poll for movement
// Always reset this array
// _temp contains a hit tested and camera culled list of IO objects
// Only the top-most one counts now, so safely ignore the rest
// We interacted with an event in this Scene, so block any Scenes below us from doing the same this frame
// If GameObject.input already cleared from higher class
// Clear from _drag and _over
// If it already has an InteractiveObject then just enable it and return
// Create an InteractiveObject and enable it
// Get a list of all objects that can be seen by the camera below the pointer in the scene and store in 'over' array.
// All objects in this array are input enabled, as checked by the hitTest method, so we don't need to check later on as well.
// Filter out the drop zones
// If we got this far then there were no Game Objects below the pointer, but it was still over
// a camera, so set that the top-most one into the pointer
// Go through all objects the pointer was over and fire their events / callbacks
// 1) GAMEOBJECT_POINTER_DOWN
// They cancelled the whole event, it can't go any further
// Check that the game object wasn't input disabled or destroyed as a result of its input event
// 2) GAMEOBJECT_DOWN
// They cancelled the whole event, it can't go any further
// If they pressed down outside the canvas, dispatch that event.
// 3) POINTER_DOWN
// 4) POINTER_DOWN_OUTSIDE
// It has moved far enough to be considered a drag
// It has been held down long enough to be considered a drag
// 3 = Pointer meets criteria and is freshly down, notify the draglist
// There are no draggable items, no over items or the pointer isn't down, so let's not even bother going further
// 1 = Primary button down and objects below, so collect a draglist
// Get draggable objects, sort them, pick the top (or all) and store them somewhere
// draglist now contains all potential candidates for dragging
// No drag criteria, so snap immediately to mode 3
// Check the distance / time on the next event
// 2 = Pointer being checked if meets drag criteria
// 4 = Pointer actively dragging the draglist and has moved
// If this GO has a target then let's check it
// Got a target, are we still over it?
// We're still over it, and it's still the top of the display list, phew ...
// Still over it but it's no longer top of the display list (targets must always be at the top)
// Nope, we've moved on (or the target has!), leave the old target
// Anything new to replace it?
// Yup!
// Nope
// 5 = Pointer was actively dragging but has been released, notify draglist
// And finally the dragend event
// Check that the game object wasn't input disabled or destroyed as a result of its input event
// They cancelled the whole event, it can't go any further
// Then sort it into display list order
// Call onOut for everything in the previouslyOver array
// Go through all objects the pointer was previously over, and see if it still is.
// Splits the previouslyOver array into two parts: justOut and stillOver
// Not in the currentlyOver array, so must be outside of this object now
// In the currentlyOver array
// Go through all objects the pointer is currently over (the hit test results)
// and if not in the previouslyOver array we know it's a new entry, so add to justOver
// Is this newly over?
// By this point the arrays are filled, so now we can process what happened...
// Process the Just Out objects
// Call onOut for everything in the justOut array
// Reset cursor before we emit the event, in case they want to change it during the event
// Process the Just Over objects
// Call onOver for everything in the justOver array
// Set cursor before we emit the event, in case they want to change it during the event
// Add the contents of justOver to the previously over array
// 1) GAMEOBJECT_POINTER_UP
// 2) GAMEOBJECT_UP
// If they released outside the canvas, but pressed down inside it, we'll still dispatch the event.
// Config object?
// Still no hitArea or callback?
// This will remove it from both the display list and update list
// Quick bail out when neither child has a container
// Quick bail out when both children have the same container
// Quick bail out when childA is a child of childB
// Container index check
// Go to the next level down
// Non-matching parents, so return
// Technically this shouldn't happen, but ...
// eslint-disable-next-line no-unreachable
// Contains the plugins that Phaser uses globally and locally.
// These are the source objects, not instantiated.
// Stores the world point inside of tempPoint
// Nothing to do here
// Moving towards our goal ...
// Sets the local x/y properties
// 0: Main button pressed, usually the left button or the un-initialized state
// No more buttons are still down
// Override button settings on macOS
// Multiple DOM events may occur within one frame, but only one Phaser event will fire
// https://w3c.github.io/gamepad/#remapping
// Sync the button values
// Sync the axis values
// Do nothing if event already handled
// FF also supports gamepadbuttondown, gamepadbuttonup and gamepadaxismove but
// nothing else does, and we can get those values via the gamepads anyway, so we will
// until more browsers support this
// Finally, listen for an update event from the Input Plugin
// Because sometimes they're null (yes, really)
// A new Gamepad, not currently stored locally
// A new Gamepad with a different vendor string, but it has got the same index as an old one
// If neither of these, it's a pad we've already got, so update it
// Process the event queue, dispatching all of the events that have stored up
// Override the default functions (it's too late for the browser to use them anyway, so we may as well)
// Event allowed to flow across all handlers in this Scene, and any other Scene in the Scene list
// Won't reach any more local (Scene level) handlers
// Won't reach any more handlers in any Scene further down the Scene list
// This event has been stopped from broadcasting to any other Scene, so abort.
// Duplicate event bailout
// On some systems, the exact same event will fire multiple times. This prevents it.
// Key specific callback first
// Reset the cancel state for other Scenes to use
// Because it's a sparsely populated array
// Can't have a zero or single length combo (string or array based)
// if 'keys' is a string we need to get the keycode of each character in it
// Key was correct
// We have to check to see if the delay between
// the new key and the old one was too long (if enabled)
// Check if they pressed it in time or not
// We don't check the time for the first key pressed, so just advance it
// Wrong key was pressed
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
// Only process the event if the target isn't the canvas
// https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
// https://patrickhlauke.github.io/touch/tests/results/
// https://www.html5rocks.com/en/mobile/touch/
// Can happen for example in a JSONFile if they've provided a JSON object instead of a URL
// Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
// Inject the available filetypes into the Loader
// Does the file already exist in the cache or texture manager?
// Or will it conflict with a file already in the queue or inflight?
// if no packKey provided we'll add everything to the queue
// Store the loader settings in case this pack replaces them
// Here we go ...
// Any meta data to process?
// Reset the loader settings
// Nothing to remove.
// If the file doesn't have its own crossOrigin set, we'll use the Loaders (which is undefined by default)
// Tells the Set iterator to abort
// Has the game been destroyed during load? If so, bail out now.
// This file has failed, so move it to the failed Set
// If we got here then all files the link file needs are ready to add to the cache
// If we got here, then the file processed, so let it add itself to its cache
// Remove it from the queue
// Nothing left to do?
// Call 'destroy' on each file ready for deletion
// Clean out any potential 'null' or 'undefined' file entries
// Link the files
// eslint-disable-next-line no-console
// After a successful request, the xhr.response property will contain the requested data as a DOMString, ArrayBuffer, Blob, or Document (depending on what was set for responseType.)
// This is the only standard method, the ones above are browser additions (maybe not universal?)
// xhr.onreadystatechange
// Before sending a request, set the xhr.responseType to "text",
// "arraybuffer", "blob", or "document", depending on your data needs.
// Note, setting xhr.responseType = '' (or omitting) will default the response to "text".
// Ignored by the Loader, only used by File.
// credentials
// timeout in ms (0 = no timeout)
// setRequestHeader
// overrideMimeType
// withCredentials
// url can either be a string, in which case it is treated like a proper url, or an object, in which case it is treated as a ready-made JS Object
// dataKey allows you to pluck a specific object out of the JSON and put just that into the cache, rather than the whole thing
// We need to hook into this event:
// But the rest is the same as a normal JSON file
// Supports an Object file definition in the key argument
// Or an array of objects in the key argument
// Or a single entry where all arguments have been defined
// Image has a normal map
// Supports an Object file definition in the key argument
// URL is an object created by AudioFile.findAudioURL
// interesting read https://github.com/WebAudio/web-audio-api/issues/1305
// eslint-disable-next-line no-console
// url may be inside key, which may be an object
// https://developers.google.com/web/updates/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs
// var stream = GetFastValue(config, 'stream', false);
// Sounds are disabled, so skip loading audio
// If it's an array it has to be an array of Objects, so we get everything out of the 'key' object
// No url? then we're going to do a json load and parse it from that
// Inspect the data for the files to now load
// "image": "texture-packer-multi-atlas-0.png",
// "normalMap": "texture-packer-multi-atlas-0_n.png",
// Reset the loader settings
// Check block size.
// Check texture compression.
// Now we need to find out which json entry this mapped to
// New properties specific to this class
// This is super-dangerous but works. Race condition potential high.
// Is there another way?
// Do we have a normal map to load as well?
// Check if we have a linked normal map
// We do, but has it loaded?
// linkFile.data = Image
// this.data = Normal Map
// linkFile.data = Normal Map
// this.data = Image
// Nothing to do here, we'll use the linkFile `addToCache` call
// to process this pair
// A JSON object has been provided (instead of a URL), so we'll use it directly as the File.data. No need to load it.
// Now we need to find out which json entry this mapped to
// Override the default onProcess function
// Internal File class used by PCTAtlasFile to load and decode a `.pct` data file into its
// structured representation. Unlike the generic TextFile this parses the loaded text as a
// Phaser Compact Texture Atlas and stores the decoded object (containing `pages`, `folders`,
// and `frames`) as `this.data`, which is later written to the atlas cache by the parent
// MultiFile. This type is not registered with the Loader and is not part of the public API.
// Called automatically by Loader.nextFile. Decodes the loaded PCT text into its structured
// object form via Phaser.Textures.Parsers.PCTDecode and stores it as this.data.
// "filename": "atlas_0.png"
// Build an image array in the correct page order by matching each
// loaded ImageFile key against the PCT{idx}_{filename} pattern used
// when the inner ImageFiles were created.
// Store the decoded PCT data in the atlas cache so it can be retrieved later
// Add the multi-source texture and its frames to the Texture Manager
// Let's pass the pack file data over to the Loader ...
// If the url variable refers to a class, add the plugin directly
// Plugin added via a js file
// Install into the current Scene Systems and Scene
// If there's no viewBox attribute, set one
// Get the w/h from the viewbox
// Safari 8 re-try
// Stops rollup from freaking out during build
// Both files have loaded
// We set these, but we don't actually load anything (the Video Game Object does that)
// Upper 3x3 of matrix is un-scaled rotation matrix
// PCG with float inputs
// PCG
// Trig: same as shader hash function.
// Combine vector.
// Expand floating-point numbers into the 32-bit range.
// Perform all math as unsigned 32-bit using >>>.
// Normalize vector to unit grid.
// Generate neighbourhood in range -1,1 on relevant axes.
// Support 1D input.
// Match the config names used by the shaders and typedefs.
// Optional warping pass, mirroring the shader behaviour.
// 2D warp uses two offset coordinates.
// 3D warp uses three offset coordinates.
// The noise functions are derived from
// https://github.com/stegu/psrdnoise/,
// specifically psrdnoise2.glsl and
// psrdnoise3.glsl, version 2021-12-02
// Copyright (c) 2021 Stefan Gustavson and Ian McEwan
// (stefan.gustavson@liu.se, ijm567@gmail.com)
// Published under the MIT license, see:
// https://opensource.org/licenses/MIT
// Temporary module-scope containers for composite data types
// For vec3's
// 2. Transform input point to find simplex "base" i0.
// x is [ x, y ], period is [ x, y ]
// 3. Enumerate simplex corners and transform back.
// 4. Compute distances to corners before we wrap them.
// 5, 6. wrap to period and adjust i0, i1, i2 accordingly.
// Custom: Seed the noise.
// 7. Compute the hash for each of the simplex corners.
// 8, 9a. Generate the gradients with an optional rotation.
// 10. Compute radial falloff.
// 11. Linear ramp along gradient (by a scalar product)
// 12, 13. Multiply and sum up noise terms.
// Scale the noise value to [-1,1] (empirical factor).
// --- 3D psrdnoise implementation (port of psrdnoise3.glsl) ---
// Temporary containers to avoid allocations.
// out = mod(((im * 34.0) + 10.0) * im, 289.0);
// 2. Transform to simplex space and find simplex "base" i0.
// uvw = M * x, where M is the 3x3 matrix in the GLSL code.
// g_ = step(f0.xyx, f0.yzz);
// v* = Mi * i*, where Mi is the inverse matrix.
// Mi rows: [-0.5, 0.5, 0.5]
// [ 0.5, -0.5, 0.5]
// [ 0.5, 0.5, -0.5]
// 4. Compute distances to corners before we wrap.
// 5, 6. Wrap to periods and update i0, i1, i2, i3 accordingly.
// Recompute lattice coordinates from wrapped positions.
// i* = floor(M * v* + 0.5);
// 7. Compute hash for each of the four corners.
// hash = permute(permute(permute(vec4(i0.z, i1.z, i2.z, i3.z)) + vec4(i0.y, i1.y, i2.y, i3.y)) + vec4(i0.x, i1.x, i2.x, i3.x));
// 8. Compute rotating gradients using the "well-behaved" method.
// 11. Linear ramps along gradients (by scalar product)
// 12, 13. Multiply and sum up the four noise terms.
// Scale noise value to range [-1,1] (empirical factor).
// Use abstract equality == for "is number" test
// eslint-disable-next-line eqeqeq
// Use strict equality === for "is number" test
// Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji
// and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl
// Assume Matrix3 with val:
// Default to identity
// Calculate the determinant
// Assume Matrix4 with val:
// Calculate the determinant
// Cache only the current line of the second matrix
// Based on http://www.gamedev.net/reference/articles/article1199.asp
// Construct the elements of the rotation matrix
// Perform rotation-specific matrix multiplication
// Perform axis-specific matrix multiplication
// Quaternion math
// Avoid division by zero
// eye and target are in the same position
// up and z are parallel
// Rotate Z
// Rotate X
// Rotate Y
// Translate
// a30 = cy * x + 0 * y + sy * z;
// Some shared 'private' arrays
// benchmarks: http://jsperf.com/quaternion-slerp-implementations
// calc cosine
// adjust signs (if necessary)
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
// calculate coefficients
// standard case (slerp)
// calculate final values
// benchmarks:
// http://jsperf.com/typed-array-access-speed
// http://jsperf.com/conversion-of-3x3-matrix-to-quaternion
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
// |w| > 1/2, may as well choose w > 1/2
// |w| <= 1/2
// This isn't quite as clean without array access
// Set the quaternion to our axis angle
// Create a rotation matrix from the axis angle
// Multiply our vector by the rotation matrix
// "Opposite" of truncate.
// Rotate and Scale
// Invert
// computes the angle in radians with respect to the positive x-axis
// benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
// calculate quat * vec
// calculate result * inverse quat
// EaseMap
// Collections of functions
// Expose the RNG Class
// Single functions
// Vector classes
// Export it
// https://github.com/mrdoob/three.js/blob/master/src/extras/core/Interpolations.js
// Always reset to default seed
// Apply any seeds
// 2^32
// 2^-53
// eslint-disable-next-line no-empty
// We know how many pixels we need to move, but how fast?
// Already destroyed
// Container?
// Store and reset collision flags
// Now the update will throw collision checks at the Body
// And finally we'll integrate the new position back to the Sprite in postUpdate
// We need a valid Game Object to continue
// Disconnect the current Game Object
// Remove the body from the world, but don't disable the Game Object
// This will remove the body from the tree, if it's in there and add the new one in
// Check if x/y are within the bounds first
// Only draw the sides where checkCollision is true, similar to debugger in layer
// They overlap but neither of them are moving
// Body1 is moving right and / or Body2 is moving left
// Body1 is moving left and/or Body2 is moving right
// Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is
// Body1 is moving down and/or Body2 is moving up
// Body1 is moving up and/or Body2 is moving down
// Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is
// children is a plain object, so swizzle them:
// children is an array of plain objects (i.e., configs)
// config is not defined and children is not a plain object nor an array of plain objects
// negative delta = left, positive delta = right (inc. gravity)
// Body1 is moving right and Body2 is blocked from going right any further
// Body1 is moving left and Body2 is blocked from going left any further
// Body2 is moving right and Body1 is blocked from going right any further
// Body2 is moving left and Body1 is blocked from going left any further
// Body1 hits Body2 on the right hand side
// Body2 hits Body1 on the right hand side
// Body1 hits Body2 on the left hand side
// Body2 hits Body1 on the left hand side
// Both pushable, or both moving at the same time, so equal rebound
// body1MovingLeft && body2OnLeft
// body2MovingRight && body2OnLeft
// body2MovingLeft && body1OnLeft
// body1MovingRight && body1OnLeft
// Body1 pushable, Body2 not
// Body2 pushable, Body1 not
// Neither body is pushable, so base it on movement
// Body2 moving same direction as Body1
// Body1 moving same direction as Body2
// But Body2 cannot go anywhere either, so we cancel out velocity
// Separation happened in the block check
// This is special case code that handles things like vertically moving platforms you can ride
// But Body1 cannot go anywhere either, so we cancel out velocity
// negative delta = up, positive delta = down (inc. gravity)
// Body1 is moving down and Body2 is blocked from going down any further
// Body1 is moving up and Body2 is blocked from going up any further
// Body2 is moving down and Body1 is blocked from going down any further
// Body2 is moving up and Body1 is blocked from going up any further
// Body1 hits Body2 on the bottom side
// Body2 hits Body1 on the bottom side
// Body1 hits Body2 on the top side
// Body2 hits Body1 on the top side
// body1MovingUp && body2OnTop
// body2MovingDown && body2OnTop
// body2MovingUp && body1OnTop
// body1MovingDown && body1OnTop
// This is special case code that handles things like horizontally moving platforms you can ride
// Can't separate two immovable bodies, or a body with its own custom separation logic
// return true if there was some overlap, otherwise false
// If we got this far then there WAS overlap, and separation is complete, so return true
// If true this Body will dispatch events
// Causes havoc otherwise
// children is an array of plain objects
// Handle Groups nested inside of Groups
// Update all active bodies
// Will a step happen this frame?
// We know that a step will happen this frame, so let's bundle it all together to save branching and iteration costs
// Optionally populate our dynamic collision tree
// Process any colliders
// Process any additional steps this frame
// Update all active bodies
// Optionally populate our dynamic collision tree
// Process any colliders
// We don't need to postUpdate if there wasn't a step this frame
// Damping based deceleration
// Linear deceleration
// They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
// Circle vs. Circle, or Circle vs. Rect
// We got a satisfactory result from the separateCircle method
// Further processing required
// Do we separate on x first or y first or both?
// No separation but we need to calculate overlapX, overlapY, etc.
// Are they still intersecting? Let's do the other axis then
// Set the AABB overlap, blocked and touching values into the bodies (we don't use the return values here)
// If a collision occurs in the corner points of the rectangle
// then the bodies behave like circles
// We know the AABBs already intersect before we enter this method
// Now we know the rect vs circle overlaps, or two circles do
// Can't separate (in this method):
// Two immovable bodies
// A body with its own custom separation logic
// A circle vs. a rect with a face-on collision
// Let SeparateX / SeparateY handle this
// If we get this far we either have circle vs. circle
// or circle vs. rect with corner collision
// Circle vs. Rect
// We'll only move the circle (if we can) and let
// the runSeparation handle the rectangle
// Let SeparateX / SeparateY handle this further
// Rect vs. Rect
// Circle vs. Circle
// Circle vs. Rect
// Rect vs. Circle
// Neither of them are arrays - do this first as it's the most common use-case
// Object 2 is an Array
// Object 1 is an Array
// Special case for array vs. self
// They're both arrays
// Collide Group with Self
// Only collide valid objects
// If neither of the objects are set then bail out
// SPRITE
// GROUPS
// TILEMAP LAYERS
// Does sprite collide with anything?
// Skip if comparing against itself, or if bodyB isn't collidable, or if bodyB isn't actually part of the Group
// Increase the hit area of the body by the size of the tiles * the scale
// This will allow GetTilesWithinWorldXY to include the tiles around the body
// Tile callbacks take priority over layer level callbacks
// We don't need to go any further if this tile doesn't actually have any colliding faces. This
// could happen if the tile was meant to be collided with re: a callback, but otherwise isn't
// needed for separation.
// Moving faster horizontally, check X axis first
// Moving faster vertically, check Y axis first
// We only need do this if both axes have colliding faces AND we're moving in both
// directions
// That's horizontal done, check if we still intersects? If not then we can return now
// That's vertical done, check if we still intersects? If not then we can return now
// Body is moving LEFT
// Body is moving RIGHT
// Body is moving UP
// Body is moving DOWN
// Currently, all bodies are treated as rectangles when colliding with a Tile.
// aliases
// Temp body pos to avoid body null checks
// First let's inject all of the components into the Game Object
// Body
// Collision:
// Constraint
// Factory
// Geometry
// If there are no callbacks we don't need to test every body, just exit when the first is found
// Install a reference to 'this' on the tile and ensure there can only be one matter body
// associated with the tile
// Set the body either from an existing body (if provided), the shapes in the tileset
// collision layer (if it exists) or a rectangle matching the tile.
// Polygons and polylines are both treated as closed polygons
// Points are relative to the object's origin (first point placed in Tiled), but
// matter expects points to be relative to the center of mass. This only applies to
// convex shapes. When a concave shape is decomposed, multiple parts are created and
// the individual parts are positioned relative to (ox, oy).
//
// Update: 8th January 2019 - the latest version of Matter needs the Vertices adjusted,
// regardless if convex or concave.
// flag coincident part edges
// Just a single Body
// Defaults
// Drag update
// Create the walls
// Reset them
// Inject debug styles
// adjust center
// find frame delta time since last call
// fallback for unusable frame delta values (e.g. 0, NaN, on first frame or long pauses)
// reuse last accepted frame delta else fallback
// record frame delta over a number of frames
// sort frame delta history
// sample a central window to limit outliers
// take the mean of the central window
// snap frame delta to the nearest 1 Hz
// update runner values for next call
// accumulate elapsed time
// limit time buffer size to a single frame of updates
// reset count of over budget updates
// get max updates per frame
// simulate time elapsed between calls
// update the engine
// consume time simulated from buffer
// find elapsed time during this tick
// defer updates if over performance budgets for this frame
// Collision Positions
// Collision Normals
// 1) Don't show invisible bodies
// 2) Don't show static bodies, OR
// 3) Don't show dynamic bodies
// Handle compound parts
// Part polygon
// Render Convex Hulls
// Render constraints
// force = vec2 / point
// Because it could be part of another Composite
// Allow them to do: shape: 'circle' instead of shape: { type: 'circle' }
// Using defaults
// Has the verts array come from Vertices.fromPath, or is it raw?
// Transform Component
// Reset Matter scale back to 1 (sigh)
// Helper function
// init required properties (order is important)
// allow options to override the automatically calculated properties
// From Matter render code:
// body.render.sprite.xOffset += -(body.bounds.min.x - body.position.x) / (body.bounds.max.x - body.bounds.min.x);
// body.render.sprite.yOffset += -(body.bounds.min.y - body.position.y) / (body.bounds.max.y - body.bounds.min.y);
// change vertices
// update properties
// orient vertices around the centre of mass at origin (0, 0)
// update inertia while vertices are at origin (0, 0)
// update geometry
// add all the parts, ensuring that the first part is always the parent body
// find the convex hull of all parts to set on the parent body
// sum the properties of all compound parts of the parent body
// Phaser addition
// Matter.js original
// body.position.x = total.centre.x;
// body.position.y = total.centre.y;
// body.positionPrev.x = total.centre.x;
// body.positionPrev.y = total.centre.y;
// scale vertices
// update properties
// update inertia (requires vertices to be at origin)
// scale position
// update bounds
// handle parent body
// handle circles
// body is no longer a circle
// from the previous step
// update velocity with Verlet integration
// update angular velocity with Verlet integration
// track speed and acceleration
// transform the body geometry
// from equations at:
// https://ecourses.ou.edu/cgi-bin/ebook.cgi?doc=&topic=st&chap_sec=07.2&page=theory
// http://output.to/sideway/default.asp?qno=121100087
// skip adding compound parts
// World is a Composite body
// see src/module/Outro.js for these aliases:
// reuse collision records for gc efficiency
// ensure normal is facing away from bodyA
// find support points, there is always either exactly one or two
// find the supports from bodyB that are inside bodyA
// find the supports from bodyA that are inside bodyB
// account for the edge case of overlapping but no vertex containment
// update supports array size
// can not be intersecting
// find deepest vertex relative to the axis
// convex hill-climbing
// measure next vertex
// compare with previous vertex
// clear collision state arrays, but maintain old reference
// pair already exists (but may or may not be active)
// pair exists and is active
// pair exists but was inactive, so a collision has just started again
// update the pair
// pair did not exist, create a new pair
// push the new pair
// find pairs that are no longer active
// remove inactive pairs
// Phaser addition - skip same body checks
// find total contacts on each body
// find impulses required to resolve penetration
// get current separation between body edges involved in collision
// reset contact count
// update body geometry
// move the body without changing velocity
// reset cached impulse if the body has velocity along it
// warm the next iteration
// resolve each contact
// total impulse from contact
// apply impulse from contact
// update body velocities
// coulomb friction
// account for mass, inertia and contact offset
// raw impulses
// handle high velocity and resting collisions separately
// high normal velocity so clear cached contact normal impulse
// solve resting collision constraints using Erin Catto's method (GDC08)
// impulse constraint tends to 0
// high tangent velocity so clear cached contact tangent impulse
// tangent impulse tends to -tangentSpeed or +tangentSpeed
// total impulse from contact
// apply impulse from contact
// if bodies defined but no points, use body centre
// calculate static length using initial world space points
// option defaults
// render
// Solve fixed constraints first.
// Solve free constraints last.
// update reference angle
// prevent singularity
// solve distance constraint with Gauss-Siedel method
// keep track of applied impulses for post solving
// apply forces
// apply damping
// apply torque
// update geometry and reset
// dampen the cached impulse for warming next step
// avoid hasOwnProperty for performance
// avoid hasOwnProperty for performance
// https://en.wikipedia.org/wiki/Linear_congruential_generator
// https://github.com/mgechev/javascript-algorithms
// Copyright (c) Minko Gechev (MIT license)
// Modifications: tidy formatting and naming
// skip circular dependencies
// flatten already chained functions
// https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358
// get user provided decomp if set
// otherwise from window global
// otherwise from node global
// decomp not available
// for temporary back compatibility only
// increment timestamp
// create an event object
// get all bodies and all constraints in the world
// if the world has changed
// update the detector bodies
// reset all composite modified flags
// update sleeping if enabled
// apply gravity to all bodies
// update all body position and rotation by integration
// update all constraints (first pass)
// find all collisions
// update collision pairs
// wake up bodies involved in collisions
// trigger collision events
// iteratively resolve position between collisions
// update all constraints (second pass)
// iteratively resolve velocity between collisions
// update body speed and velocity properties
// clear force buffers
// log the time elapsed computing this update
// reset force buffers
// add the resultant force of gravity
// wrap bodies within the wrapBounds parameters
// wrap composites within the wrapBounds parameters
// handle Events.off(object, callback)
// create runner if engine is first argument
// fixed timestep
// dynamic timestep based on wall clock between calls
// optimistically filter delta over a few frames, to improve stability
// limit delta
// update engine timing object
// create an event object
// fps counter
// update
// update bodies sleeping status
// wake up bodies if they have a force applied
// biased average motion estimation between frames
// don't wake inactive pairs
// don't wake if at least one body is static
// TODO: true circle bodies
// approximate circles with polygons until true circles implemented in SAT
// optimisation: always use even number of sides (half the number of unique axes)
// check decomp is as expected
// ensure vertexSets is an array of arrays
// fallback to convex hull when decomposition is not possible
// initialise a decomposition
// vertices are concave and simple, we can decompose into parts
// use the quick decomposition algorithm (Bayazit)
// for each decomposed chunk
// convert vertices into the correct structure
// skip small chunks
// create a compound part
// create body parts
// flag internal edges (coincident part edges)
// iterate vertices of both parts
// find distances between the vertices
// if both vertices are very close, consider the edge concident (internal)
// create the parent body to be returned, that contains generated compound parts
// offset such that body.position is at the centre off mass
// iterate vertices of both parts
// find distances between the vertices
// if both vertices are very close, consider the edge concident (internal)
// reverse row order
// retroactively fix the first body's position, since width was unknown
// find the unique axes, using edge normal gradients
// limit precision
// https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js
// all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1)
// when the last point doesn't equal the current point add the current point
// set last point
// skip path ends
// map segment to x and y
// ensure path is absolute
// get total length
// queue segments
// sample through path
// get segment at position
// new segment
// add points in between when curving
// TODO: adaptive sampling
// increment by sample value
// add remaining segments not passed by sampling
// http://phrogz.net/convert-svg-path-to-all-absolute-commands
// Copyright (c) Gavin Kistner
// http://phrogz.net/js/_ReuseLicense.txt
// TODO: consider params for reusing vector objects
// find the polygon's moment of inertia, using second moment of area
// from equations at http://www.physicsforums.com/showthread.php?t=25293
// quality defaults to -1, which is auto
// automatically decide precision
// use an even value for precision, more likely to reduce axes by using symmetry
// http://paulbourke.net/geometry/polygonmesh/
// Copyright (c) Paul Bourke (use permitted)
// http://geomalgorithms.com/a10-_hull-1.html
// sort vertices on x-axis (y-axis for ties)
// build lower hull
// build upper hull
// concatenation of the lower and upper hulls gives the convex hull
// omit last points because they are repeated at the beginning of the other list
// v0.3.0
// segments are parallel
// find bottom right point
// reverse poly if clockwise
// for each edge
// ignore incident edges
// Insert all vertices from i to j
// Insert vertices 0 to j
// Insert vertices i to end
// Cut all polys
// Found poly! Cut and quit
// Was given one edge
// Check
// Check the segment between the last and the first point to all others
// if there are no vertices to connect to, choose a point in the middle
//console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+polygon.length+")");
//lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1);
//upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end());
//upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
//lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
//lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1);
//upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1);
// connect to the closest point within the triangle
//console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+polygon.length+")\n");
// solve smallest poly first
// Remove the middle point
// Here are the game-level events you can listen to.
// At the very least you should offer a destroy handler for when the game closes down.
// var eventEmitter = this.game.events;
// eventEmitter.once('destroy', this.gameDestroy, this);
// eventEmitter.on('pause', this.gamePause, this);
// eventEmitter.on('resume', this.gameResume, this);
// eventEmitter.on('resize', this.gameResize, this);
// eventEmitter.on('prestep', this.gamePreStep, this);
// eventEmitter.on('step', this.gameStep, this);
// eventEmitter.on('poststep', this.gamePostStep, this);
// eventEmitter.on('prerender', this.gamePreRender, this);
// eventEmitter.on('postrender', this.gamePostRender, this);
// Contains the plugins that the dev has loaded into their game
// Any plugins to install?
// Any plugins added outside of the game config, but before the game booted?
// { key: 'TestPlugin', plugin: TestPlugin, start: true, mapping: 'test', data: { msg: 'The plugin is alive' } }
// Any scene plugins to install?
// { key: 'moveSpritePlugin', plugin: MoveSpritePlugin, , mapping: 'move' }
// Reference the GlobalPlugins from Game into Scene.Systems
// Scene level injection
// Scene is already booted, usually because this method is being called at run-time, so boot the plugin
// And finally, inject any 'global scene plugins'
// Merge in custom Scene plugins
// Plugin is freshly loaded
// Plugin wasn't from the loader but already exists
// Add it to the plugin store
// Plugin already running under this key?
// It exists, we just need to start it up again
// From https://github.com/ThaUnknown/rvfc-polyfill
// Not included because there's no clear use case for it.
// SUBTRACT: 3,
// Has the underlying canvas size changed?
// Save context pre-clip
// Restore pre-clip context
// Nothing to see, so abort early
// Auto-invert the flipY if this is coming from a GLTexture
// Multiply by the Sprite matrix
// Nothing to see, so don't waste time calculating stuff
// Blend Mode
// Area Grab
// Full Grab
// Un-premultiplication.
// This will be automatically populated below.
// Create a framebuffer referencing the canvas.
// This is used for the main framebuffer.
// It does not need to resize after creation.
// Convert Y coordinate to WebGL space.
// Ensure the framebuffer texture is not bound to a texture unit.
// Seek a DrawingContext of the given size.
// Extract the DrawingContext from the agePool
// Seek a DrawingContext that is old enough to reuse.
// Remove the DrawingContext from the agePool
// Remove the DrawingContext from the sizePool
// Resize the DrawingContext
// Create a new DrawingContext within the pool size limit.
// Seek the oldest DrawingContext to resize.
// Remove the DrawingContext from the sizePool
// Resize the DrawingContext
// Create a new DrawingContext exceeding the pool size limit.
// Remove carriage return characters from the shader source.
// Remove carriage return characters from the shader source.
// Name the program after the key.
// Remove any remaining template directives.
// Note: This is the maximum number of TIUs that a _fragment_ shader supports
// https://www.khronos.org/opengl/wiki/Common_Mistakes#Texture_Unit
// Hard-clamp this to 16 to avoid run-away texture counts such as on Android
// Self-shadowing uniforms.
// Clear lighting uniforms.
// removed by dead control flow
// Did they provide their own context?
// Set it back into the Game, so developers can access it from there too
// ADD
// MULTIPLY
// SCREEN
// ERASE
// Setup initial WebGL state
// Mipmaps
// Check maximum supported textures
// Provision the generic quad index buffer.
// Ensure that there is no VAO bound, because the following index buffer
// will modify any currently bound VAO.
// Set up render nodes.
// Set-up default textures, fbo and scissor
// Set up drawing contexts.
// Disable the option if the extension is not supported.
// Make WebGL2 core features which were extensions available on the WebGL1 context.
// This allows us to use a WebGL2 context.
// Incorporate instanced arrays.
// Incorporate vertex array objects.
// Incorporate standard derivatives.
// Restore GL extensions.
// Force update the GL state.
// Re-enable compressed texture formats.
// Restore wrapped GL objects.
// Order matters, as some wrappers depend on others.
// Restore texture unit assignment.
// Apply resize.
// Context has been restored.
// Filters above LINEAR only work with MIPmaps.
// These are only generated for power of two (POT) textures.
// Compressed textures with mipmaps are always POT,
// but POT compressed textures might not have mipmaps.
// Sync the background color to the DrawingContext.
// Handle snapshot requests.
// Ensure they're not trying to grab an area larger than the framebuffer
// We don't need to unbind the framebuffer,
// because the next time we draw it will be bound again.
// Calculate the final number of instances per batch.
// Listen for changes to the number of draw calls per batch.
// Ensure that there is no VAO bound, because the following index buffer
// Prepare the vertex buffer layout.
// Fill in program configuration from config.
// Ensure that shader program has the correct number of textures.
// Set the dimension-related uniforms and listen for resize events.
// Deep copy shaderAdditions to avoid modifying the original object.
// These may be left undefined to auto-calculate instance count.
// Set up vertex buffer layout.
// This is empty and should be overridden by subclasses.
// Update vertex buffers.
// Because we frequently aren't filling the entire buffer,
// we need to update the buffer with the correct size.
// Reset batch accumulation.
// Update the vertex buffer.
// Bottom left
// Top left
// Bottom right
// Top right
// Increment the instance count.
// Check whether the batch should be rendered immediately.
// This guarantees that none of the arrays are full above.
// Now the batch is empty.
// Placed before super call because the constructor needs it.
// Main sampler will never change after initialization,
// because it addresses texture units, not textures.
// The batch is currently running. Flush the current batch entry,
// before the shader program becomes unable to handle all textures.
// Update program manager to use the new texture count.
// Standard uniforms.
// Lighting uniforms.
// In the shader, this is an array of vec2s.
// But we must compose it as a flat array,
// not an array of arrays.
// The normal map is included in the textures array,
// but it's attached to another texture unit,
// so we shouldn't count it.
// Finalize the current batch entry.
// Update vertex buffers.
// Because we frequently aren't filling the entire buffer,
// we need to update the buffer with the correct size.
// Check render options and run the batch if they differ.
// Process textures and get relevant data.
// Pack tint mode with secondary tint colors.
// Assign default secondary tint colors if not provided.
// Bottom-left
// Top-left
// Bottom-right
// Top-right
// Texture data, used for either texture ID or normal map rotation.
// Multi Texture
// Check if the texture is already in the batch.
// This could be a very expensive operation if we're not careful.
// If we just use `batchTextures.indexOf`, a linear search,
// we can use up to 20% of a frame budget.
// Instead, we cache the texture unit index on the texture itself,
// so we can immediately tell whether it's in the batch.
// We reset this value when we flush the batch.
// Commit the current batch entry and start a new one.
// // Complete the entire batch if the texture changes.
// this.run(currentContext);
// Current batch entry has been redefined.
// Single texture.
// Current batch entry has been redefined.
// Clear unit assignment on textures.
// We do not expect to use extra textures.
// This guarantees that none of the arrays are full below.
// Add degenerate triangles between strips.
// Copy the previous vertex to the start of the next strip.
// Repeat the first vertex of the strip.
// Increment the instance count.
// Every 2 vertices is an instance.
// Enable texture resolution data if not already available.
// The options are constant across the whole mesh, so we check once.
// Build the transform matrix once for the whole mesh, then project each
// vertex cheaply below.
// Process the texture. This may start a new batch entry.
// Vertex A
// Vertex B
// Vertex C
// Increment the instance count.
// Check whether the batch should be rendered immediately.
// This guarantees that none of the arrays are full above.
// Now the batch is empty.
// Update index buffer.
// We must bind the VAO before updating the index buffer.
// Each index is a 16-bit unsigned integer, so 2 bytes.
// Buffer data
// Track vertex usage.
// Update the vertex buffer.
// Assign the vertex to the current pass.
// Record the index where the vertex was stored.
// Update the index buffer.
// There is always at least one index per vertex,
// so we can assume that the vertex buffer is large enough.
// Check whether the instance is complete.
// The instance count has been reached.
// This triangle is complete, and another would exceed the index buffer size.
// Check if the camera has any active filters.
// Check whether the parentTransformMatrix is the identity matrix.
// Generate a drawing context.
// Set the scissor to the camera dimensions.
// Enter drawing context.
// Draw camera background.
// Draw children.
// Draw camera post effects.
// Finish rendering children.
// Filters and framebuffers.
// Set up render options.
// Draw internal filters.
// Execute the filter RenderNode.
// Record padding.
// Begin external filters.
// Calculate coverage, starting from the final filter.
// Increase coverage.
// Will the texture need to be repositioned for the external filters?
// Create external context.
// Draw the framebuffer to the external context.
// If there are no external filters, this will be the final draw.
// Assume that `roundPixels` conveys the intent to round coordinates.
// The `Filters` game object component sets this accordingly.
// Texture.
// While this comes from a temporary framebuffer,
// and this is a batch operation,
// so the texture might not be accessed immediately,
// any operation that accesses the framebuffer pool
// will cause the batch to flush before the texture is reassigned.
// Transformed quad in order TL, BL, TR, BR:
// Texture coordinates in X, Y, Width, Height:
// Tint color:
// Tint colors in order TL, BL, TR, BR:
// Render options:
// Draw external filters.
// The filter supports drawing to the base context.
// The texture is the same size as the base context.
// Last filter.
// Alpha is 1.
// Draw the final filter straight to the base context.
// Execute the filter RenderNode.
// Get and invert the padding for the next step.
// Draw external stack to parent context.
// Texture.
// Transformed quad in order TL, BL, TR, BR:
// Texture coordinates in X, Y, Width, Height:
// Tint color:
// Tint colors in order TL, BL, TR, BR:
// Render options:
// A well-formed path has no zero length segments, so we don't check.
// Ensure the framebuffer texture is not bound,
// to avoid WebGL feedback.
// Big list of reused variables.
// Traverse commands.
// Handle custom capture camera.
// Clear the command buffer.
// Finish rendering.
// Regenerate any mipmap before using the texture.
// Handle blend mode.
// Reset to the base context.
// Change blend mode.
// Transform the point.
// Skip this point if it's too close to the previous point
// and is not the first or last point in the path.
// If the tint colors are all the same,
// then we can share vertices between the triangles.
// If the tint colors are different,
// then we need to create a new vertex for each triangle.
// Vertex A
// Vertex B
// Vertex C
// Add new indices for the triangle.
// Render each child in the display list
// Only release non-base contexts.
// Reset to the base context.
// Change blend mode.
// Release any remaining context.
// Clear the current framebuffer's stencil and depth renderbuffers.
// Rebind the entire WebGL state, setting resources to null.
// Unbind all texture units, forcing rebind on use.
// Insert code here.
// If a node is somehow added during a debug render pass,
// ensure that it is also set to debug.
// Insert a synthetic root node.
// Get transformed quad vertices.
// Populate vertex buffer.
// Bottom Left.
// Top Left.
// Bottom Right.
// Top Right.
// Render.
// Set user uniforms after built-ins to permit overrides.
// Draw.
// NOOP.
// Determine connectivity of index array.
// Lines will be connected by a secondary quad.
// The last line will be connected to the first line.
// Skip the next point if it's too close to the current point.
// Compute and add the vertices for the line segment.
// The previous operation added 4 vertices.
// Draw two triangles.
// The vertices are in the order: TL, BL, BR, TR
// Draw a quad connecting to the previous line segment.
// The vertices are in the order:
// - TL
// - BL
// - Previous BR
// - Previous TR
// Connect the last line segment to the first.
// The vertices are in the order:
// - BR
// - TR
// - First TL
// - First BL
// This is the base run method that all filters should override
// Include the BoundedSampler addition.
// Set the shader program to use texture unit 0.
// Get a new DrawingContext to render to.
// Assemble textures.
// Compute quad vertices.
// Account for padding.
// Update vertex buffer.
// Render.
// Render layer.
// Complete render.
// This is the base setupUniforms method that all filters should override
// Low,high are in the range -1,1.
// Convert low,high to 0,1.
// Blend texture.
// Horizontal pass
// Stop adding padding after the first pass.
// Vertical pass
// Displacement texture.
// Ramp data texture.
// Environment map texture.
// Normal map texture.
// Update dynamic texture if necessary.
// Mask texture.
// Prevent the input from being sent back to its pool.
// Process bottom filters.
// Don't apply more padding after the first filter.
// Process top filters.
// Check whether the input is no longer in use,
// and won't be released automatically below.
// If it is the bottom context, it will be released by the Blend.
// If it is the top context, it will be released directly.
// Blend the top and bottom filters.
// Whether top context is new or the input, it now needs to be released.
// No filters to run.
// Copy the input to the output.
// Region is a Rectangle.
// Region is a point.
// Sample the whole buffer.
// Reveal texture
// Build the transform matrix once for the whole mesh, so that
// `_submitQuad` can transform each vertex cheaply.
// If the game object has a prebuilt ordered index list, consume it
// directly. It is arranged into quad-forming pairs of triangles, so we
// can submit quads without searching for shared edges.
// Each quad is a pair of triangles (8 values):
// p, q, r, page (first triangle) and q, r, s, page (second).
// If the mesh does not have a prebuilt ordered index list,
// submit each triangle as a quad,
// synthesizing a degenerate triangle for the other half of the quad.
// The transform matrix is built once per mesh by `run`, via
// `transformerNode.setupMatrix`, so we only project each vertex here.
// Combined quad in order TL, BL, TR, BR:
// Texture coordinates in order TL, BL, TR, BR:
// Extra render options:
// Secondary tint colors in order TL, BL, TR, BR:
// Use `frame.source.glTexture` instead of `frame.glTexture`
// to avoid unnecessary getter function calls.
// Get normal map.
// Get normal map rotation.
// Get self-shadow.
// Get smooth pixel art option.
// Set up vertex buffer.
// The vertex index, 0-3.
// Set up vertex buffer layout.
// Set up instance buffer layout.
// Set texture sampler uniforms.
// Lighting uniforms.
// Set alpha strategy options.
// Set lighting options.
// Set smooth pixel art options.
// Set features.
// Update instance buffer if needed.
// Everything needs updating.
// Only some segments need updating.
// Render instances.
// Frame coordinates in order TL, BL, TR, BR:
// Normal map rotation must include the texture rotation.
// Dynamic UV coordinates in order TL, BL, TR, BR:
// TilemapGPULayer uniforms.
// We do not track whether the shader program has changed.
// This is because this is not a batch renderer,
// and the program is set every time this is called.
// Set animation options.
// Set self-shadow options.
// Set up border filtering options.
// Transform layer quad.
// Multiply by the Sprite matrix
// Compute output quad.
// Modify the frame dimensions based on the crop.
// TODO: Is there any other crop logic to consider?
// Compute UVs.
// // Normalize coordinate space.
// Apply texture transformation in TSR order.
// This is necessary to avoid skew.
// Find where the GameObject area sits in normalized space.
// Store the output quad.
// Determine whether the matrix does not rotate, scale, or skew.
// Keyword: #OnlyTranslate
// Handle vertex rounding.
// Get view matrix.
// TODO: Is the tileset missing?
// Unlike TransformerImage, the dimensions of a TileSprite are not
// derived from the frame, but from the GameObject itself.
// Cache whether vertices should be rounded, as this is constant
// for the whole GameObject.
// Integer, so add a decimal point to convert to a float.
// Possible errors that can be thrown by `gl.checkFramebufferStatus()`.
// Only generate depth and stencil buffers if color attachments are provided.
// Generate a depth-stencil buffer if both are requested.
// These must be attached after the color attachments,
// so that the framebuffer is complete when they're attached.
// Remove any existing framebuffer.
// Create framebuffer.
// Create attachments.
// Check for completeness.
// We must do this after the color attachments are created,
// or the framebuffer will be incomplete and cannot accept
// a renderbuffer.
// We could check for completeness again here,
// but the invocations were checked during development,
// and the renderbuffer is free of error.
// Remove bindings from the global state.
// Must happen after setting the framebuffer.
// Ensure that there is no vertex buffer associated with this program,
// so that the attributes are reset.
// GL state can't be updated right now.
// `createResource` will run when the context is restored.
// Unbind current program before creating a new one.
// Otherwise, the old program will stay in use,
// and cause errors.
// Extract attributes.
// Send the old uniforms to the request map,
// so they are recreated with the new program.
// Update stored values if they are different.
// Get info about the uniform.
// Set the value.
// Create a reusable 1x1 texture for all units.
// Leave the units undefined, so they can be set to null.
// Enumerate the texture units.
// eslint-disable-next-line camelcase
// Use the source texture directly.
// Set Spector metadata.
// Assign the texture to our wrapper.
// Repeat modes
// Mipmap modes
// Assume that the source might change.
// eslint-disable-next-line camelcase
// eslint-disable-next-line camelcase
// Do not delete a texture that belongs to another wrapper.
// Connect attribute locations from program.
// This attribute is not used in the shader, so skip it.
// Create attribute pointers.
// Finalize VAO.
// Force unbind buffers, as they may have been unbound by the VAO
// without syncing state management.
// Fill in the layout with the stride
// and per-attribute bytes and offset.
// First, append the current offset.
// Convert the type to a GLenum if it is a string.
// Append the bytes per attribute element.
// Now that we know the total stride, we can set it.
// Parse the config to get the scaling values we need
// Only set the parent bounds if the parent has an actual size
// Get the parent element, if any
// Get the size of the parent element
// This can often set a height of zero (especially for un-styled divs)
// If width = '100%', or similar value
// Does width have a % character at the end? If not, we use it as a numeric value.
// If we have a parent with a width, we'll work it out from that
// If height = '100%', or similar value
// Does height have a % character at the end? If not, we use it as a numeric value.
// If we have a parent with a height, we'll work it out from that
// The un-modified game size, as requested in the game config (the raw width / height) as used for world bounds, etc
// The modified game size
// The size used for the canvas style, factoring in the scale mode and parent and zoom value
// We just use the w/h here as this is what sets the aspect ratio (which doesn't then change)
// User is responsible for managing the parent
// The parent STILL has no height, clearly no CSS
// has been set on it even though we fixed the body :(
// And now get the fullscreenTarget
// Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect
// The returned value is a DOMRect object which is the smallest rectangle which contains the entire element,
// including its padding and border-width. The left, top, right, bottom, x, y, width, and height properties
// describe the position and size of the overall rectangle in pixels. Properties other than width and height
// are relative to the top-left of the viewport.
// Update the aspect ratio
// No scale
// Resize to match parent
// This will constrain using min/max
// Expand canvas size to fit game size's width or height
// Resize to match parent, like RESIZE mode
// All other scale modes
// Update the parentSize in case the canvas / style change modified it
// Finally, update the centering
// Get the parent size again as it will have changed
// Only dispatched on mobile devices
// MS Specific
// They pressed ESC while in fullscreen mode
// Returns true if the parent bounds have changed size
// MS Specific
// No default physics system or systems in this scene
// Let's build the systems array
// An array of Physics systems to start for this Scene
// Scene Plugins always override Default Plugins
// No default plugins or plugins in this scene
// These properties get injected into the Scene and map to local systems
// The map value is the property that is injected into the Scene, the key is the Scene.Systems reference.
// These defaults can be modified via the Scene config object
// var config = {
// map: {
// add: 'makeStuff',
// load: 'loader'
// }
// };
// The i === 0 part just autostarts the first Scene given (unless it says otherwise in its config)
// Create the system Scene
// Replace key in case the scene changed it
// Any data to inject?
// Clear the pending lists
// _start might have been populated by the above
// _start might have been populated by this.add
// Clear the pending lists
// If processing or not booted then put scene into a holding pattern
// Any data to inject?
// Replace key in case the scene changed it
// Start the loader going as we have something in the queue
// No preload? Then there was nothing to load either
// Loop through the active scenes in reverse order
// Loop through the scenes in forward order
// If the Scene has an update function we'll set it now, otherwise it'll remain as NOOP
// Extract callbacks
// Now let's move across any other functions or properties that may exist in the extend object:
// Populate the DataManager
// By this point it's either 'default' or extracted from the Scene
// Sleeping?
// Paused?
// Not actually running?
// If the Scene Manager is not running, then put the Scene into a holding pattern
// If the scene is already started but not yet running,
// let it continue.
// If the Scene is already running, paused, or sleeping,
// close it down before starting it again.
// If the Scene is INIT or SHUTDOWN,
// start it directly.
// Files payload?
// Remove
// Add in new location
// Add in new location
// Not a valid target if it doesn't exist, isn't active or is already transitioning in or out
// Notify target scene
// Clear target scene settings
// Clear local settings
// Now everything is clear we can handle what happens to this Scene
// Pass the 'hasOwnProperty' checks
// Loader payload array
// Cameras
// Scene Property Injection Map
// Physics
// Loader
// Plugins
// Input
// Global Systems - these are single-instance global managers that belong to Game
// Core Plugins - these are non-optional Scene plugins, needed by lots of the other systems
// This will get replaced by the SceneManager with the actual update function, if it exists, once create is over.
// For plugins to listen out for
// For user-land code to listen out for
// eslint-disable-next-line no-console
// \/\/\/ isPlaying = true, isPaused = false \/\/\/
// \/\/\/ isPlaying = false, isPaused = true \/\/\/
// \/\/\/ isPlaying = false, isPaused = false \/\/\/
// sort by progress
// eslint-disable-next-line no-unused-vars
// handling delayed playback
// handle looping and ending
// eslint-disable-next-line no-unused-vars
// sound ended
// else was stopped
// setTimeout to avoid weird audio artifacts (thanks Apple)
// eslint-disable-next-line no-console
// Firefox doesn't currently implement positionX, positionY and positionZ properties on AudioListener,
// falling back on AudioListener.prototype.setPosition() method. @see https://developer.mozilla.org/en-US/docs/Web/API/AudioListener/setPosition
// Resume interrupted audio on iOS only if the game has focus
// Return -1 if given child isn't a child of this display list
// eslint-disable-next-line no-console
// Don't add if already active or pending, but DO add if active AND in the destroy list
// Check if it's in the _pending list
// Remove directly, no need to wait for an update loop
// Item is actively running? Queue it for deletion
// If neither of the above conditions pass, then the item is either already in the destroy list,
// or isn't pending or active, so cannot be removed anyway
// Clear the 'destroy' list
// Remove from the 'active' array
// Process the pending addition list
// This stops callbacks and out of sync events from populating the active array mid-way during an update
// The owner of this queue can now safely do whatever it needs to with the active list
// max entries in a node is 9 by default; min node fill is 40% for best performance
// recursively build the tree with the given data from scratch using OMT algorithm
// save as is if tree is empty
// split root if trees have the same height
// swap trees if inserted one is bigger
// insert the small tree into the large tree at appropriate level
// depth-first iterative tree traversal
// item found, remove the item and condense tree upwards
// reached leaf level; return leaf
// target height of the bulk-loaded tree
// target number of root entries to maximize storage utilization
// split the items into M mostly square tiles
// pack each entry recursively
// choose entry with the least area enlargement
// otherwise choose one with the smallest area
// find the best node for accommodating the item, saving all nodes along the path too
// put the item into the node
// split on node overflow; propagate upwards if necessary
// adjust bboxes along the insertion path
// split overflowed node into two
// split root node
// choose distribution with minimum overlap
// otherwise choose distribution with minimum area
// sorts node children by the best axis for split
// if total distributions margin value is minimal for x, sort by minX,
// otherwise it's already sorted by minY
// total margin of all possible split distributions where each node is at least m full
// adjust bboxes along the given tree path
// go through the path, removing empty nodes and updating bboxes
// calculate node's bbox from bboxes of its children
// min bounding rectangle of node children from k to p-1
// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
// combines selection algorithm with binary divide & conquer approach
// We need to change the height to fit the width
// Reduce the width accordingly
// We need to change the width to fit the height
// Reduce the height accordingly
// Update the Canvas
// Update the Texture Source
// Update the Frame
// Update this
// Resize the frame
// The last command finished an ERASE operation,
// so we can just extend it.
// Game Objects
// Groups / Display Lists
// Texture key
// Texture Frame instance
// Another Array
// Compute the parent transform.
// Ensure that parent transform exists.
// Ensure that camera transforms are applied.
// Cache and override the object properties.
// Only apply angle if rotation is not defined.
// Restore the object properties.
// Store actual values
// Adjust properties
// Clamp the input values
// Need to check for intersection between the cut area and the crop area
// If there is none, we set UV to be empty, otherwise set it to be the intersection area
// Map the given coordinates into UV space, clamping to the 0-1 range.
// Canvas data
// WebGL data
// Canvas data
// Load the Sources
// Set the first frame of the Texture (other than __BASE)
// This is used to ensure we don't spam the display with entire
// atlases of sprite sheets, but instead just the first frame of them
// should the dev incorrectly specify the frame index
// null, undefined, empty string, zero
// By this point key should be a Texture, if not, the following fails anyway
// Phaser Compact Texture Atlas format?
// New Texture Packer format?
// Multi-Atlas?
// !! Assumes the textures are in the same order in the source array as in the json data !!
// If trimmed we need to help the parser adjust
// Adjust for trim (if not trimmed x and y are just zero)
// removed by dead control flow
// Tidy up unused pool canvases.
// Malformed?
// Add in a __BASE entry (for the entire atlas)
// By this stage frames is a fully parsed array
// The frame values are the exact coordinates to cut the frame out of the atlas from
// These are the original (non-trimmed) sprite values
// Copy over any extra data
// Copy over any additional data that was in the JSON to Texture.customData
// By this stage frames is a fully parsed Object
// levelSize field
// add padding for odd sized image
// offset += 3 - ((levelSize + 3) % 4);
// Add a __BASE entry for source 0 (matches the behavior of JSONArray / JSONHash)
// Copy the page and folder metadata onto the Texture's customData so it is accessible later
// Hardcoded extension dictionary, as defined by the PCT format specification
// Folder index: "N/rest"
// Extension index: "name~N" (per-name, overrides line-level)
// Check for trailing extension suffix: ~N at very end
// Validate the version header - must be the first line
// Strip trailing \r if the file uses CRLF line endings
// A pending block ALWAYS consumes the next non-empty line as its
// names line, regardless of what prefix character that line starts
// with. This must be checked before any prefix-based dispatch below.
// Alias: A:originalName=dupName1,dupName2,...
// Individual frame line
// Unknown or future line type — skip safely
// Trim data is packed into a single segment as "sw,sh,sx,sy",
// mirroring the layout used by the B: block header trim fields.
// VERSION
// PIXEL_FORMAT_INDEX
// Colour Space
// MIPMAPCOUNT_INDEX
// WIDTH_INDEX
// HEIGHT_INDEX
// HEADER_SIZE + METADATA_SIZE_INDEX
// If missing we can't proceed
// Allow negative skipframes.
// Add in a __BASE entry (for the entire atlas frame)
// trim offsets
// The frame values are the exact coordinates to cut the frame out of the atlas from
// These are the original (non-trimmed) sprite values
// Add in a __BASE entry (for the entire atlas)
// var pivot = { x: 0, y: 0 };
// var border = { x: 0, y: 0, z: 0, w: 0 };
// Start new list
// case 'pivot':
// pivot = eval('var obj = ' + value);
// break;
// case 'border':
// border = eval('var obj = ' + value);
// Check that mipmaps are power-of-two sized.
// WebGL does not allow non-power-of-two textures for mip levels above 0.
// Check specific format requirements.
// WEBGL_compressed_texture_astc
// WEBGL_compressed_texture_etc
// WEBGL_compressed_texture_etc1
// ASTC, ETC, and ETC1
// only require data be provided in arrays of specific size,
// which are already set by the parser.
// WEBGL_compressed_texture_pvrtc
// Other mip levels have already been checked for power-of-two size.
// WEBGL_compressed_texture_s3tc_srgb
// Mip levels above 0 must be 0, 1, 2, or a multiple of 4 pixels.
// However, as WebGL mip levels must all be power-of-two sized,
// this is already covered by the power-of-two check.
// ETC internal formats:
// COMPRESSED_R11_EAC
// COMPRESSED_SIGNED_R11_EAC
// COMPRESSED_RG11_EAC
// COMPRESSED_SIGNED_RG11_EAC
// COMPRESSED_RGB8_ETC2
// COMPRESSED_SRGB8_ETC2
// COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
// COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
// COMPRESSED_RGBA8_ETC2_EAC
// COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
// ETC1 internal formats:
// COMPRESSED_RGB_ETC1_WEBGL
// ATC internal formats:
// COMPRESSED_RGB_ATC_WEBGL
// COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL
// COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
// These formats are no longer supported in WebGL.
// They have no special restrictions on size, so if they were decoded,
// they are already valid.
// We'll show a warning for no format checker found.
// ASTC internal formats:
// COMPRESSED_RGBA_ASTC_4x4_KHR
// COMPRESSED_RGBA_ASTC_5x4_KHR
// COMPRESSED_RGBA_ASTC_5x5_KHR
// COMPRESSED_RGBA_ASTC_6x5_KHR
// COMPRESSED_RGBA_ASTC_6x6_KHR
// COMPRESSED_RGBA_ASTC_8x5_KHR
// COMPRESSED_RGBA_ASTC_8x6_KHR
// COMPRESSED_RGBA_ASTC_8x8_KHR
// COMPRESSED_RGBA_ASTC_10x5_KHR
// COMPRESSED_RGBA_ASTC_10x6_KHR
// COMPRESSED_RGBA_ASTC_10x8_KHR
// COMPRESSED_RGBA_ASTC_10x10_KHR
// COMPRESSED_RGBA_ASTC_12x10_KHR
// COMPRESSED_RGBA_ASTC_12x12_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR
// COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR
// BPTC internal formats:
// COMPRESSED_RGBA_BPTC_UNORM_EXT
// COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT
// COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT
// COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT
// RGTC internal formats:
// COMPRESSED_RED_RGTC1
// COMPRESSED_SIGNED_RED_RGTC1
// COMPRESSED_RG_RGTC2
// COMPRESSED_SIGNED_RG_RGTC2
// PVRTC internal formats:
// COMPRESSED_RGB_PVRTC_4BPPV1_IMG
// COMPRESSED_RGB_PVRTC_2BPPV1_IMG
// COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
// COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
// S3TC internal formats:
// COMPRESSED_RGB_S3TC_DXT1_EXT
// COMPRESSED_RGBA_S3TC_DXT1_EXT
// COMPRESSED_RGBA_S3TC_DXT3_EXT
// COMPRESSED_RGBA_S3TC_DXT5_EXT
// S3TCSRGB internal formats:
// COMPRESSED_SRGB_S3TC_DXT1_EXT
// COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT
// COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT
// COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
// This relies on the tileset texture *also* having been loaded as a spritesheet. This isn't guaranteed!
// If we can't satisfy the request, probably best to null it out rather than set a whole spritesheet or something.
// Tiled places tiles on a grid of baseWidth x baseHeight. The origin for a tile in grid
// units is the bottom left, so the y coordinate needs to be adjusted by the difference
// between the base size and this tile's size.
// In orthogonal mode, Tiled places tiles on a grid of baseWidth x baseHeight. The origin for a tile is the
// bottom left, while the Phaser renderer assumes the origin is the top left. The y
// coordinate needs to be adjusted by the difference.
// Reminder: For the tilemap to be centered we have to move the image to the right with the camera!
// This is crucial for wordtotile, tiletoworld to work.
// Check for an associated tilemap layer
// Default the x/y position to match Tiled layer offset, if it exists.
// Sweep to get all the objects we want to convert in this pass
// Now let's convert them ...
// Origin is (0, 1) for tile objects or (0, 0) for other objects in Tiled, so find the offset that matches the Sprites origin.
// Do not offset objects with zero dimensions (e.g. points).
// If the object is rotated, then the origin offset also needs to be rotated.
// Update the base tile size on all layers & tiles
// Defaults are applied in ParseToTilemap
// Allow users to specify null to indicate that they want the default value, since null is
// shorter & more legible than undefined. Convert null to undefined to allow ParseToTilemap
// defaults to take effect.
// Convert layer into a data texture.
// Get or initialize the animation data texture in the Tileset.
// Generate the layer map.
// This tile is part of an animation.
// Set flip flags.
// Set the fourth bit to 1 to indicate an empty tile.
// Create or update the tile data texture.
// Link the LayerData with this static tilemap layer
// Abort, we've already been destroyed
// Uninstall this layer only if it is still installed on the LayerData object
// Binary search.
// In Tiled a tileset image that is not an even multiple of the tile dimensions is truncated
// - hence the floor when calculating the rows/columns.
// In Tiled, "empty" spaces in a tileset count as tiles and hence count towards the gid
// Update the animation data texture.
// This index maps to an animation, not a single tile.
// This animation points to a run of frames.
// The run of frames stores the duration and the actual index.
// Store the maximum length of any animation.
// Store the index as an offset from the start of the animation frames.
// Double the index to account for the 2x 32-bit values per entry.
// Create or update the animation data texture.
// Assume the changed tile has all interesting edges
// Reset edges that are shared between tile and its neighbors
// we always subtract 1/2 of the tile's height/width to make the culling distance start from the center of the tiles.
// Returns an array of Tile references
// Create a new array of fresh Tile objects
// Recalculate the faces within the destination area and neighboring tiles
// Assume 1 to 1 mapping with indexes array
// Assume 1 replacement for all types of tile given
// We need to use the tile sizes defined for the map as a whole, not the layer,
// in order to calculate the bounds correctly. As different sized tiles may be
// placed on the grid and we cannot trust layer.baseTileWidth to give us the true size.
// Camera world view bounds, snapped for scaled tile size
// Cull Padding values are given in tiles, not pixels
// Recalculate the faces within the area and neighboring tiles
// Top Left
// Top Right
// Bottom Right
// Bottom Left
// Clip x, y to top left of map, while shrinking width/height to match.
// Clip width and height to bottom right of map.
// intersectTest is a function with parameters: shape, rect
// Top left corner of the shapes's bounding box, rounded down to include partial tiles
// Bottom right corner of the shapes's bounding box, rounded up to include partial tiles
// Tiles within bounding rectangle of shape. Bounds are forced to be at least 1 x 1 tile in size
// to grab tiles for shapes that don't have a height or width (e.g. a horizontal line).
// Top left corner of the rect, rounded down to include partial tiles
// Bottom right corner of the rect, rounded up to include partial tiles
// Sets the center of the tile into tempVec
// Hard-coded orientation values for Pointy-Top Hexagons only
// origin
// Find the world position relative to the static or dynamic layer's top left origin,
// factoring in the camera's vertical scroll
// size
// x = b0 * tileWidth
// y = tileHeightHalf
// x = tileWidthHalf
// y = b0 * tileHeight
// right-down
// left-down
// right-up
// left-up
// factoring in the camera's horizontal scroll
// Updating colliding flag on the new tile
// Recalculate faces only if the colliding flag at (tileX, tileY) has changed
// Force the input array to be a 2D array
// If no indices are given, then find all the unique indexes within the specified region
// Recalculate faces only if the removed tile was a colliding tile
// Default colors without needlessly creating Color objects
// Inset the face line to prevent neighboring tile's lines from overlapping
// var hr = hex_round(h);
// var o = roffset_from_cube(ODD, hr);
// var b = roffset_to_cube(ODD, o);
// g.scene.add.text(c[3].x + 2, c[3].y + 6, `${hr.q} x ${hr.r}`);
// Update the array of colliding indexes
// Update the tiles
// Update the array of colliding indexes
// Update the tiles
// Note: this only updates layer.collideIndexes for tile indexes found currently in the layer
// It's possible in Tiled to have a collision group without any shapes, e.g. create a
// shape and then delete the shape.
// Find the world position relative to the static or dynamic layer's top left origin,
// factoring in the camera's vertical scroll
// Because Tiled can sometimes create an empty object if you don't populate it, not an empty array
// Loop through the data field in the JSON. This is a 2D array containing the tile indexes,
// one after the other. The indexes are relative to the tileset that contains the tile.
// In Weltmeister, 0 = no tile, but the Tilemap API expects -1 = no tile.
// A relative filepath to the source image (within Weltmeister) is used for the name
// Only add unique tilesets that have a valid name. Collision layers will have a blank name.
// Tiles are stored with an ID relative to the tileset, rather than a globally unique ID
// across all tilesets. Also, tilesets in Weltmeister have no margin or padding.
// go through each of the map data layers
// rows of tiles
// individual tiles
// find the relevant tileset
// Ensure that a tile's size matches its tileset
// if that tile type has any properties, add them to the tile object
// Interpret binaryString as an array of bytes representing little-endian encoded uint32 values.
// Can add extra properties here as needed
// Return a default group state object
// Values inherited from parent group
// Compute group layer x, y
// Compute next state inherited from group
// Parse the flip flags into something Phaser can use
// State inherited from a parent group
// Ensure recursion stack is not empty first
// Return to previous recursive state
// Get current layer and advance iterator
// Compute next state inherited from group
// Preserve current state before recursing
// Skip this layer OR 'recurse' (iterative style) into the group
// Map data will consist of: layers, objects, images, tilesets, sizes
// Object tiles
// Otherwise, assume it is a rectangle
// Modify inherited properties
// Base64 decode data if necessary. NOTE: uncompressed base64 only.
// Chunks for an infinite map
// Non-infinite map data
// This is an array containing the tile indexes, one after the other. -1 = no tile,
// everything else = the tile index (starting at 1 for Tiled, 0 for CSV) If the map
// contains multiple tilesets then the indexes are relative to that which the set starts
// from. Need to set which tileset in the cache = which tileset in the JSON, if you do this
// manually it means you can use the same map data but a new tileset.
// index, x, y, width, height
// Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal
// propeties into flipX, flipY and rotation
// Loop through the data field in the JSON.
// index, x, y, width, height
// Turning Tiled's FlippedHorizontal, FlippedVertical and FlippedAntiDiagonal
// propeties into flipX, flipY and rotation
// name, firstgid, width, height, margin, spacing, properties
// Tiled 1.2+
// Convert tileproperties.
// Convert objectgroup
// Copy animation data
// Copy tile `type` field
// (see https://doc.mapeditor.org/en/latest/manual/custom-properties/#typed-tiles).
// Sum up animation length.
// Tiled 1
// Properties stored per-tile in object with string indexes starting at "0"
// Object & terrain shapes stored per-tile in object with string indexes starting at "0"
// Parse the objects into Phaser format to match handling of other Tiled objects
// For a normal sliced tileset the row/count/size information is computed when updated.
// This is done (again) after the image is set.
// We've got a new Tileset, so set the lastgid into the previous one
// Tiled before v2020.09.09
// Tiled after v2020.09.09
// The wangid layout is north, northeast, east, southeast, etc.
// Sync with the TimeStep
// Delete old events
// Pool them?
// Clear the lists
// Use delta time to increase elapsed.
// Avoids needing to adjust for pause / resume.
// Automatically smoothed by TimeStep class.
// In testing accurate to +- 1ms!
// Limit it, in case it's checked in the callback
// Process the event
// Very short delay
// set is an object of key value pairs, apply them to target
// Count the number of incomplete events
// Timeline is complete when there are no incomplete events remaining
// This can happen when all events are complete (and not removed),
// or when all once events have been removed (events.length === 0 but totalComplete > 0)
// Start at the exact time given, based on elapsed time (i.e. x ms from the start of the Timeline)
// Start in x ms from whatever the current elapsed time is (i.e. x ms from now)
// Start in x ms from whatever the previous event's start time was (i.e. x ms after the previous event)
// Can also be set to -1 for an infinite loop (same as setting loop: true)
// Allow them to send an array of mixed instances and configs
// If we've got a negative delta, skip this step
// By not caching the length we can immediately update tweens added
// this frame (such as chained tweens)
// If Tween.update returns 'true' then it means it has completed,
// so move it to the destroy list
// Clean-up the 'toDestroy' list
// Remove it on the next frame
// Remove it immediately
// Default ease function
// Prepare ease function
// String based look-up
// 1) They specified it correctly
// Do some string manipulation to try and find it
// quad.in = Quad.easeIn
// quad.out = Quad.easeOut
// quad.inout = Quad.easeInOut
// Custom function
// No custom ease parameters?
// Return ease function
// Return ease function with custom ease parameters
// Default interpolation function
// Prepare interpolation function
// Return interpolation function
// First see if we have a props object
// Skip any property that starts with an underscore
// Skip any property that is in the ReservedProps list or that starts with an underscore
// The returned value sets what the property will be at the END of the Tween (usually called at the start of the Tween)
// The returned value sets what the property will be at the START of the Tween (usually called at the end of the Tween)
// What to set the property to the moment the TweenData is invoked
// props: {
// x: 400,
// y: 300
// }
// x: [ 400, 300, 200 ],
// y: [ 10, 500, 10 ]
// x: '+=400',
// y: '-=300',
// z: '*=2',
// w: '/=2',
// p: 'random(10, 100)' - random float
// p: 'int(10, 100)' - random int
// random(0.5, 3.45)
// int(10, 100)
// The same as setting just the getEnd function and no getStart
// props: {
// x: function (target, key, value, targetIndex, totalTargets, tween, tweenData) { return value + 50); },
// Called the moment Tween is active. The returned value sets the property on the target immediately.
// Called at the start of the Tween. The returned value sets what the property will be at the END of the Tween.
// Called at the end of the Tween. The returned value sets what the property will be at the START of the Tween.
// 'value' may still be a string, function or a number
// props: {
// x: { value: 400, ... },
// y: { value: 300, ... }
// }
// 'from' and 'to' may still be a string, function or a number
// x: { from: 400, to: 600 },
// y: { from: 300, to: 500 }
// Same as above, but the 'start' value is set immediately on the target
// x: { start: 400, to: 600 },
// y: { start: 300, to: 500 }
// 'start' value is set immediately, then it goes 'from' to 'to' during the tween
// x: { start: 200, from: 400, to: 600 },
// y: { start: 300, from: 300, to: 500 }
// If callback not set by the else if block above then set it here and return it
// var tween = this.tweens.addCounter({
// from: 100,
// to: 200,
// ... (normal tween properties)
// })
// Then use it in your game via:
// tween.getValue()
// Set the Callbacks
// Pre-calc the grid to save doing it for every TweenData update
// zero offset
// Create arrays of the Targets and the Properties. This Targets array should not be manipulated outside of this Tween.
// Default Tween values
// Loop through every property defined in the Tween, i.e.: props { x, y, alpha }
// Create 1 TweenData per target, per property
// Skip null or undefined targets
// Special-case for scale short-cut:
// Default TweenChain values
// Add in the Tweens
// Reset the delta so we always start progress from zero
// Function signature: target, key, value, index, total, tween
// calcDuration:
// Set t1 (duration + hold + yoyo)
// Set t2 (repeatDelay + duration + hold + yoyo)
// Total Duration
// Set the longest duration in the parent Tween
// Account for any extra time we got from the previous frame
// Custom
// Delay?
// RESERVED properties that a Tween config object uses
// completeDelay: The time the tween will wait before the onComplete event is dispatched once it has completed
// delay: The time the tween will wait before it first starts
// duration: The duration of the tween
// ease: The ease function used by the tween
// easeParams: The parameters to go with the ease function (if any)
// flipX: flip X the GameObject on tween end
// flipY: flip Y the GameObject on tween end
// hold: The time the tween will pause before running a yoyo
// loop: The time the tween will pause before starting either a yoyo or returning to the start for a repeat
// loopDelay:
// paused: Does the tween start in a paused state, or playing?
// props: The properties being tweened by the tween
// repeat: The number of times the tween will repeat itself (a value of 1 means the tween will play twice, as it repeated once)
// repeatDelay: The time the tween will pause for before starting a repeat. The tween holds in the start state.
// targets: The targets the tween is updating.
// yoyo: boolean - Does the tween reverse itself (yoyo) when it reaches the end?
// These two values are updated directly during TweenData.reset:
// Clamp duration to ensure we never divide by zero
// Reset the delta so we always start progress from zero
// Anything still running? If not, we're done
// This calls onCompleteHandler if this tween is over
// if nextState called onCompleteHandler then we're ready to be removed, unless we persist
// Remove it immediately
// The TweenChain.timeScale is applied within Tween.update, so doesn't need including here
// This tween has finished playback, so move to the next one
// If nextState called onCompleteHandler then it is ready to be removed, unless persist is set to true
// Bail out if we don't have a target to act upon
// All of the above have the ability to change the state, so put this in its own check
// Return TRUE if this TweenData still playing, otherwise FALSE
// 1 used to be INIT prior to 3.60
// 3 used to be OFFSET_DELAY prior to 3.60
// Tween specific (starts from 20 to cleanly allow extra TweenData consts in the future)
// Taken from klasse by mattdesl https://github.com/mattdesl/klasse
// This may be a lightweight object, OR it might be a property that was defined previously.
// For simple class descriptors we can just assume its NOT previously defined.
// This might be a regular property, or it may be a getter/setter the user defined in a class.
// If Extends is used, we will check its prototype to see if the final variable exists.
// Just skip the final property
// We cannot re-define a property that is configurable=false.
// So we will consider them final and throw an error. This is by
// default so it is clear to the developer what is happening.
// You can set ignoreFinals to true if you need to extend a class
// which has configurable=false; it will simply not re-define final properties.
// The variable name here dictates what we see in Chrome debugger
// Usually we should avoid 'delete' in V8 at all costs.
// However, its unlikely to make any performance difference
// here since we only call this on class creation (i.e. not object creation).
// For getOwnPropertyDescriptor to work, we need to act directly on the Extends (or Mixin)
// Grab the mixins, if they are specified...
// First, mixin if we can.
// Now we grab the actual definition which defines the overrides.
// NOOP
// There's nothing more we can do here, the array is full
// Fast path to avoid array mutation and iteration
// If we got this far, we have an array of items to insert
// Ensure all the items are unique
// Already exists in array, so remove it
// Anything left?
// Truncate to the limit
// item1 is already above item2
// Remove item1 from its current position
// Recalculate baseIndex after removal
// Insert item1 immediately after item2
// item1 is already below item2
// Remove
// Add in new location
// Remove
// Add in new location
// The element one above `item` in the array
// Endless repeat, so limit by max
// Work out how many repeats we need
// If we got this far, we have an array of items to remove
// Short-circuit when there's nothing to sort.
// Rather than dividing input, simply iterate chunks of 1, 2, 4, 8, etc.
// Chunks are the size of the left or right hand in merge sort.
// Stop when the left-hand covers all of the array.
// Step size / double chunk size.
// Bounds of the left and right chunks.
// Iterators over the left and right chunk.
// Iterate over pairs of chunks.
// Iterate both chunks in parallel.
// Compare the chunks.
// This works for a regular `sort()` compatible comparator,
// but also for a simple comparator like: `a > b`
// Nothing to compare, just flush what's left.
// Both iterators are at the chunk ends.
// Short-circuit when there's nothing to sort.
// This simply copies back if the result isn't in the original array, which happens on an odd number of passes.
// How long is the first row?
// Validate the rest of the rows are the same length
// Vertical translation
// Shift Up
// Shift Down
// Horizontal translation
// Use a lookup table to find the index.
// Is it a data uri? if so, strip the header away
// inObject is not an object
// Create an array or object to hold the values
// Recursively (deep) copy for nested objects, including arrays
// @param {boolean} deep - Perform a deep copy?
// @param {object} target - The target object to copy to.
// @return {object} The extended object.
// Handle a deep copy situation
// skip the boolean and the target
// extend Phaser if only one argument is passed
// Only deal with non-null/undefined values
// Extend the base object
// Prevent never-ending loop
// Recurse if we're merging plain objects or arrays
// Never move original objects, clone them
// Don't bring in undefined values
// Return the modified object
// Use for loop here so we can break early
// Yes parentA has a key property, let's carry on down
// Yes parentB has a key property, let's carry on down
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
// Yes it has a key property, let's carry on down